drm/i915: Move load time init of display/audio hooks earlier
[cascardo/linux.git] / drivers / gpu / drm / i915 / intel_display.c
1 /*
2  * Copyright © 2006-2007 Intel Corporation
3  *
4  * Permission is hereby granted, free of charge, to any person obtaining a
5  * copy of this software and associated documentation files (the "Software"),
6  * to deal in the Software without restriction, including without limitation
7  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
8  * and/or sell copies of the Software, and to permit persons to whom the
9  * Software is furnished to do so, subject to the following conditions:
10  *
11  * The above copyright notice and this permission notice (including the next
12  * paragraph) shall be included in all copies or substantial portions of the
13  * Software.
14  *
15  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
18  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
20  * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
21  * DEALINGS IN THE SOFTWARE.
22  *
23  * Authors:
24  *      Eric Anholt <eric@anholt.net>
25  */
26
27 #include <linux/dmi.h>
28 #include <linux/module.h>
29 #include <linux/input.h>
30 #include <linux/i2c.h>
31 #include <linux/kernel.h>
32 #include <linux/slab.h>
33 #include <linux/vgaarb.h>
34 #include <drm/drm_edid.h>
35 #include <drm/drmP.h>
36 #include "intel_drv.h"
37 #include <drm/i915_drm.h>
38 #include "i915_drv.h"
39 #include "i915_trace.h"
40 #include <drm/drm_atomic.h>
41 #include <drm/drm_atomic_helper.h>
42 #include <drm/drm_dp_helper.h>
43 #include <drm/drm_crtc_helper.h>
44 #include <drm/drm_plane_helper.h>
45 #include <drm/drm_rect.h>
46 #include <linux/dma_remapping.h>
47 #include <linux/reservation.h>
48 #include <linux/dma-buf.h>
49
50 /* Primary plane formats for gen <= 3 */
51 static const uint32_t i8xx_primary_formats[] = {
52         DRM_FORMAT_C8,
53         DRM_FORMAT_RGB565,
54         DRM_FORMAT_XRGB1555,
55         DRM_FORMAT_XRGB8888,
56 };
57
58 /* Primary plane formats for gen >= 4 */
59 static const uint32_t i965_primary_formats[] = {
60         DRM_FORMAT_C8,
61         DRM_FORMAT_RGB565,
62         DRM_FORMAT_XRGB8888,
63         DRM_FORMAT_XBGR8888,
64         DRM_FORMAT_XRGB2101010,
65         DRM_FORMAT_XBGR2101010,
66 };
67
68 static const uint32_t skl_primary_formats[] = {
69         DRM_FORMAT_C8,
70         DRM_FORMAT_RGB565,
71         DRM_FORMAT_XRGB8888,
72         DRM_FORMAT_XBGR8888,
73         DRM_FORMAT_ARGB8888,
74         DRM_FORMAT_ABGR8888,
75         DRM_FORMAT_XRGB2101010,
76         DRM_FORMAT_XBGR2101010,
77         DRM_FORMAT_YUYV,
78         DRM_FORMAT_YVYU,
79         DRM_FORMAT_UYVY,
80         DRM_FORMAT_VYUY,
81 };
82
83 /* Cursor formats */
84 static const uint32_t intel_cursor_formats[] = {
85         DRM_FORMAT_ARGB8888,
86 };
87
88 static void i9xx_crtc_clock_get(struct intel_crtc *crtc,
89                                 struct intel_crtc_state *pipe_config);
90 static void ironlake_pch_clock_get(struct intel_crtc *crtc,
91                                    struct intel_crtc_state *pipe_config);
92
93 static int intel_framebuffer_init(struct drm_device *dev,
94                                   struct intel_framebuffer *ifb,
95                                   struct drm_mode_fb_cmd2 *mode_cmd,
96                                   struct drm_i915_gem_object *obj);
97 static void i9xx_set_pipeconf(struct intel_crtc *intel_crtc);
98 static void intel_set_pipe_timings(struct intel_crtc *intel_crtc);
99 static void intel_cpu_transcoder_set_m_n(struct intel_crtc *crtc,
100                                          struct intel_link_m_n *m_n,
101                                          struct intel_link_m_n *m2_n2);
102 static void ironlake_set_pipeconf(struct drm_crtc *crtc);
103 static void haswell_set_pipeconf(struct drm_crtc *crtc);
104 static void intel_set_pipe_csc(struct drm_crtc *crtc);
105 static void vlv_prepare_pll(struct intel_crtc *crtc,
106                             const struct intel_crtc_state *pipe_config);
107 static void chv_prepare_pll(struct intel_crtc *crtc,
108                             const struct intel_crtc_state *pipe_config);
109 static void intel_begin_crtc_commit(struct drm_crtc *, struct drm_crtc_state *);
110 static void intel_finish_crtc_commit(struct drm_crtc *, struct drm_crtc_state *);
111 static void skl_init_scalers(struct drm_device *dev, struct intel_crtc *intel_crtc,
112         struct intel_crtc_state *crtc_state);
113 static int i9xx_get_refclk(const struct intel_crtc_state *crtc_state,
114                            int num_connectors);
115 static void skylake_pfit_enable(struct intel_crtc *crtc);
116 static void ironlake_pfit_disable(struct intel_crtc *crtc, bool force);
117 static void ironlake_pfit_enable(struct intel_crtc *crtc);
118 static void intel_modeset_setup_hw_state(struct drm_device *dev);
119 static void intel_pre_disable_primary_noatomic(struct drm_crtc *crtc);
120
121 typedef struct {
122         int     min, max;
123 } intel_range_t;
124
125 typedef struct {
126         int     dot_limit;
127         int     p2_slow, p2_fast;
128 } intel_p2_t;
129
130 typedef struct intel_limit intel_limit_t;
131 struct intel_limit {
132         intel_range_t   dot, vco, n, m, m1, m2, p, p1;
133         intel_p2_t          p2;
134 };
135
136 /* returns HPLL frequency in kHz */
137 static int valleyview_get_vco(struct drm_i915_private *dev_priv)
138 {
139         int hpll_freq, vco_freq[] = { 800, 1600, 2000, 2400 };
140
141         /* Obtain SKU information */
142         mutex_lock(&dev_priv->sb_lock);
143         hpll_freq = vlv_cck_read(dev_priv, CCK_FUSE_REG) &
144                 CCK_FUSE_HPLL_FREQ_MASK;
145         mutex_unlock(&dev_priv->sb_lock);
146
147         return vco_freq[hpll_freq] * 1000;
148 }
149
150 static int vlv_get_cck_clock_hpll(struct drm_i915_private *dev_priv,
151                                   const char *name, u32 reg)
152 {
153         u32 val;
154         int divider;
155
156         if (dev_priv->hpll_freq == 0)
157                 dev_priv->hpll_freq = valleyview_get_vco(dev_priv);
158
159         mutex_lock(&dev_priv->sb_lock);
160         val = vlv_cck_read(dev_priv, reg);
161         mutex_unlock(&dev_priv->sb_lock);
162
163         divider = val & CCK_FREQUENCY_VALUES;
164
165         WARN((val & CCK_FREQUENCY_STATUS) !=
166              (divider << CCK_FREQUENCY_STATUS_SHIFT),
167              "%s change in progress\n", name);
168
169         return DIV_ROUND_CLOSEST(dev_priv->hpll_freq << 1, divider + 1);
170 }
171
172 static int
173 intel_pch_rawclk(struct drm_i915_private *dev_priv)
174 {
175         return (I915_READ(PCH_RAWCLK_FREQ) & RAWCLK_FREQ_MASK) * 1000;
176 }
177
178 static int
179 intel_vlv_hrawclk(struct drm_i915_private *dev_priv)
180 {
181         return vlv_get_cck_clock_hpll(dev_priv, "hrawclk",
182                                       CCK_DISPLAY_REF_CLOCK_CONTROL);
183 }
184
185 static int
186 intel_g4x_hrawclk(struct drm_i915_private *dev_priv)
187 {
188         uint32_t clkcfg;
189
190         /* hrawclock is 1/4 the FSB frequency */
191         clkcfg = I915_READ(CLKCFG);
192         switch (clkcfg & CLKCFG_FSB_MASK) {
193         case CLKCFG_FSB_400:
194                 return 100000;
195         case CLKCFG_FSB_533:
196                 return 133333;
197         case CLKCFG_FSB_667:
198                 return 166667;
199         case CLKCFG_FSB_800:
200                 return 200000;
201         case CLKCFG_FSB_1067:
202                 return 266667;
203         case CLKCFG_FSB_1333:
204                 return 333333;
205         /* these two are just a guess; one of them might be right */
206         case CLKCFG_FSB_1600:
207         case CLKCFG_FSB_1600_ALT:
208                 return 400000;
209         default:
210                 return 133333;
211         }
212 }
213
214 static void intel_update_rawclk(struct drm_i915_private *dev_priv)
215 {
216         if (HAS_PCH_SPLIT(dev_priv))
217                 dev_priv->rawclk_freq = intel_pch_rawclk(dev_priv);
218         else if (IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv))
219                 dev_priv->rawclk_freq = intel_vlv_hrawclk(dev_priv);
220         else if (IS_G4X(dev_priv) || IS_PINEVIEW(dev_priv))
221                 dev_priv->rawclk_freq = intel_g4x_hrawclk(dev_priv);
222         else
223                 return; /* no rawclk on other platforms, or no need to know it */
224
225         DRM_DEBUG_DRIVER("rawclk rate: %d kHz\n", dev_priv->rawclk_freq);
226 }
227
228 static void intel_update_czclk(struct drm_i915_private *dev_priv)
229 {
230         if (!(IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv)))
231                 return;
232
233         dev_priv->czclk_freq = vlv_get_cck_clock_hpll(dev_priv, "czclk",
234                                                       CCK_CZ_CLOCK_CONTROL);
235
236         DRM_DEBUG_DRIVER("CZ clock rate: %d kHz\n", dev_priv->czclk_freq);
237 }
238
239 static inline u32 /* units of 100MHz */
240 intel_fdi_link_freq(struct drm_i915_private *dev_priv,
241                     const struct intel_crtc_state *pipe_config)
242 {
243         if (HAS_DDI(dev_priv))
244                 return pipe_config->port_clock; /* SPLL */
245         else if (IS_GEN5(dev_priv))
246                 return ((I915_READ(FDI_PLL_BIOS_0) & FDI_PLL_FB_CLOCK_MASK) + 2) * 10000;
247         else
248                 return 270000;
249 }
250
251 static const intel_limit_t intel_limits_i8xx_dac = {
252         .dot = { .min = 25000, .max = 350000 },
253         .vco = { .min = 908000, .max = 1512000 },
254         .n = { .min = 2, .max = 16 },
255         .m = { .min = 96, .max = 140 },
256         .m1 = { .min = 18, .max = 26 },
257         .m2 = { .min = 6, .max = 16 },
258         .p = { .min = 4, .max = 128 },
259         .p1 = { .min = 2, .max = 33 },
260         .p2 = { .dot_limit = 165000,
261                 .p2_slow = 4, .p2_fast = 2 },
262 };
263
264 static const intel_limit_t intel_limits_i8xx_dvo = {
265         .dot = { .min = 25000, .max = 350000 },
266         .vco = { .min = 908000, .max = 1512000 },
267         .n = { .min = 2, .max = 16 },
268         .m = { .min = 96, .max = 140 },
269         .m1 = { .min = 18, .max = 26 },
270         .m2 = { .min = 6, .max = 16 },
271         .p = { .min = 4, .max = 128 },
272         .p1 = { .min = 2, .max = 33 },
273         .p2 = { .dot_limit = 165000,
274                 .p2_slow = 4, .p2_fast = 4 },
275 };
276
277 static const intel_limit_t intel_limits_i8xx_lvds = {
278         .dot = { .min = 25000, .max = 350000 },
279         .vco = { .min = 908000, .max = 1512000 },
280         .n = { .min = 2, .max = 16 },
281         .m = { .min = 96, .max = 140 },
282         .m1 = { .min = 18, .max = 26 },
283         .m2 = { .min = 6, .max = 16 },
284         .p = { .min = 4, .max = 128 },
285         .p1 = { .min = 1, .max = 6 },
286         .p2 = { .dot_limit = 165000,
287                 .p2_slow = 14, .p2_fast = 7 },
288 };
289
290 static const intel_limit_t intel_limits_i9xx_sdvo = {
291         .dot = { .min = 20000, .max = 400000 },
292         .vco = { .min = 1400000, .max = 2800000 },
293         .n = { .min = 1, .max = 6 },
294         .m = { .min = 70, .max = 120 },
295         .m1 = { .min = 8, .max = 18 },
296         .m2 = { .min = 3, .max = 7 },
297         .p = { .min = 5, .max = 80 },
298         .p1 = { .min = 1, .max = 8 },
299         .p2 = { .dot_limit = 200000,
300                 .p2_slow = 10, .p2_fast = 5 },
301 };
302
303 static const intel_limit_t intel_limits_i9xx_lvds = {
304         .dot = { .min = 20000, .max = 400000 },
305         .vco = { .min = 1400000, .max = 2800000 },
306         .n = { .min = 1, .max = 6 },
307         .m = { .min = 70, .max = 120 },
308         .m1 = { .min = 8, .max = 18 },
309         .m2 = { .min = 3, .max = 7 },
310         .p = { .min = 7, .max = 98 },
311         .p1 = { .min = 1, .max = 8 },
312         .p2 = { .dot_limit = 112000,
313                 .p2_slow = 14, .p2_fast = 7 },
314 };
315
316
317 static const intel_limit_t intel_limits_g4x_sdvo = {
318         .dot = { .min = 25000, .max = 270000 },
319         .vco = { .min = 1750000, .max = 3500000},
320         .n = { .min = 1, .max = 4 },
321         .m = { .min = 104, .max = 138 },
322         .m1 = { .min = 17, .max = 23 },
323         .m2 = { .min = 5, .max = 11 },
324         .p = { .min = 10, .max = 30 },
325         .p1 = { .min = 1, .max = 3},
326         .p2 = { .dot_limit = 270000,
327                 .p2_slow = 10,
328                 .p2_fast = 10
329         },
330 };
331
332 static const intel_limit_t intel_limits_g4x_hdmi = {
333         .dot = { .min = 22000, .max = 400000 },
334         .vco = { .min = 1750000, .max = 3500000},
335         .n = { .min = 1, .max = 4 },
336         .m = { .min = 104, .max = 138 },
337         .m1 = { .min = 16, .max = 23 },
338         .m2 = { .min = 5, .max = 11 },
339         .p = { .min = 5, .max = 80 },
340         .p1 = { .min = 1, .max = 8},
341         .p2 = { .dot_limit = 165000,
342                 .p2_slow = 10, .p2_fast = 5 },
343 };
344
345 static const intel_limit_t intel_limits_g4x_single_channel_lvds = {
346         .dot = { .min = 20000, .max = 115000 },
347         .vco = { .min = 1750000, .max = 3500000 },
348         .n = { .min = 1, .max = 3 },
349         .m = { .min = 104, .max = 138 },
350         .m1 = { .min = 17, .max = 23 },
351         .m2 = { .min = 5, .max = 11 },
352         .p = { .min = 28, .max = 112 },
353         .p1 = { .min = 2, .max = 8 },
354         .p2 = { .dot_limit = 0,
355                 .p2_slow = 14, .p2_fast = 14
356         },
357 };
358
359 static const intel_limit_t intel_limits_g4x_dual_channel_lvds = {
360         .dot = { .min = 80000, .max = 224000 },
361         .vco = { .min = 1750000, .max = 3500000 },
362         .n = { .min = 1, .max = 3 },
363         .m = { .min = 104, .max = 138 },
364         .m1 = { .min = 17, .max = 23 },
365         .m2 = { .min = 5, .max = 11 },
366         .p = { .min = 14, .max = 42 },
367         .p1 = { .min = 2, .max = 6 },
368         .p2 = { .dot_limit = 0,
369                 .p2_slow = 7, .p2_fast = 7
370         },
371 };
372
373 static const intel_limit_t intel_limits_pineview_sdvo = {
374         .dot = { .min = 20000, .max = 400000},
375         .vco = { .min = 1700000, .max = 3500000 },
376         /* Pineview's Ncounter is a ring counter */
377         .n = { .min = 3, .max = 6 },
378         .m = { .min = 2, .max = 256 },
379         /* Pineview only has one combined m divider, which we treat as m2. */
380         .m1 = { .min = 0, .max = 0 },
381         .m2 = { .min = 0, .max = 254 },
382         .p = { .min = 5, .max = 80 },
383         .p1 = { .min = 1, .max = 8 },
384         .p2 = { .dot_limit = 200000,
385                 .p2_slow = 10, .p2_fast = 5 },
386 };
387
388 static const intel_limit_t intel_limits_pineview_lvds = {
389         .dot = { .min = 20000, .max = 400000 },
390         .vco = { .min = 1700000, .max = 3500000 },
391         .n = { .min = 3, .max = 6 },
392         .m = { .min = 2, .max = 256 },
393         .m1 = { .min = 0, .max = 0 },
394         .m2 = { .min = 0, .max = 254 },
395         .p = { .min = 7, .max = 112 },
396         .p1 = { .min = 1, .max = 8 },
397         .p2 = { .dot_limit = 112000,
398                 .p2_slow = 14, .p2_fast = 14 },
399 };
400
401 /* Ironlake / Sandybridge
402  *
403  * We calculate clock using (register_value + 2) for N/M1/M2, so here
404  * the range value for them is (actual_value - 2).
405  */
406 static const intel_limit_t intel_limits_ironlake_dac = {
407         .dot = { .min = 25000, .max = 350000 },
408         .vco = { .min = 1760000, .max = 3510000 },
409         .n = { .min = 1, .max = 5 },
410         .m = { .min = 79, .max = 127 },
411         .m1 = { .min = 12, .max = 22 },
412         .m2 = { .min = 5, .max = 9 },
413         .p = { .min = 5, .max = 80 },
414         .p1 = { .min = 1, .max = 8 },
415         .p2 = { .dot_limit = 225000,
416                 .p2_slow = 10, .p2_fast = 5 },
417 };
418
419 static const intel_limit_t intel_limits_ironlake_single_lvds = {
420         .dot = { .min = 25000, .max = 350000 },
421         .vco = { .min = 1760000, .max = 3510000 },
422         .n = { .min = 1, .max = 3 },
423         .m = { .min = 79, .max = 118 },
424         .m1 = { .min = 12, .max = 22 },
425         .m2 = { .min = 5, .max = 9 },
426         .p = { .min = 28, .max = 112 },
427         .p1 = { .min = 2, .max = 8 },
428         .p2 = { .dot_limit = 225000,
429                 .p2_slow = 14, .p2_fast = 14 },
430 };
431
432 static const intel_limit_t intel_limits_ironlake_dual_lvds = {
433         .dot = { .min = 25000, .max = 350000 },
434         .vco = { .min = 1760000, .max = 3510000 },
435         .n = { .min = 1, .max = 3 },
436         .m = { .min = 79, .max = 127 },
437         .m1 = { .min = 12, .max = 22 },
438         .m2 = { .min = 5, .max = 9 },
439         .p = { .min = 14, .max = 56 },
440         .p1 = { .min = 2, .max = 8 },
441         .p2 = { .dot_limit = 225000,
442                 .p2_slow = 7, .p2_fast = 7 },
443 };
444
445 /* LVDS 100mhz refclk limits. */
446 static const intel_limit_t intel_limits_ironlake_single_lvds_100m = {
447         .dot = { .min = 25000, .max = 350000 },
448         .vco = { .min = 1760000, .max = 3510000 },
449         .n = { .min = 1, .max = 2 },
450         .m = { .min = 79, .max = 126 },
451         .m1 = { .min = 12, .max = 22 },
452         .m2 = { .min = 5, .max = 9 },
453         .p = { .min = 28, .max = 112 },
454         .p1 = { .min = 2, .max = 8 },
455         .p2 = { .dot_limit = 225000,
456                 .p2_slow = 14, .p2_fast = 14 },
457 };
458
459 static const intel_limit_t intel_limits_ironlake_dual_lvds_100m = {
460         .dot = { .min = 25000, .max = 350000 },
461         .vco = { .min = 1760000, .max = 3510000 },
462         .n = { .min = 1, .max = 3 },
463         .m = { .min = 79, .max = 126 },
464         .m1 = { .min = 12, .max = 22 },
465         .m2 = { .min = 5, .max = 9 },
466         .p = { .min = 14, .max = 42 },
467         .p1 = { .min = 2, .max = 6 },
468         .p2 = { .dot_limit = 225000,
469                 .p2_slow = 7, .p2_fast = 7 },
470 };
471
472 static const intel_limit_t intel_limits_vlv = {
473          /*
474           * These are the data rate limits (measured in fast clocks)
475           * since those are the strictest limits we have. The fast
476           * clock and actual rate limits are more relaxed, so checking
477           * them would make no difference.
478           */
479         .dot = { .min = 25000 * 5, .max = 270000 * 5 },
480         .vco = { .min = 4000000, .max = 6000000 },
481         .n = { .min = 1, .max = 7 },
482         .m1 = { .min = 2, .max = 3 },
483         .m2 = { .min = 11, .max = 156 },
484         .p1 = { .min = 2, .max = 3 },
485         .p2 = { .p2_slow = 2, .p2_fast = 20 }, /* slow=min, fast=max */
486 };
487
488 static const intel_limit_t intel_limits_chv = {
489         /*
490          * These are the data rate limits (measured in fast clocks)
491          * since those are the strictest limits we have.  The fast
492          * clock and actual rate limits are more relaxed, so checking
493          * them would make no difference.
494          */
495         .dot = { .min = 25000 * 5, .max = 540000 * 5},
496         .vco = { .min = 4800000, .max = 6480000 },
497         .n = { .min = 1, .max = 1 },
498         .m1 = { .min = 2, .max = 2 },
499         .m2 = { .min = 24 << 22, .max = 175 << 22 },
500         .p1 = { .min = 2, .max = 4 },
501         .p2 = { .p2_slow = 1, .p2_fast = 14 },
502 };
503
504 static const intel_limit_t intel_limits_bxt = {
505         /* FIXME: find real dot limits */
506         .dot = { .min = 0, .max = INT_MAX },
507         .vco = { .min = 4800000, .max = 6700000 },
508         .n = { .min = 1, .max = 1 },
509         .m1 = { .min = 2, .max = 2 },
510         /* FIXME: find real m2 limits */
511         .m2 = { .min = 2 << 22, .max = 255 << 22 },
512         .p1 = { .min = 2, .max = 4 },
513         .p2 = { .p2_slow = 1, .p2_fast = 20 },
514 };
515
516 static bool
517 needs_modeset(struct drm_crtc_state *state)
518 {
519         return drm_atomic_crtc_needs_modeset(state);
520 }
521
522 /**
523  * Returns whether any output on the specified pipe is of the specified type
524  */
525 bool intel_pipe_has_type(struct intel_crtc *crtc, enum intel_output_type type)
526 {
527         struct drm_device *dev = crtc->base.dev;
528         struct intel_encoder *encoder;
529
530         for_each_encoder_on_crtc(dev, &crtc->base, encoder)
531                 if (encoder->type == type)
532                         return true;
533
534         return false;
535 }
536
537 /**
538  * Returns whether any output on the specified pipe will have the specified
539  * type after a staged modeset is complete, i.e., the same as
540  * intel_pipe_has_type() but looking at encoder->new_crtc instead of
541  * encoder->crtc.
542  */
543 static bool intel_pipe_will_have_type(const struct intel_crtc_state *crtc_state,
544                                       int type)
545 {
546         struct drm_atomic_state *state = crtc_state->base.state;
547         struct drm_connector *connector;
548         struct drm_connector_state *connector_state;
549         struct intel_encoder *encoder;
550         int i, num_connectors = 0;
551
552         for_each_connector_in_state(state, connector, connector_state, i) {
553                 if (connector_state->crtc != crtc_state->base.crtc)
554                         continue;
555
556                 num_connectors++;
557
558                 encoder = to_intel_encoder(connector_state->best_encoder);
559                 if (encoder->type == type)
560                         return true;
561         }
562
563         WARN_ON(num_connectors == 0);
564
565         return false;
566 }
567
568 static const intel_limit_t *
569 intel_ironlake_limit(struct intel_crtc_state *crtc_state, int refclk)
570 {
571         struct drm_device *dev = crtc_state->base.crtc->dev;
572         const intel_limit_t *limit;
573
574         if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_LVDS)) {
575                 if (intel_is_dual_link_lvds(dev)) {
576                         if (refclk == 100000)
577                                 limit = &intel_limits_ironlake_dual_lvds_100m;
578                         else
579                                 limit = &intel_limits_ironlake_dual_lvds;
580                 } else {
581                         if (refclk == 100000)
582                                 limit = &intel_limits_ironlake_single_lvds_100m;
583                         else
584                                 limit = &intel_limits_ironlake_single_lvds;
585                 }
586         } else
587                 limit = &intel_limits_ironlake_dac;
588
589         return limit;
590 }
591
592 static const intel_limit_t *
593 intel_g4x_limit(struct intel_crtc_state *crtc_state)
594 {
595         struct drm_device *dev = crtc_state->base.crtc->dev;
596         const intel_limit_t *limit;
597
598         if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_LVDS)) {
599                 if (intel_is_dual_link_lvds(dev))
600                         limit = &intel_limits_g4x_dual_channel_lvds;
601                 else
602                         limit = &intel_limits_g4x_single_channel_lvds;
603         } else if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_HDMI) ||
604                    intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_ANALOG)) {
605                 limit = &intel_limits_g4x_hdmi;
606         } else if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_SDVO)) {
607                 limit = &intel_limits_g4x_sdvo;
608         } else /* The option is for other outputs */
609                 limit = &intel_limits_i9xx_sdvo;
610
611         return limit;
612 }
613
614 static const intel_limit_t *
615 intel_limit(struct intel_crtc_state *crtc_state, int refclk)
616 {
617         struct drm_device *dev = crtc_state->base.crtc->dev;
618         const intel_limit_t *limit;
619
620         if (IS_BROXTON(dev))
621                 limit = &intel_limits_bxt;
622         else if (HAS_PCH_SPLIT(dev))
623                 limit = intel_ironlake_limit(crtc_state, refclk);
624         else if (IS_G4X(dev)) {
625                 limit = intel_g4x_limit(crtc_state);
626         } else if (IS_PINEVIEW(dev)) {
627                 if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_LVDS))
628                         limit = &intel_limits_pineview_lvds;
629                 else
630                         limit = &intel_limits_pineview_sdvo;
631         } else if (IS_CHERRYVIEW(dev)) {
632                 limit = &intel_limits_chv;
633         } else if (IS_VALLEYVIEW(dev)) {
634                 limit = &intel_limits_vlv;
635         } else if (!IS_GEN2(dev)) {
636                 if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_LVDS))
637                         limit = &intel_limits_i9xx_lvds;
638                 else
639                         limit = &intel_limits_i9xx_sdvo;
640         } else {
641                 if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_LVDS))
642                         limit = &intel_limits_i8xx_lvds;
643                 else if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_DVO))
644                         limit = &intel_limits_i8xx_dvo;
645                 else
646                         limit = &intel_limits_i8xx_dac;
647         }
648         return limit;
649 }
650
651 /*
652  * Platform specific helpers to calculate the port PLL loopback- (clock.m),
653  * and post-divider (clock.p) values, pre- (clock.vco) and post-divided fast
654  * (clock.dot) clock rates. This fast dot clock is fed to the port's IO logic.
655  * The helpers' return value is the rate of the clock that is fed to the
656  * display engine's pipe which can be the above fast dot clock rate or a
657  * divided-down version of it.
658  */
659 /* m1 is reserved as 0 in Pineview, n is a ring counter */
660 static int pnv_calc_dpll_params(int refclk, intel_clock_t *clock)
661 {
662         clock->m = clock->m2 + 2;
663         clock->p = clock->p1 * clock->p2;
664         if (WARN_ON(clock->n == 0 || clock->p == 0))
665                 return 0;
666         clock->vco = DIV_ROUND_CLOSEST(refclk * clock->m, clock->n);
667         clock->dot = DIV_ROUND_CLOSEST(clock->vco, clock->p);
668
669         return clock->dot;
670 }
671
672 static uint32_t i9xx_dpll_compute_m(struct dpll *dpll)
673 {
674         return 5 * (dpll->m1 + 2) + (dpll->m2 + 2);
675 }
676
677 static int i9xx_calc_dpll_params(int refclk, intel_clock_t *clock)
678 {
679         clock->m = i9xx_dpll_compute_m(clock);
680         clock->p = clock->p1 * clock->p2;
681         if (WARN_ON(clock->n + 2 == 0 || clock->p == 0))
682                 return 0;
683         clock->vco = DIV_ROUND_CLOSEST(refclk * clock->m, clock->n + 2);
684         clock->dot = DIV_ROUND_CLOSEST(clock->vco, clock->p);
685
686         return clock->dot;
687 }
688
689 static int vlv_calc_dpll_params(int refclk, intel_clock_t *clock)
690 {
691         clock->m = clock->m1 * clock->m2;
692         clock->p = clock->p1 * clock->p2;
693         if (WARN_ON(clock->n == 0 || clock->p == 0))
694                 return 0;
695         clock->vco = DIV_ROUND_CLOSEST(refclk * clock->m, clock->n);
696         clock->dot = DIV_ROUND_CLOSEST(clock->vco, clock->p);
697
698         return clock->dot / 5;
699 }
700
701 int chv_calc_dpll_params(int refclk, intel_clock_t *clock)
702 {
703         clock->m = clock->m1 * clock->m2;
704         clock->p = clock->p1 * clock->p2;
705         if (WARN_ON(clock->n == 0 || clock->p == 0))
706                 return 0;
707         clock->vco = DIV_ROUND_CLOSEST_ULL((uint64_t)refclk * clock->m,
708                         clock->n << 22);
709         clock->dot = DIV_ROUND_CLOSEST(clock->vco, clock->p);
710
711         return clock->dot / 5;
712 }
713
714 #define INTELPllInvalid(s)   do { /* DRM_DEBUG(s); */ return false; } while (0)
715 /**
716  * Returns whether the given set of divisors are valid for a given refclk with
717  * the given connectors.
718  */
719
720 static bool intel_PLL_is_valid(struct drm_device *dev,
721                                const intel_limit_t *limit,
722                                const intel_clock_t *clock)
723 {
724         if (clock->n   < limit->n.min   || limit->n.max   < clock->n)
725                 INTELPllInvalid("n out of range\n");
726         if (clock->p1  < limit->p1.min  || limit->p1.max  < clock->p1)
727                 INTELPllInvalid("p1 out of range\n");
728         if (clock->m2  < limit->m2.min  || limit->m2.max  < clock->m2)
729                 INTELPllInvalid("m2 out of range\n");
730         if (clock->m1  < limit->m1.min  || limit->m1.max  < clock->m1)
731                 INTELPllInvalid("m1 out of range\n");
732
733         if (!IS_PINEVIEW(dev) && !IS_VALLEYVIEW(dev) &&
734             !IS_CHERRYVIEW(dev) && !IS_BROXTON(dev))
735                 if (clock->m1 <= clock->m2)
736                         INTELPllInvalid("m1 <= m2\n");
737
738         if (!IS_VALLEYVIEW(dev) && !IS_CHERRYVIEW(dev) && !IS_BROXTON(dev)) {
739                 if (clock->p < limit->p.min || limit->p.max < clock->p)
740                         INTELPllInvalid("p out of range\n");
741                 if (clock->m < limit->m.min || limit->m.max < clock->m)
742                         INTELPllInvalid("m out of range\n");
743         }
744
745         if (clock->vco < limit->vco.min || limit->vco.max < clock->vco)
746                 INTELPllInvalid("vco out of range\n");
747         /* XXX: We may need to be checking "Dot clock" depending on the multiplier,
748          * connector, etc., rather than just a single range.
749          */
750         if (clock->dot < limit->dot.min || limit->dot.max < clock->dot)
751                 INTELPllInvalid("dot out of range\n");
752
753         return true;
754 }
755
756 static int
757 i9xx_select_p2_div(const intel_limit_t *limit,
758                    const struct intel_crtc_state *crtc_state,
759                    int target)
760 {
761         struct drm_device *dev = crtc_state->base.crtc->dev;
762
763         if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_LVDS)) {
764                 /*
765                  * For LVDS just rely on its current settings for dual-channel.
766                  * We haven't figured out how to reliably set up different
767                  * single/dual channel state, if we even can.
768                  */
769                 if (intel_is_dual_link_lvds(dev))
770                         return limit->p2.p2_fast;
771                 else
772                         return limit->p2.p2_slow;
773         } else {
774                 if (target < limit->p2.dot_limit)
775                         return limit->p2.p2_slow;
776                 else
777                         return limit->p2.p2_fast;
778         }
779 }
780
781 static bool
782 i9xx_find_best_dpll(const intel_limit_t *limit,
783                     struct intel_crtc_state *crtc_state,
784                     int target, int refclk, intel_clock_t *match_clock,
785                     intel_clock_t *best_clock)
786 {
787         struct drm_device *dev = crtc_state->base.crtc->dev;
788         intel_clock_t clock;
789         int err = target;
790
791         memset(best_clock, 0, sizeof(*best_clock));
792
793         clock.p2 = i9xx_select_p2_div(limit, crtc_state, target);
794
795         for (clock.m1 = limit->m1.min; clock.m1 <= limit->m1.max;
796              clock.m1++) {
797                 for (clock.m2 = limit->m2.min;
798                      clock.m2 <= limit->m2.max; clock.m2++) {
799                         if (clock.m2 >= clock.m1)
800                                 break;
801                         for (clock.n = limit->n.min;
802                              clock.n <= limit->n.max; clock.n++) {
803                                 for (clock.p1 = limit->p1.min;
804                                         clock.p1 <= limit->p1.max; clock.p1++) {
805                                         int this_err;
806
807                                         i9xx_calc_dpll_params(refclk, &clock);
808                                         if (!intel_PLL_is_valid(dev, limit,
809                                                                 &clock))
810                                                 continue;
811                                         if (match_clock &&
812                                             clock.p != match_clock->p)
813                                                 continue;
814
815                                         this_err = abs(clock.dot - target);
816                                         if (this_err < err) {
817                                                 *best_clock = clock;
818                                                 err = this_err;
819                                         }
820                                 }
821                         }
822                 }
823         }
824
825         return (err != target);
826 }
827
828 static bool
829 pnv_find_best_dpll(const intel_limit_t *limit,
830                    struct intel_crtc_state *crtc_state,
831                    int target, int refclk, intel_clock_t *match_clock,
832                    intel_clock_t *best_clock)
833 {
834         struct drm_device *dev = crtc_state->base.crtc->dev;
835         intel_clock_t clock;
836         int err = target;
837
838         memset(best_clock, 0, sizeof(*best_clock));
839
840         clock.p2 = i9xx_select_p2_div(limit, crtc_state, target);
841
842         for (clock.m1 = limit->m1.min; clock.m1 <= limit->m1.max;
843              clock.m1++) {
844                 for (clock.m2 = limit->m2.min;
845                      clock.m2 <= limit->m2.max; clock.m2++) {
846                         for (clock.n = limit->n.min;
847                              clock.n <= limit->n.max; clock.n++) {
848                                 for (clock.p1 = limit->p1.min;
849                                         clock.p1 <= limit->p1.max; clock.p1++) {
850                                         int this_err;
851
852                                         pnv_calc_dpll_params(refclk, &clock);
853                                         if (!intel_PLL_is_valid(dev, limit,
854                                                                 &clock))
855                                                 continue;
856                                         if (match_clock &&
857                                             clock.p != match_clock->p)
858                                                 continue;
859
860                                         this_err = abs(clock.dot - target);
861                                         if (this_err < err) {
862                                                 *best_clock = clock;
863                                                 err = this_err;
864                                         }
865                                 }
866                         }
867                 }
868         }
869
870         return (err != target);
871 }
872
873 static bool
874 g4x_find_best_dpll(const intel_limit_t *limit,
875                    struct intel_crtc_state *crtc_state,
876                    int target, int refclk, intel_clock_t *match_clock,
877                    intel_clock_t *best_clock)
878 {
879         struct drm_device *dev = crtc_state->base.crtc->dev;
880         intel_clock_t clock;
881         int max_n;
882         bool found = false;
883         /* approximately equals target * 0.00585 */
884         int err_most = (target >> 8) + (target >> 9);
885
886         memset(best_clock, 0, sizeof(*best_clock));
887
888         clock.p2 = i9xx_select_p2_div(limit, crtc_state, target);
889
890         max_n = limit->n.max;
891         /* based on hardware requirement, prefer smaller n to precision */
892         for (clock.n = limit->n.min; clock.n <= max_n; clock.n++) {
893                 /* based on hardware requirement, prefere larger m1,m2 */
894                 for (clock.m1 = limit->m1.max;
895                      clock.m1 >= limit->m1.min; clock.m1--) {
896                         for (clock.m2 = limit->m2.max;
897                              clock.m2 >= limit->m2.min; clock.m2--) {
898                                 for (clock.p1 = limit->p1.max;
899                                      clock.p1 >= limit->p1.min; clock.p1--) {
900                                         int this_err;
901
902                                         i9xx_calc_dpll_params(refclk, &clock);
903                                         if (!intel_PLL_is_valid(dev, limit,
904                                                                 &clock))
905                                                 continue;
906
907                                         this_err = abs(clock.dot - target);
908                                         if (this_err < err_most) {
909                                                 *best_clock = clock;
910                                                 err_most = this_err;
911                                                 max_n = clock.n;
912                                                 found = true;
913                                         }
914                                 }
915                         }
916                 }
917         }
918         return found;
919 }
920
921 /*
922  * Check if the calculated PLL configuration is more optimal compared to the
923  * best configuration and error found so far. Return the calculated error.
924  */
925 static bool vlv_PLL_is_optimal(struct drm_device *dev, int target_freq,
926                                const intel_clock_t *calculated_clock,
927                                const intel_clock_t *best_clock,
928                                unsigned int best_error_ppm,
929                                unsigned int *error_ppm)
930 {
931         /*
932          * For CHV ignore the error and consider only the P value.
933          * Prefer a bigger P value based on HW requirements.
934          */
935         if (IS_CHERRYVIEW(dev)) {
936                 *error_ppm = 0;
937
938                 return calculated_clock->p > best_clock->p;
939         }
940
941         if (WARN_ON_ONCE(!target_freq))
942                 return false;
943
944         *error_ppm = div_u64(1000000ULL *
945                                 abs(target_freq - calculated_clock->dot),
946                              target_freq);
947         /*
948          * Prefer a better P value over a better (smaller) error if the error
949          * is small. Ensure this preference for future configurations too by
950          * setting the error to 0.
951          */
952         if (*error_ppm < 100 && calculated_clock->p > best_clock->p) {
953                 *error_ppm = 0;
954
955                 return true;
956         }
957
958         return *error_ppm + 10 < best_error_ppm;
959 }
960
961 static bool
962 vlv_find_best_dpll(const intel_limit_t *limit,
963                    struct intel_crtc_state *crtc_state,
964                    int target, int refclk, intel_clock_t *match_clock,
965                    intel_clock_t *best_clock)
966 {
967         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
968         struct drm_device *dev = crtc->base.dev;
969         intel_clock_t clock;
970         unsigned int bestppm = 1000000;
971         /* min update 19.2 MHz */
972         int max_n = min(limit->n.max, refclk / 19200);
973         bool found = false;
974
975         target *= 5; /* fast clock */
976
977         memset(best_clock, 0, sizeof(*best_clock));
978
979         /* based on hardware requirement, prefer smaller n to precision */
980         for (clock.n = limit->n.min; clock.n <= max_n; clock.n++) {
981                 for (clock.p1 = limit->p1.max; clock.p1 >= limit->p1.min; clock.p1--) {
982                         for (clock.p2 = limit->p2.p2_fast; clock.p2 >= limit->p2.p2_slow;
983                              clock.p2 -= clock.p2 > 10 ? 2 : 1) {
984                                 clock.p = clock.p1 * clock.p2;
985                                 /* based on hardware requirement, prefer bigger m1,m2 values */
986                                 for (clock.m1 = limit->m1.min; clock.m1 <= limit->m1.max; clock.m1++) {
987                                         unsigned int ppm;
988
989                                         clock.m2 = DIV_ROUND_CLOSEST(target * clock.p * clock.n,
990                                                                      refclk * clock.m1);
991
992                                         vlv_calc_dpll_params(refclk, &clock);
993
994                                         if (!intel_PLL_is_valid(dev, limit,
995                                                                 &clock))
996                                                 continue;
997
998                                         if (!vlv_PLL_is_optimal(dev, target,
999                                                                 &clock,
1000                                                                 best_clock,
1001                                                                 bestppm, &ppm))
1002                                                 continue;
1003
1004                                         *best_clock = clock;
1005                                         bestppm = ppm;
1006                                         found = true;
1007                                 }
1008                         }
1009                 }
1010         }
1011
1012         return found;
1013 }
1014
1015 static bool
1016 chv_find_best_dpll(const intel_limit_t *limit,
1017                    struct intel_crtc_state *crtc_state,
1018                    int target, int refclk, intel_clock_t *match_clock,
1019                    intel_clock_t *best_clock)
1020 {
1021         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
1022         struct drm_device *dev = crtc->base.dev;
1023         unsigned int best_error_ppm;
1024         intel_clock_t clock;
1025         uint64_t m2;
1026         int found = false;
1027
1028         memset(best_clock, 0, sizeof(*best_clock));
1029         best_error_ppm = 1000000;
1030
1031         /*
1032          * Based on hardware doc, the n always set to 1, and m1 always
1033          * set to 2.  If requires to support 200Mhz refclk, we need to
1034          * revisit this because n may not 1 anymore.
1035          */
1036         clock.n = 1, clock.m1 = 2;
1037         target *= 5;    /* fast clock */
1038
1039         for (clock.p1 = limit->p1.max; clock.p1 >= limit->p1.min; clock.p1--) {
1040                 for (clock.p2 = limit->p2.p2_fast;
1041                                 clock.p2 >= limit->p2.p2_slow;
1042                                 clock.p2 -= clock.p2 > 10 ? 2 : 1) {
1043                         unsigned int error_ppm;
1044
1045                         clock.p = clock.p1 * clock.p2;
1046
1047                         m2 = DIV_ROUND_CLOSEST_ULL(((uint64_t)target * clock.p *
1048                                         clock.n) << 22, refclk * clock.m1);
1049
1050                         if (m2 > INT_MAX/clock.m1)
1051                                 continue;
1052
1053                         clock.m2 = m2;
1054
1055                         chv_calc_dpll_params(refclk, &clock);
1056
1057                         if (!intel_PLL_is_valid(dev, limit, &clock))
1058                                 continue;
1059
1060                         if (!vlv_PLL_is_optimal(dev, target, &clock, best_clock,
1061                                                 best_error_ppm, &error_ppm))
1062                                 continue;
1063
1064                         *best_clock = clock;
1065                         best_error_ppm = error_ppm;
1066                         found = true;
1067                 }
1068         }
1069
1070         return found;
1071 }
1072
1073 bool bxt_find_best_dpll(struct intel_crtc_state *crtc_state, int target_clock,
1074                         intel_clock_t *best_clock)
1075 {
1076         int refclk = i9xx_get_refclk(crtc_state, 0);
1077
1078         return chv_find_best_dpll(intel_limit(crtc_state, refclk), crtc_state,
1079                                   target_clock, refclk, NULL, best_clock);
1080 }
1081
1082 bool intel_crtc_active(struct drm_crtc *crtc)
1083 {
1084         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
1085
1086         /* Be paranoid as we can arrive here with only partial
1087          * state retrieved from the hardware during setup.
1088          *
1089          * We can ditch the adjusted_mode.crtc_clock check as soon
1090          * as Haswell has gained clock readout/fastboot support.
1091          *
1092          * We can ditch the crtc->primary->fb check as soon as we can
1093          * properly reconstruct framebuffers.
1094          *
1095          * FIXME: The intel_crtc->active here should be switched to
1096          * crtc->state->active once we have proper CRTC states wired up
1097          * for atomic.
1098          */
1099         return intel_crtc->active && crtc->primary->state->fb &&
1100                 intel_crtc->config->base.adjusted_mode.crtc_clock;
1101 }
1102
1103 enum transcoder intel_pipe_to_cpu_transcoder(struct drm_i915_private *dev_priv,
1104                                              enum pipe pipe)
1105 {
1106         struct drm_crtc *crtc = dev_priv->pipe_to_crtc_mapping[pipe];
1107         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
1108
1109         return intel_crtc->config->cpu_transcoder;
1110 }
1111
1112 static bool pipe_dsl_stopped(struct drm_device *dev, enum pipe pipe)
1113 {
1114         struct drm_i915_private *dev_priv = dev->dev_private;
1115         i915_reg_t reg = PIPEDSL(pipe);
1116         u32 line1, line2;
1117         u32 line_mask;
1118
1119         if (IS_GEN2(dev))
1120                 line_mask = DSL_LINEMASK_GEN2;
1121         else
1122                 line_mask = DSL_LINEMASK_GEN3;
1123
1124         line1 = I915_READ(reg) & line_mask;
1125         msleep(5);
1126         line2 = I915_READ(reg) & line_mask;
1127
1128         return line1 == line2;
1129 }
1130
1131 /*
1132  * intel_wait_for_pipe_off - wait for pipe to turn off
1133  * @crtc: crtc whose pipe to wait for
1134  *
1135  * After disabling a pipe, we can't wait for vblank in the usual way,
1136  * spinning on the vblank interrupt status bit, since we won't actually
1137  * see an interrupt when the pipe is disabled.
1138  *
1139  * On Gen4 and above:
1140  *   wait for the pipe register state bit to turn off
1141  *
1142  * Otherwise:
1143  *   wait for the display line value to settle (it usually
1144  *   ends up stopping at the start of the next frame).
1145  *
1146  */
1147 static void intel_wait_for_pipe_off(struct intel_crtc *crtc)
1148 {
1149         struct drm_device *dev = crtc->base.dev;
1150         struct drm_i915_private *dev_priv = dev->dev_private;
1151         enum transcoder cpu_transcoder = crtc->config->cpu_transcoder;
1152         enum pipe pipe = crtc->pipe;
1153
1154         if (INTEL_INFO(dev)->gen >= 4) {
1155                 i915_reg_t reg = PIPECONF(cpu_transcoder);
1156
1157                 /* Wait for the Pipe State to go off */
1158                 if (wait_for((I915_READ(reg) & I965_PIPECONF_ACTIVE) == 0,
1159                              100))
1160                         WARN(1, "pipe_off wait timed out\n");
1161         } else {
1162                 /* Wait for the display line to settle */
1163                 if (wait_for(pipe_dsl_stopped(dev, pipe), 100))
1164                         WARN(1, "pipe_off wait timed out\n");
1165         }
1166 }
1167
1168 /* Only for pre-ILK configs */
1169 void assert_pll(struct drm_i915_private *dev_priv,
1170                 enum pipe pipe, bool state)
1171 {
1172         u32 val;
1173         bool cur_state;
1174
1175         val = I915_READ(DPLL(pipe));
1176         cur_state = !!(val & DPLL_VCO_ENABLE);
1177         I915_STATE_WARN(cur_state != state,
1178              "PLL state assertion failure (expected %s, current %s)\n",
1179                         onoff(state), onoff(cur_state));
1180 }
1181
1182 /* XXX: the dsi pll is shared between MIPI DSI ports */
1183 static void assert_dsi_pll(struct drm_i915_private *dev_priv, bool state)
1184 {
1185         u32 val;
1186         bool cur_state;
1187
1188         mutex_lock(&dev_priv->sb_lock);
1189         val = vlv_cck_read(dev_priv, CCK_REG_DSI_PLL_CONTROL);
1190         mutex_unlock(&dev_priv->sb_lock);
1191
1192         cur_state = val & DSI_PLL_VCO_EN;
1193         I915_STATE_WARN(cur_state != state,
1194              "DSI PLL state assertion failure (expected %s, current %s)\n",
1195                         onoff(state), onoff(cur_state));
1196 }
1197 #define assert_dsi_pll_enabled(d) assert_dsi_pll(d, true)
1198 #define assert_dsi_pll_disabled(d) assert_dsi_pll(d, false)
1199
1200 static void assert_fdi_tx(struct drm_i915_private *dev_priv,
1201                           enum pipe pipe, bool state)
1202 {
1203         bool cur_state;
1204         enum transcoder cpu_transcoder = intel_pipe_to_cpu_transcoder(dev_priv,
1205                                                                       pipe);
1206
1207         if (HAS_DDI(dev_priv->dev)) {
1208                 /* DDI does not have a specific FDI_TX register */
1209                 u32 val = I915_READ(TRANS_DDI_FUNC_CTL(cpu_transcoder));
1210                 cur_state = !!(val & TRANS_DDI_FUNC_ENABLE);
1211         } else {
1212                 u32 val = I915_READ(FDI_TX_CTL(pipe));
1213                 cur_state = !!(val & FDI_TX_ENABLE);
1214         }
1215         I915_STATE_WARN(cur_state != state,
1216              "FDI TX state assertion failure (expected %s, current %s)\n",
1217                         onoff(state), onoff(cur_state));
1218 }
1219 #define assert_fdi_tx_enabled(d, p) assert_fdi_tx(d, p, true)
1220 #define assert_fdi_tx_disabled(d, p) assert_fdi_tx(d, p, false)
1221
1222 static void assert_fdi_rx(struct drm_i915_private *dev_priv,
1223                           enum pipe pipe, bool state)
1224 {
1225         u32 val;
1226         bool cur_state;
1227
1228         val = I915_READ(FDI_RX_CTL(pipe));
1229         cur_state = !!(val & FDI_RX_ENABLE);
1230         I915_STATE_WARN(cur_state != state,
1231              "FDI RX state assertion failure (expected %s, current %s)\n",
1232                         onoff(state), onoff(cur_state));
1233 }
1234 #define assert_fdi_rx_enabled(d, p) assert_fdi_rx(d, p, true)
1235 #define assert_fdi_rx_disabled(d, p) assert_fdi_rx(d, p, false)
1236
1237 static void assert_fdi_tx_pll_enabled(struct drm_i915_private *dev_priv,
1238                                       enum pipe pipe)
1239 {
1240         u32 val;
1241
1242         /* ILK FDI PLL is always enabled */
1243         if (INTEL_INFO(dev_priv->dev)->gen == 5)
1244                 return;
1245
1246         /* On Haswell, DDI ports are responsible for the FDI PLL setup */
1247         if (HAS_DDI(dev_priv->dev))
1248                 return;
1249
1250         val = I915_READ(FDI_TX_CTL(pipe));
1251         I915_STATE_WARN(!(val & FDI_TX_PLL_ENABLE), "FDI TX PLL assertion failure, should be active but is disabled\n");
1252 }
1253
1254 void assert_fdi_rx_pll(struct drm_i915_private *dev_priv,
1255                        enum pipe pipe, bool state)
1256 {
1257         u32 val;
1258         bool cur_state;
1259
1260         val = I915_READ(FDI_RX_CTL(pipe));
1261         cur_state = !!(val & FDI_RX_PLL_ENABLE);
1262         I915_STATE_WARN(cur_state != state,
1263              "FDI RX PLL assertion failure (expected %s, current %s)\n",
1264                         onoff(state), onoff(cur_state));
1265 }
1266
1267 void assert_panel_unlocked(struct drm_i915_private *dev_priv,
1268                            enum pipe pipe)
1269 {
1270         struct drm_device *dev = dev_priv->dev;
1271         i915_reg_t pp_reg;
1272         u32 val;
1273         enum pipe panel_pipe = PIPE_A;
1274         bool locked = true;
1275
1276         if (WARN_ON(HAS_DDI(dev)))
1277                 return;
1278
1279         if (HAS_PCH_SPLIT(dev)) {
1280                 u32 port_sel;
1281
1282                 pp_reg = PCH_PP_CONTROL;
1283                 port_sel = I915_READ(PCH_PP_ON_DELAYS) & PANEL_PORT_SELECT_MASK;
1284
1285                 if (port_sel == PANEL_PORT_SELECT_LVDS &&
1286                     I915_READ(PCH_LVDS) & LVDS_PIPEB_SELECT)
1287                         panel_pipe = PIPE_B;
1288                 /* XXX: else fix for eDP */
1289         } else if (IS_VALLEYVIEW(dev) || IS_CHERRYVIEW(dev)) {
1290                 /* presumably write lock depends on pipe, not port select */
1291                 pp_reg = VLV_PIPE_PP_CONTROL(pipe);
1292                 panel_pipe = pipe;
1293         } else {
1294                 pp_reg = PP_CONTROL;
1295                 if (I915_READ(LVDS) & LVDS_PIPEB_SELECT)
1296                         panel_pipe = PIPE_B;
1297         }
1298
1299         val = I915_READ(pp_reg);
1300         if (!(val & PANEL_POWER_ON) ||
1301             ((val & PANEL_UNLOCK_MASK) == PANEL_UNLOCK_REGS))
1302                 locked = false;
1303
1304         I915_STATE_WARN(panel_pipe == pipe && locked,
1305              "panel assertion failure, pipe %c regs locked\n",
1306              pipe_name(pipe));
1307 }
1308
1309 static void assert_cursor(struct drm_i915_private *dev_priv,
1310                           enum pipe pipe, bool state)
1311 {
1312         struct drm_device *dev = dev_priv->dev;
1313         bool cur_state;
1314
1315         if (IS_845G(dev) || IS_I865G(dev))
1316                 cur_state = I915_READ(CURCNTR(PIPE_A)) & CURSOR_ENABLE;
1317         else
1318                 cur_state = I915_READ(CURCNTR(pipe)) & CURSOR_MODE;
1319
1320         I915_STATE_WARN(cur_state != state,
1321              "cursor on pipe %c assertion failure (expected %s, current %s)\n",
1322                         pipe_name(pipe), onoff(state), onoff(cur_state));
1323 }
1324 #define assert_cursor_enabled(d, p) assert_cursor(d, p, true)
1325 #define assert_cursor_disabled(d, p) assert_cursor(d, p, false)
1326
1327 void assert_pipe(struct drm_i915_private *dev_priv,
1328                  enum pipe pipe, bool state)
1329 {
1330         bool cur_state;
1331         enum transcoder cpu_transcoder = intel_pipe_to_cpu_transcoder(dev_priv,
1332                                                                       pipe);
1333         enum intel_display_power_domain power_domain;
1334
1335         /* if we need the pipe quirk it must be always on */
1336         if ((pipe == PIPE_A && dev_priv->quirks & QUIRK_PIPEA_FORCE) ||
1337             (pipe == PIPE_B && dev_priv->quirks & QUIRK_PIPEB_FORCE))
1338                 state = true;
1339
1340         power_domain = POWER_DOMAIN_TRANSCODER(cpu_transcoder);
1341         if (intel_display_power_get_if_enabled(dev_priv, power_domain)) {
1342                 u32 val = I915_READ(PIPECONF(cpu_transcoder));
1343                 cur_state = !!(val & PIPECONF_ENABLE);
1344
1345                 intel_display_power_put(dev_priv, power_domain);
1346         } else {
1347                 cur_state = false;
1348         }
1349
1350         I915_STATE_WARN(cur_state != state,
1351              "pipe %c assertion failure (expected %s, current %s)\n",
1352                         pipe_name(pipe), onoff(state), onoff(cur_state));
1353 }
1354
1355 static void assert_plane(struct drm_i915_private *dev_priv,
1356                          enum plane plane, bool state)
1357 {
1358         u32 val;
1359         bool cur_state;
1360
1361         val = I915_READ(DSPCNTR(plane));
1362         cur_state = !!(val & DISPLAY_PLANE_ENABLE);
1363         I915_STATE_WARN(cur_state != state,
1364              "plane %c assertion failure (expected %s, current %s)\n",
1365                         plane_name(plane), onoff(state), onoff(cur_state));
1366 }
1367
1368 #define assert_plane_enabled(d, p) assert_plane(d, p, true)
1369 #define assert_plane_disabled(d, p) assert_plane(d, p, false)
1370
1371 static void assert_planes_disabled(struct drm_i915_private *dev_priv,
1372                                    enum pipe pipe)
1373 {
1374         struct drm_device *dev = dev_priv->dev;
1375         int i;
1376
1377         /* Primary planes are fixed to pipes on gen4+ */
1378         if (INTEL_INFO(dev)->gen >= 4) {
1379                 u32 val = I915_READ(DSPCNTR(pipe));
1380                 I915_STATE_WARN(val & DISPLAY_PLANE_ENABLE,
1381                      "plane %c assertion failure, should be disabled but not\n",
1382                      plane_name(pipe));
1383                 return;
1384         }
1385
1386         /* Need to check both planes against the pipe */
1387         for_each_pipe(dev_priv, i) {
1388                 u32 val = I915_READ(DSPCNTR(i));
1389                 enum pipe cur_pipe = (val & DISPPLANE_SEL_PIPE_MASK) >>
1390                         DISPPLANE_SEL_PIPE_SHIFT;
1391                 I915_STATE_WARN((val & DISPLAY_PLANE_ENABLE) && pipe == cur_pipe,
1392                      "plane %c assertion failure, should be off on pipe %c but is still active\n",
1393                      plane_name(i), pipe_name(pipe));
1394         }
1395 }
1396
1397 static void assert_sprites_disabled(struct drm_i915_private *dev_priv,
1398                                     enum pipe pipe)
1399 {
1400         struct drm_device *dev = dev_priv->dev;
1401         int sprite;
1402
1403         if (INTEL_INFO(dev)->gen >= 9) {
1404                 for_each_sprite(dev_priv, pipe, sprite) {
1405                         u32 val = I915_READ(PLANE_CTL(pipe, sprite));
1406                         I915_STATE_WARN(val & PLANE_CTL_ENABLE,
1407                              "plane %d assertion failure, should be off on pipe %c but is still active\n",
1408                              sprite, pipe_name(pipe));
1409                 }
1410         } else if (IS_VALLEYVIEW(dev) || IS_CHERRYVIEW(dev)) {
1411                 for_each_sprite(dev_priv, pipe, sprite) {
1412                         u32 val = I915_READ(SPCNTR(pipe, sprite));
1413                         I915_STATE_WARN(val & SP_ENABLE,
1414                              "sprite %c assertion failure, should be off on pipe %c but is still active\n",
1415                              sprite_name(pipe, sprite), pipe_name(pipe));
1416                 }
1417         } else if (INTEL_INFO(dev)->gen >= 7) {
1418                 u32 val = I915_READ(SPRCTL(pipe));
1419                 I915_STATE_WARN(val & SPRITE_ENABLE,
1420                      "sprite %c assertion failure, should be off on pipe %c but is still active\n",
1421                      plane_name(pipe), pipe_name(pipe));
1422         } else if (INTEL_INFO(dev)->gen >= 5) {
1423                 u32 val = I915_READ(DVSCNTR(pipe));
1424                 I915_STATE_WARN(val & DVS_ENABLE,
1425                      "sprite %c assertion failure, should be off on pipe %c but is still active\n",
1426                      plane_name(pipe), pipe_name(pipe));
1427         }
1428 }
1429
1430 static void assert_vblank_disabled(struct drm_crtc *crtc)
1431 {
1432         if (I915_STATE_WARN_ON(drm_crtc_vblank_get(crtc) == 0))
1433                 drm_crtc_vblank_put(crtc);
1434 }
1435
1436 void assert_pch_transcoder_disabled(struct drm_i915_private *dev_priv,
1437                                     enum pipe pipe)
1438 {
1439         u32 val;
1440         bool enabled;
1441
1442         val = I915_READ(PCH_TRANSCONF(pipe));
1443         enabled = !!(val & TRANS_ENABLE);
1444         I915_STATE_WARN(enabled,
1445              "transcoder assertion failed, should be off on pipe %c but is still active\n",
1446              pipe_name(pipe));
1447 }
1448
1449 static bool dp_pipe_enabled(struct drm_i915_private *dev_priv,
1450                             enum pipe pipe, u32 port_sel, u32 val)
1451 {
1452         if ((val & DP_PORT_EN) == 0)
1453                 return false;
1454
1455         if (HAS_PCH_CPT(dev_priv->dev)) {
1456                 u32 trans_dp_ctl = I915_READ(TRANS_DP_CTL(pipe));
1457                 if ((trans_dp_ctl & TRANS_DP_PORT_SEL_MASK) != port_sel)
1458                         return false;
1459         } else if (IS_CHERRYVIEW(dev_priv->dev)) {
1460                 if ((val & DP_PIPE_MASK_CHV) != DP_PIPE_SELECT_CHV(pipe))
1461                         return false;
1462         } else {
1463                 if ((val & DP_PIPE_MASK) != (pipe << 30))
1464                         return false;
1465         }
1466         return true;
1467 }
1468
1469 static bool hdmi_pipe_enabled(struct drm_i915_private *dev_priv,
1470                               enum pipe pipe, u32 val)
1471 {
1472         if ((val & SDVO_ENABLE) == 0)
1473                 return false;
1474
1475         if (HAS_PCH_CPT(dev_priv->dev)) {
1476                 if ((val & SDVO_PIPE_SEL_MASK_CPT) != SDVO_PIPE_SEL_CPT(pipe))
1477                         return false;
1478         } else if (IS_CHERRYVIEW(dev_priv->dev)) {
1479                 if ((val & SDVO_PIPE_SEL_MASK_CHV) != SDVO_PIPE_SEL_CHV(pipe))
1480                         return false;
1481         } else {
1482                 if ((val & SDVO_PIPE_SEL_MASK) != SDVO_PIPE_SEL(pipe))
1483                         return false;
1484         }
1485         return true;
1486 }
1487
1488 static bool lvds_pipe_enabled(struct drm_i915_private *dev_priv,
1489                               enum pipe pipe, u32 val)
1490 {
1491         if ((val & LVDS_PORT_EN) == 0)
1492                 return false;
1493
1494         if (HAS_PCH_CPT(dev_priv->dev)) {
1495                 if ((val & PORT_TRANS_SEL_MASK) != PORT_TRANS_SEL_CPT(pipe))
1496                         return false;
1497         } else {
1498                 if ((val & LVDS_PIPE_MASK) != LVDS_PIPE(pipe))
1499                         return false;
1500         }
1501         return true;
1502 }
1503
1504 static bool adpa_pipe_enabled(struct drm_i915_private *dev_priv,
1505                               enum pipe pipe, u32 val)
1506 {
1507         if ((val & ADPA_DAC_ENABLE) == 0)
1508                 return false;
1509         if (HAS_PCH_CPT(dev_priv->dev)) {
1510                 if ((val & PORT_TRANS_SEL_MASK) != PORT_TRANS_SEL_CPT(pipe))
1511                         return false;
1512         } else {
1513                 if ((val & ADPA_PIPE_SELECT_MASK) != ADPA_PIPE_SELECT(pipe))
1514                         return false;
1515         }
1516         return true;
1517 }
1518
1519 static void assert_pch_dp_disabled(struct drm_i915_private *dev_priv,
1520                                    enum pipe pipe, i915_reg_t reg,
1521                                    u32 port_sel)
1522 {
1523         u32 val = I915_READ(reg);
1524         I915_STATE_WARN(dp_pipe_enabled(dev_priv, pipe, port_sel, val),
1525              "PCH DP (0x%08x) enabled on transcoder %c, should be disabled\n",
1526              i915_mmio_reg_offset(reg), pipe_name(pipe));
1527
1528         I915_STATE_WARN(HAS_PCH_IBX(dev_priv->dev) && (val & DP_PORT_EN) == 0
1529              && (val & DP_PIPEB_SELECT),
1530              "IBX PCH dp port still using transcoder B\n");
1531 }
1532
1533 static void assert_pch_hdmi_disabled(struct drm_i915_private *dev_priv,
1534                                      enum pipe pipe, i915_reg_t reg)
1535 {
1536         u32 val = I915_READ(reg);
1537         I915_STATE_WARN(hdmi_pipe_enabled(dev_priv, pipe, val),
1538              "PCH HDMI (0x%08x) enabled on transcoder %c, should be disabled\n",
1539              i915_mmio_reg_offset(reg), pipe_name(pipe));
1540
1541         I915_STATE_WARN(HAS_PCH_IBX(dev_priv->dev) && (val & SDVO_ENABLE) == 0
1542              && (val & SDVO_PIPE_B_SELECT),
1543              "IBX PCH hdmi port still using transcoder B\n");
1544 }
1545
1546 static void assert_pch_ports_disabled(struct drm_i915_private *dev_priv,
1547                                       enum pipe pipe)
1548 {
1549         u32 val;
1550
1551         assert_pch_dp_disabled(dev_priv, pipe, PCH_DP_B, TRANS_DP_PORT_SEL_B);
1552         assert_pch_dp_disabled(dev_priv, pipe, PCH_DP_C, TRANS_DP_PORT_SEL_C);
1553         assert_pch_dp_disabled(dev_priv, pipe, PCH_DP_D, TRANS_DP_PORT_SEL_D);
1554
1555         val = I915_READ(PCH_ADPA);
1556         I915_STATE_WARN(adpa_pipe_enabled(dev_priv, pipe, val),
1557              "PCH VGA enabled on transcoder %c, should be disabled\n",
1558              pipe_name(pipe));
1559
1560         val = I915_READ(PCH_LVDS);
1561         I915_STATE_WARN(lvds_pipe_enabled(dev_priv, pipe, val),
1562              "PCH LVDS enabled on transcoder %c, should be disabled\n",
1563              pipe_name(pipe));
1564
1565         assert_pch_hdmi_disabled(dev_priv, pipe, PCH_HDMIB);
1566         assert_pch_hdmi_disabled(dev_priv, pipe, PCH_HDMIC);
1567         assert_pch_hdmi_disabled(dev_priv, pipe, PCH_HDMID);
1568 }
1569
1570 static void vlv_enable_pll(struct intel_crtc *crtc,
1571                            const struct intel_crtc_state *pipe_config)
1572 {
1573         struct drm_device *dev = crtc->base.dev;
1574         struct drm_i915_private *dev_priv = dev->dev_private;
1575         i915_reg_t reg = DPLL(crtc->pipe);
1576         u32 dpll = pipe_config->dpll_hw_state.dpll;
1577
1578         assert_pipe_disabled(dev_priv, crtc->pipe);
1579
1580         /* PLL is protected by panel, make sure we can write it */
1581         if (IS_MOBILE(dev_priv->dev))
1582                 assert_panel_unlocked(dev_priv, crtc->pipe);
1583
1584         I915_WRITE(reg, dpll);
1585         POSTING_READ(reg);
1586         udelay(150);
1587
1588         if (wait_for(((I915_READ(reg) & DPLL_LOCK_VLV) == DPLL_LOCK_VLV), 1))
1589                 DRM_ERROR("DPLL %d failed to lock\n", crtc->pipe);
1590
1591         I915_WRITE(DPLL_MD(crtc->pipe), pipe_config->dpll_hw_state.dpll_md);
1592         POSTING_READ(DPLL_MD(crtc->pipe));
1593
1594         /* We do this three times for luck */
1595         I915_WRITE(reg, dpll);
1596         POSTING_READ(reg);
1597         udelay(150); /* wait for warmup */
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 }
1605
1606 static void chv_enable_pll(struct intel_crtc *crtc,
1607                            const struct intel_crtc_state *pipe_config)
1608 {
1609         struct drm_device *dev = crtc->base.dev;
1610         struct drm_i915_private *dev_priv = dev->dev_private;
1611         int pipe = crtc->pipe;
1612         enum dpio_channel port = vlv_pipe_to_channel(pipe);
1613         u32 tmp;
1614
1615         assert_pipe_disabled(dev_priv, crtc->pipe);
1616
1617         mutex_lock(&dev_priv->sb_lock);
1618
1619         /* Enable back the 10bit clock to display controller */
1620         tmp = vlv_dpio_read(dev_priv, pipe, CHV_CMN_DW14(port));
1621         tmp |= DPIO_DCLKP_EN;
1622         vlv_dpio_write(dev_priv, pipe, CHV_CMN_DW14(port), tmp);
1623
1624         mutex_unlock(&dev_priv->sb_lock);
1625
1626         /*
1627          * Need to wait > 100ns between dclkp clock enable bit and PLL enable.
1628          */
1629         udelay(1);
1630
1631         /* Enable PLL */
1632         I915_WRITE(DPLL(pipe), pipe_config->dpll_hw_state.dpll);
1633
1634         /* Check PLL is locked */
1635         if (wait_for(((I915_READ(DPLL(pipe)) & DPLL_LOCK_VLV) == DPLL_LOCK_VLV), 1))
1636                 DRM_ERROR("PLL %d failed to lock\n", pipe);
1637
1638         /* not sure when this should be written */
1639         I915_WRITE(DPLL_MD(pipe), pipe_config->dpll_hw_state.dpll_md);
1640         POSTING_READ(DPLL_MD(pipe));
1641 }
1642
1643 static int intel_num_dvo_pipes(struct drm_device *dev)
1644 {
1645         struct intel_crtc *crtc;
1646         int count = 0;
1647
1648         for_each_intel_crtc(dev, crtc)
1649                 count += crtc->base.state->active &&
1650                         intel_pipe_has_type(crtc, INTEL_OUTPUT_DVO);
1651
1652         return count;
1653 }
1654
1655 static void i9xx_enable_pll(struct intel_crtc *crtc)
1656 {
1657         struct drm_device *dev = crtc->base.dev;
1658         struct drm_i915_private *dev_priv = dev->dev_private;
1659         i915_reg_t reg = DPLL(crtc->pipe);
1660         u32 dpll = crtc->config->dpll_hw_state.dpll;
1661
1662         assert_pipe_disabled(dev_priv, crtc->pipe);
1663
1664         /* No really, not for ILK+ */
1665         BUG_ON(INTEL_INFO(dev)->gen >= 5);
1666
1667         /* PLL is protected by panel, make sure we can write it */
1668         if (IS_MOBILE(dev) && !IS_I830(dev))
1669                 assert_panel_unlocked(dev_priv, crtc->pipe);
1670
1671         /* Enable DVO 2x clock on both PLLs if necessary */
1672         if (IS_I830(dev) && intel_num_dvo_pipes(dev) > 0) {
1673                 /*
1674                  * It appears to be important that we don't enable this
1675                  * for the current pipe before otherwise configuring the
1676                  * PLL. No idea how this should be handled if multiple
1677                  * DVO outputs are enabled simultaneosly.
1678                  */
1679                 dpll |= DPLL_DVO_2X_MODE;
1680                 I915_WRITE(DPLL(!crtc->pipe),
1681                            I915_READ(DPLL(!crtc->pipe)) | DPLL_DVO_2X_MODE);
1682         }
1683
1684         /*
1685          * Apparently we need to have VGA mode enabled prior to changing
1686          * the P1/P2 dividers. Otherwise the DPLL will keep using the old
1687          * dividers, even though the register value does change.
1688          */
1689         I915_WRITE(reg, 0);
1690
1691         I915_WRITE(reg, dpll);
1692
1693         /* Wait for the clocks to stabilize. */
1694         POSTING_READ(reg);
1695         udelay(150);
1696
1697         if (INTEL_INFO(dev)->gen >= 4) {
1698                 I915_WRITE(DPLL_MD(crtc->pipe),
1699                            crtc->config->dpll_hw_state.dpll_md);
1700         } else {
1701                 /* The pixel multiplier can only be updated once the
1702                  * DPLL is enabled and the clocks are stable.
1703                  *
1704                  * So write it again.
1705                  */
1706                 I915_WRITE(reg, dpll);
1707         }
1708
1709         /* We do this three times for luck */
1710         I915_WRITE(reg, dpll);
1711         POSTING_READ(reg);
1712         udelay(150); /* wait for warmup */
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 }
1720
1721 /**
1722  * i9xx_disable_pll - disable a PLL
1723  * @dev_priv: i915 private structure
1724  * @pipe: pipe PLL to disable
1725  *
1726  * Disable the PLL for @pipe, making sure the pipe is off first.
1727  *
1728  * Note!  This is for pre-ILK only.
1729  */
1730 static void i9xx_disable_pll(struct intel_crtc *crtc)
1731 {
1732         struct drm_device *dev = crtc->base.dev;
1733         struct drm_i915_private *dev_priv = dev->dev_private;
1734         enum pipe pipe = crtc->pipe;
1735
1736         /* Disable DVO 2x clock on both PLLs if necessary */
1737         if (IS_I830(dev) &&
1738             intel_pipe_has_type(crtc, INTEL_OUTPUT_DVO) &&
1739             !intel_num_dvo_pipes(dev)) {
1740                 I915_WRITE(DPLL(PIPE_B),
1741                            I915_READ(DPLL(PIPE_B)) & ~DPLL_DVO_2X_MODE);
1742                 I915_WRITE(DPLL(PIPE_A),
1743                            I915_READ(DPLL(PIPE_A)) & ~DPLL_DVO_2X_MODE);
1744         }
1745
1746         /* Don't disable pipe or pipe PLLs if needed */
1747         if ((pipe == PIPE_A && dev_priv->quirks & QUIRK_PIPEA_FORCE) ||
1748             (pipe == PIPE_B && dev_priv->quirks & QUIRK_PIPEB_FORCE))
1749                 return;
1750
1751         /* Make sure the pipe isn't still relying on us */
1752         assert_pipe_disabled(dev_priv, pipe);
1753
1754         I915_WRITE(DPLL(pipe), DPLL_VGA_MODE_DIS);
1755         POSTING_READ(DPLL(pipe));
1756 }
1757
1758 static void vlv_disable_pll(struct drm_i915_private *dev_priv, enum pipe pipe)
1759 {
1760         u32 val;
1761
1762         /* Make sure the pipe isn't still relying on us */
1763         assert_pipe_disabled(dev_priv, pipe);
1764
1765         /*
1766          * Leave integrated clock source and reference clock enabled for pipe B.
1767          * The latter is needed for VGA hotplug / manual detection.
1768          */
1769         val = DPLL_VGA_MODE_DIS;
1770         if (pipe == PIPE_B)
1771                 val = DPLL_INTEGRATED_CRI_CLK_VLV | DPLL_REF_CLK_ENABLE_VLV;
1772         I915_WRITE(DPLL(pipe), val);
1773         POSTING_READ(DPLL(pipe));
1774
1775 }
1776
1777 static void chv_disable_pll(struct drm_i915_private *dev_priv, enum pipe pipe)
1778 {
1779         enum dpio_channel port = vlv_pipe_to_channel(pipe);
1780         u32 val;
1781
1782         /* Make sure the pipe isn't still relying on us */
1783         assert_pipe_disabled(dev_priv, pipe);
1784
1785         /* Set PLL en = 0 */
1786         val = DPLL_SSC_REF_CLK_CHV |
1787                 DPLL_REF_CLK_ENABLE_VLV | DPLL_VGA_MODE_DIS;
1788         if (pipe != PIPE_A)
1789                 val |= DPLL_INTEGRATED_CRI_CLK_VLV;
1790         I915_WRITE(DPLL(pipe), val);
1791         POSTING_READ(DPLL(pipe));
1792
1793         mutex_lock(&dev_priv->sb_lock);
1794
1795         /* Disable 10bit clock to display controller */
1796         val = vlv_dpio_read(dev_priv, pipe, CHV_CMN_DW14(port));
1797         val &= ~DPIO_DCLKP_EN;
1798         vlv_dpio_write(dev_priv, pipe, CHV_CMN_DW14(port), val);
1799
1800         mutex_unlock(&dev_priv->sb_lock);
1801 }
1802
1803 void vlv_wait_port_ready(struct drm_i915_private *dev_priv,
1804                          struct intel_digital_port *dport,
1805                          unsigned int expected_mask)
1806 {
1807         u32 port_mask;
1808         i915_reg_t dpll_reg;
1809
1810         switch (dport->port) {
1811         case PORT_B:
1812                 port_mask = DPLL_PORTB_READY_MASK;
1813                 dpll_reg = DPLL(0);
1814                 break;
1815         case PORT_C:
1816                 port_mask = DPLL_PORTC_READY_MASK;
1817                 dpll_reg = DPLL(0);
1818                 expected_mask <<= 4;
1819                 break;
1820         case PORT_D:
1821                 port_mask = DPLL_PORTD_READY_MASK;
1822                 dpll_reg = DPIO_PHY_STATUS;
1823                 break;
1824         default:
1825                 BUG();
1826         }
1827
1828         if (wait_for((I915_READ(dpll_reg) & port_mask) == expected_mask, 1000))
1829                 WARN(1, "timed out waiting for port %c ready: got 0x%x, expected 0x%x\n",
1830                      port_name(dport->port), I915_READ(dpll_reg) & port_mask, expected_mask);
1831 }
1832
1833 static void ironlake_enable_pch_transcoder(struct drm_i915_private *dev_priv,
1834                                            enum pipe pipe)
1835 {
1836         struct drm_device *dev = dev_priv->dev;
1837         struct drm_crtc *crtc = dev_priv->pipe_to_crtc_mapping[pipe];
1838         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
1839         i915_reg_t reg;
1840         uint32_t val, pipeconf_val;
1841
1842         /* PCH only available on ILK+ */
1843         BUG_ON(!HAS_PCH_SPLIT(dev));
1844
1845         /* Make sure PCH DPLL is enabled */
1846         assert_shared_dpll_enabled(dev_priv, intel_crtc->config->shared_dpll);
1847
1848         /* FDI must be feeding us bits for PCH ports */
1849         assert_fdi_tx_enabled(dev_priv, pipe);
1850         assert_fdi_rx_enabled(dev_priv, pipe);
1851
1852         if (HAS_PCH_CPT(dev)) {
1853                 /* Workaround: Set the timing override bit before enabling the
1854                  * pch transcoder. */
1855                 reg = TRANS_CHICKEN2(pipe);
1856                 val = I915_READ(reg);
1857                 val |= TRANS_CHICKEN2_TIMING_OVERRIDE;
1858                 I915_WRITE(reg, val);
1859         }
1860
1861         reg = PCH_TRANSCONF(pipe);
1862         val = I915_READ(reg);
1863         pipeconf_val = I915_READ(PIPECONF(pipe));
1864
1865         if (HAS_PCH_IBX(dev_priv->dev)) {
1866                 /*
1867                  * Make the BPC in transcoder be consistent with
1868                  * that in pipeconf reg. For HDMI we must use 8bpc
1869                  * here for both 8bpc and 12bpc.
1870                  */
1871                 val &= ~PIPECONF_BPC_MASK;
1872                 if (intel_pipe_has_type(intel_crtc, INTEL_OUTPUT_HDMI))
1873                         val |= PIPECONF_8BPC;
1874                 else
1875                         val |= pipeconf_val & PIPECONF_BPC_MASK;
1876         }
1877
1878         val &= ~TRANS_INTERLACE_MASK;
1879         if ((pipeconf_val & PIPECONF_INTERLACE_MASK) == PIPECONF_INTERLACED_ILK)
1880                 if (HAS_PCH_IBX(dev_priv->dev) &&
1881                     intel_pipe_has_type(intel_crtc, INTEL_OUTPUT_SDVO))
1882                         val |= TRANS_LEGACY_INTERLACED_ILK;
1883                 else
1884                         val |= TRANS_INTERLACED;
1885         else
1886                 val |= TRANS_PROGRESSIVE;
1887
1888         I915_WRITE(reg, val | TRANS_ENABLE);
1889         if (wait_for(I915_READ(reg) & TRANS_STATE_ENABLE, 100))
1890                 DRM_ERROR("failed to enable transcoder %c\n", pipe_name(pipe));
1891 }
1892
1893 static void lpt_enable_pch_transcoder(struct drm_i915_private *dev_priv,
1894                                       enum transcoder cpu_transcoder)
1895 {
1896         u32 val, pipeconf_val;
1897
1898         /* PCH only available on ILK+ */
1899         BUG_ON(!HAS_PCH_SPLIT(dev_priv->dev));
1900
1901         /* FDI must be feeding us bits for PCH ports */
1902         assert_fdi_tx_enabled(dev_priv, (enum pipe) cpu_transcoder);
1903         assert_fdi_rx_enabled(dev_priv, TRANSCODER_A);
1904
1905         /* Workaround: set timing override bit. */
1906         val = I915_READ(TRANS_CHICKEN2(PIPE_A));
1907         val |= TRANS_CHICKEN2_TIMING_OVERRIDE;
1908         I915_WRITE(TRANS_CHICKEN2(PIPE_A), val);
1909
1910         val = TRANS_ENABLE;
1911         pipeconf_val = I915_READ(PIPECONF(cpu_transcoder));
1912
1913         if ((pipeconf_val & PIPECONF_INTERLACE_MASK_HSW) ==
1914             PIPECONF_INTERLACED_ILK)
1915                 val |= TRANS_INTERLACED;
1916         else
1917                 val |= TRANS_PROGRESSIVE;
1918
1919         I915_WRITE(LPT_TRANSCONF, val);
1920         if (wait_for(I915_READ(LPT_TRANSCONF) & TRANS_STATE_ENABLE, 100))
1921                 DRM_ERROR("Failed to enable PCH transcoder\n");
1922 }
1923
1924 static void ironlake_disable_pch_transcoder(struct drm_i915_private *dev_priv,
1925                                             enum pipe pipe)
1926 {
1927         struct drm_device *dev = dev_priv->dev;
1928         i915_reg_t reg;
1929         uint32_t val;
1930
1931         /* FDI relies on the transcoder */
1932         assert_fdi_tx_disabled(dev_priv, pipe);
1933         assert_fdi_rx_disabled(dev_priv, pipe);
1934
1935         /* Ports must be off as well */
1936         assert_pch_ports_disabled(dev_priv, pipe);
1937
1938         reg = PCH_TRANSCONF(pipe);
1939         val = I915_READ(reg);
1940         val &= ~TRANS_ENABLE;
1941         I915_WRITE(reg, val);
1942         /* wait for PCH transcoder off, transcoder state */
1943         if (wait_for((I915_READ(reg) & TRANS_STATE_ENABLE) == 0, 50))
1944                 DRM_ERROR("failed to disable transcoder %c\n", pipe_name(pipe));
1945
1946         if (HAS_PCH_CPT(dev)) {
1947                 /* Workaround: Clear the timing override chicken bit again. */
1948                 reg = TRANS_CHICKEN2(pipe);
1949                 val = I915_READ(reg);
1950                 val &= ~TRANS_CHICKEN2_TIMING_OVERRIDE;
1951                 I915_WRITE(reg, val);
1952         }
1953 }
1954
1955 static void lpt_disable_pch_transcoder(struct drm_i915_private *dev_priv)
1956 {
1957         u32 val;
1958
1959         val = I915_READ(LPT_TRANSCONF);
1960         val &= ~TRANS_ENABLE;
1961         I915_WRITE(LPT_TRANSCONF, val);
1962         /* wait for PCH transcoder off, transcoder state */
1963         if (wait_for((I915_READ(LPT_TRANSCONF) & TRANS_STATE_ENABLE) == 0, 50))
1964                 DRM_ERROR("Failed to disable PCH transcoder\n");
1965
1966         /* Workaround: clear timing override bit. */
1967         val = I915_READ(TRANS_CHICKEN2(PIPE_A));
1968         val &= ~TRANS_CHICKEN2_TIMING_OVERRIDE;
1969         I915_WRITE(TRANS_CHICKEN2(PIPE_A), val);
1970 }
1971
1972 /**
1973  * intel_enable_pipe - enable a pipe, asserting requirements
1974  * @crtc: crtc responsible for the pipe
1975  *
1976  * Enable @crtc's pipe, making sure that various hardware specific requirements
1977  * are met, if applicable, e.g. PLL enabled, LVDS pairs enabled, etc.
1978  */
1979 static void intel_enable_pipe(struct intel_crtc *crtc)
1980 {
1981         struct drm_device *dev = crtc->base.dev;
1982         struct drm_i915_private *dev_priv = dev->dev_private;
1983         enum pipe pipe = crtc->pipe;
1984         enum transcoder cpu_transcoder = crtc->config->cpu_transcoder;
1985         enum pipe pch_transcoder;
1986         i915_reg_t reg;
1987         u32 val;
1988
1989         DRM_DEBUG_KMS("enabling pipe %c\n", pipe_name(pipe));
1990
1991         assert_planes_disabled(dev_priv, pipe);
1992         assert_cursor_disabled(dev_priv, pipe);
1993         assert_sprites_disabled(dev_priv, pipe);
1994
1995         if (HAS_PCH_LPT(dev_priv->dev))
1996                 pch_transcoder = TRANSCODER_A;
1997         else
1998                 pch_transcoder = pipe;
1999
2000         /*
2001          * A pipe without a PLL won't actually be able to drive bits from
2002          * a plane.  On ILK+ the pipe PLLs are integrated, so we don't
2003          * need the check.
2004          */
2005         if (HAS_GMCH_DISPLAY(dev_priv->dev))
2006                 if (crtc->config->has_dsi_encoder)
2007                         assert_dsi_pll_enabled(dev_priv);
2008                 else
2009                         assert_pll_enabled(dev_priv, pipe);
2010         else {
2011                 if (crtc->config->has_pch_encoder) {
2012                         /* if driving the PCH, we need FDI enabled */
2013                         assert_fdi_rx_pll_enabled(dev_priv, pch_transcoder);
2014                         assert_fdi_tx_pll_enabled(dev_priv,
2015                                                   (enum pipe) cpu_transcoder);
2016                 }
2017                 /* FIXME: assert CPU port conditions for SNB+ */
2018         }
2019
2020         reg = PIPECONF(cpu_transcoder);
2021         val = I915_READ(reg);
2022         if (val & PIPECONF_ENABLE) {
2023                 WARN_ON(!((pipe == PIPE_A && dev_priv->quirks & QUIRK_PIPEA_FORCE) ||
2024                           (pipe == PIPE_B && dev_priv->quirks & QUIRK_PIPEB_FORCE)));
2025                 return;
2026         }
2027
2028         I915_WRITE(reg, val | PIPECONF_ENABLE);
2029         POSTING_READ(reg);
2030
2031         /*
2032          * Until the pipe starts DSL will read as 0, which would cause
2033          * an apparent vblank timestamp jump, which messes up also the
2034          * frame count when it's derived from the timestamps. So let's
2035          * wait for the pipe to start properly before we call
2036          * drm_crtc_vblank_on()
2037          */
2038         if (dev->max_vblank_count == 0 &&
2039             wait_for(intel_get_crtc_scanline(crtc) != crtc->scanline_offset, 50))
2040                 DRM_ERROR("pipe %c didn't start\n", pipe_name(pipe));
2041 }
2042
2043 /**
2044  * intel_disable_pipe - disable a pipe, asserting requirements
2045  * @crtc: crtc whose pipes is to be disabled
2046  *
2047  * Disable the pipe of @crtc, making sure that various hardware
2048  * specific requirements are met, if applicable, e.g. plane
2049  * disabled, panel fitter off, etc.
2050  *
2051  * Will wait until the pipe has shut down before returning.
2052  */
2053 static void intel_disable_pipe(struct intel_crtc *crtc)
2054 {
2055         struct drm_i915_private *dev_priv = crtc->base.dev->dev_private;
2056         enum transcoder cpu_transcoder = crtc->config->cpu_transcoder;
2057         enum pipe pipe = crtc->pipe;
2058         i915_reg_t reg;
2059         u32 val;
2060
2061         DRM_DEBUG_KMS("disabling pipe %c\n", pipe_name(pipe));
2062
2063         /*
2064          * Make sure planes won't keep trying to pump pixels to us,
2065          * or we might hang the display.
2066          */
2067         assert_planes_disabled(dev_priv, pipe);
2068         assert_cursor_disabled(dev_priv, pipe);
2069         assert_sprites_disabled(dev_priv, pipe);
2070
2071         reg = PIPECONF(cpu_transcoder);
2072         val = I915_READ(reg);
2073         if ((val & PIPECONF_ENABLE) == 0)
2074                 return;
2075
2076         /*
2077          * Double wide has implications for planes
2078          * so best keep it disabled when not needed.
2079          */
2080         if (crtc->config->double_wide)
2081                 val &= ~PIPECONF_DOUBLE_WIDE;
2082
2083         /* Don't disable pipe or pipe PLLs if needed */
2084         if (!(pipe == PIPE_A && dev_priv->quirks & QUIRK_PIPEA_FORCE) &&
2085             !(pipe == PIPE_B && dev_priv->quirks & QUIRK_PIPEB_FORCE))
2086                 val &= ~PIPECONF_ENABLE;
2087
2088         I915_WRITE(reg, val);
2089         if ((val & PIPECONF_ENABLE) == 0)
2090                 intel_wait_for_pipe_off(crtc);
2091 }
2092
2093 static bool need_vtd_wa(struct drm_device *dev)
2094 {
2095 #ifdef CONFIG_INTEL_IOMMU
2096         if (INTEL_INFO(dev)->gen >= 6 && intel_iommu_gfx_mapped)
2097                 return true;
2098 #endif
2099         return false;
2100 }
2101
2102 static unsigned int intel_tile_size(const struct drm_i915_private *dev_priv)
2103 {
2104         return IS_GEN2(dev_priv) ? 2048 : 4096;
2105 }
2106
2107 static unsigned int intel_tile_width_bytes(const struct drm_i915_private *dev_priv,
2108                                            uint64_t fb_modifier, unsigned int cpp)
2109 {
2110         switch (fb_modifier) {
2111         case DRM_FORMAT_MOD_NONE:
2112                 return cpp;
2113         case I915_FORMAT_MOD_X_TILED:
2114                 if (IS_GEN2(dev_priv))
2115                         return 128;
2116                 else
2117                         return 512;
2118         case I915_FORMAT_MOD_Y_TILED:
2119                 if (IS_GEN2(dev_priv) || HAS_128_BYTE_Y_TILING(dev_priv))
2120                         return 128;
2121                 else
2122                         return 512;
2123         case I915_FORMAT_MOD_Yf_TILED:
2124                 switch (cpp) {
2125                 case 1:
2126                         return 64;
2127                 case 2:
2128                 case 4:
2129                         return 128;
2130                 case 8:
2131                 case 16:
2132                         return 256;
2133                 default:
2134                         MISSING_CASE(cpp);
2135                         return cpp;
2136                 }
2137                 break;
2138         default:
2139                 MISSING_CASE(fb_modifier);
2140                 return cpp;
2141         }
2142 }
2143
2144 unsigned int intel_tile_height(const struct drm_i915_private *dev_priv,
2145                                uint64_t fb_modifier, unsigned int cpp)
2146 {
2147         if (fb_modifier == DRM_FORMAT_MOD_NONE)
2148                 return 1;
2149         else
2150                 return intel_tile_size(dev_priv) /
2151                         intel_tile_width_bytes(dev_priv, fb_modifier, cpp);
2152 }
2153
2154 /* Return the tile dimensions in pixel units */
2155 static void intel_tile_dims(const struct drm_i915_private *dev_priv,
2156                             unsigned int *tile_width,
2157                             unsigned int *tile_height,
2158                             uint64_t fb_modifier,
2159                             unsigned int cpp)
2160 {
2161         unsigned int tile_width_bytes =
2162                 intel_tile_width_bytes(dev_priv, fb_modifier, cpp);
2163
2164         *tile_width = tile_width_bytes / cpp;
2165         *tile_height = intel_tile_size(dev_priv) / tile_width_bytes;
2166 }
2167
2168 unsigned int
2169 intel_fb_align_height(struct drm_device *dev, unsigned int height,
2170                       uint32_t pixel_format, uint64_t fb_modifier)
2171 {
2172         unsigned int cpp = drm_format_plane_cpp(pixel_format, 0);
2173         unsigned int tile_height = intel_tile_height(to_i915(dev), fb_modifier, cpp);
2174
2175         return ALIGN(height, tile_height);
2176 }
2177
2178 unsigned int intel_rotation_info_size(const struct intel_rotation_info *rot_info)
2179 {
2180         unsigned int size = 0;
2181         int i;
2182
2183         for (i = 0 ; i < ARRAY_SIZE(rot_info->plane); i++)
2184                 size += rot_info->plane[i].width * rot_info->plane[i].height;
2185
2186         return size;
2187 }
2188
2189 static void
2190 intel_fill_fb_ggtt_view(struct i915_ggtt_view *view,
2191                         const struct drm_framebuffer *fb,
2192                         unsigned int rotation)
2193 {
2194         if (intel_rotation_90_or_270(rotation)) {
2195                 *view = i915_ggtt_view_rotated;
2196                 view->params.rotated = to_intel_framebuffer(fb)->rot_info;
2197         } else {
2198                 *view = i915_ggtt_view_normal;
2199         }
2200 }
2201
2202 static void
2203 intel_fill_fb_info(struct drm_i915_private *dev_priv,
2204                    struct drm_framebuffer *fb)
2205 {
2206         struct intel_rotation_info *info = &to_intel_framebuffer(fb)->rot_info;
2207         unsigned int tile_size, tile_width, tile_height, cpp;
2208
2209         tile_size = intel_tile_size(dev_priv);
2210
2211         cpp = drm_format_plane_cpp(fb->pixel_format, 0);
2212         intel_tile_dims(dev_priv, &tile_width, &tile_height,
2213                         fb->modifier[0], cpp);
2214
2215         info->plane[0].width = DIV_ROUND_UP(fb->pitches[0], tile_width * cpp);
2216         info->plane[0].height = DIV_ROUND_UP(fb->height, tile_height);
2217
2218         if (info->pixel_format == DRM_FORMAT_NV12) {
2219                 cpp = drm_format_plane_cpp(fb->pixel_format, 1);
2220                 intel_tile_dims(dev_priv, &tile_width, &tile_height,
2221                                 fb->modifier[1], cpp);
2222
2223                 info->uv_offset = fb->offsets[1];
2224                 info->plane[1].width = DIV_ROUND_UP(fb->pitches[1], tile_width * cpp);
2225                 info->plane[1].height = DIV_ROUND_UP(fb->height / 2, tile_height);
2226         }
2227 }
2228
2229 static unsigned int intel_linear_alignment(const struct drm_i915_private *dev_priv)
2230 {
2231         if (INTEL_INFO(dev_priv)->gen >= 9)
2232                 return 256 * 1024;
2233         else if (IS_BROADWATER(dev_priv) || IS_CRESTLINE(dev_priv) ||
2234                  IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv))
2235                 return 128 * 1024;
2236         else if (INTEL_INFO(dev_priv)->gen >= 4)
2237                 return 4 * 1024;
2238         else
2239                 return 0;
2240 }
2241
2242 static unsigned int intel_surf_alignment(const struct drm_i915_private *dev_priv,
2243                                          uint64_t fb_modifier)
2244 {
2245         switch (fb_modifier) {
2246         case DRM_FORMAT_MOD_NONE:
2247                 return intel_linear_alignment(dev_priv);
2248         case I915_FORMAT_MOD_X_TILED:
2249                 if (INTEL_INFO(dev_priv)->gen >= 9)
2250                         return 256 * 1024;
2251                 return 0;
2252         case I915_FORMAT_MOD_Y_TILED:
2253         case I915_FORMAT_MOD_Yf_TILED:
2254                 return 1 * 1024 * 1024;
2255         default:
2256                 MISSING_CASE(fb_modifier);
2257                 return 0;
2258         }
2259 }
2260
2261 int
2262 intel_pin_and_fence_fb_obj(struct drm_framebuffer *fb,
2263                            unsigned int rotation)
2264 {
2265         struct drm_device *dev = fb->dev;
2266         struct drm_i915_private *dev_priv = dev->dev_private;
2267         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
2268         struct i915_ggtt_view view;
2269         u32 alignment;
2270         int ret;
2271
2272         WARN_ON(!mutex_is_locked(&dev->struct_mutex));
2273
2274         alignment = intel_surf_alignment(dev_priv, fb->modifier[0]);
2275
2276         intel_fill_fb_ggtt_view(&view, fb, rotation);
2277
2278         /* Note that the w/a also requires 64 PTE of padding following the
2279          * bo. We currently fill all unused PTE with the shadow page and so
2280          * we should always have valid PTE following the scanout preventing
2281          * the VT-d warning.
2282          */
2283         if (need_vtd_wa(dev) && alignment < 256 * 1024)
2284                 alignment = 256 * 1024;
2285
2286         /*
2287          * Global gtt pte registers are special registers which actually forward
2288          * writes to a chunk of system memory. Which means that there is no risk
2289          * that the register values disappear as soon as we call
2290          * intel_runtime_pm_put(), so it is correct to wrap only the
2291          * pin/unpin/fence and not more.
2292          */
2293         intel_runtime_pm_get(dev_priv);
2294
2295         ret = i915_gem_object_pin_to_display_plane(obj, alignment,
2296                                                    &view);
2297         if (ret)
2298                 goto err_pm;
2299
2300         /* Install a fence for tiled scan-out. Pre-i965 always needs a
2301          * fence, whereas 965+ only requires a fence if using
2302          * framebuffer compression.  For simplicity, we always install
2303          * a fence as the cost is not that onerous.
2304          */
2305         if (view.type == I915_GGTT_VIEW_NORMAL) {
2306                 ret = i915_gem_object_get_fence(obj);
2307                 if (ret == -EDEADLK) {
2308                         /*
2309                          * -EDEADLK means there are no free fences
2310                          * no pending flips.
2311                          *
2312                          * This is propagated to atomic, but it uses
2313                          * -EDEADLK to force a locking recovery, so
2314                          * change the returned error to -EBUSY.
2315                          */
2316                         ret = -EBUSY;
2317                         goto err_unpin;
2318                 } else if (ret)
2319                         goto err_unpin;
2320
2321                 i915_gem_object_pin_fence(obj);
2322         }
2323
2324         intel_runtime_pm_put(dev_priv);
2325         return 0;
2326
2327 err_unpin:
2328         i915_gem_object_unpin_from_display_plane(obj, &view);
2329 err_pm:
2330         intel_runtime_pm_put(dev_priv);
2331         return ret;
2332 }
2333
2334 static void intel_unpin_fb_obj(struct drm_framebuffer *fb, unsigned int rotation)
2335 {
2336         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
2337         struct i915_ggtt_view view;
2338
2339         WARN_ON(!mutex_is_locked(&obj->base.dev->struct_mutex));
2340
2341         intel_fill_fb_ggtt_view(&view, fb, rotation);
2342
2343         if (view.type == I915_GGTT_VIEW_NORMAL)
2344                 i915_gem_object_unpin_fence(obj);
2345
2346         i915_gem_object_unpin_from_display_plane(obj, &view);
2347 }
2348
2349 /*
2350  * Adjust the tile offset by moving the difference into
2351  * the x/y offsets.
2352  *
2353  * Input tile dimensions and pitch must already be
2354  * rotated to match x and y, and in pixel units.
2355  */
2356 static u32 intel_adjust_tile_offset(int *x, int *y,
2357                                     unsigned int tile_width,
2358                                     unsigned int tile_height,
2359                                     unsigned int tile_size,
2360                                     unsigned int pitch_tiles,
2361                                     u32 old_offset,
2362                                     u32 new_offset)
2363 {
2364         unsigned int tiles;
2365
2366         WARN_ON(old_offset & (tile_size - 1));
2367         WARN_ON(new_offset & (tile_size - 1));
2368         WARN_ON(new_offset > old_offset);
2369
2370         tiles = (old_offset - new_offset) / tile_size;
2371
2372         *y += tiles / pitch_tiles * tile_height;
2373         *x += tiles % pitch_tiles * tile_width;
2374
2375         return new_offset;
2376 }
2377
2378 /*
2379  * Computes the linear offset to the base tile and adjusts
2380  * x, y. bytes per pixel is assumed to be a power-of-two.
2381  *
2382  * In the 90/270 rotated case, x and y are assumed
2383  * to be already rotated to match the rotated GTT view, and
2384  * pitch is the tile_height aligned framebuffer height.
2385  */
2386 u32 intel_compute_tile_offset(int *x, int *y,
2387                               const struct drm_framebuffer *fb, int plane,
2388                               unsigned int pitch,
2389                               unsigned int rotation)
2390 {
2391         const struct drm_i915_private *dev_priv = to_i915(fb->dev);
2392         uint64_t fb_modifier = fb->modifier[plane];
2393         unsigned int cpp = drm_format_plane_cpp(fb->pixel_format, plane);
2394         u32 offset, offset_aligned, alignment;
2395
2396         alignment = intel_surf_alignment(dev_priv, fb_modifier);
2397         if (alignment)
2398                 alignment--;
2399
2400         if (fb_modifier != DRM_FORMAT_MOD_NONE) {
2401                 unsigned int tile_size, tile_width, tile_height;
2402                 unsigned int tile_rows, tiles, pitch_tiles;
2403
2404                 tile_size = intel_tile_size(dev_priv);
2405                 intel_tile_dims(dev_priv, &tile_width, &tile_height,
2406                                 fb_modifier, cpp);
2407
2408                 if (intel_rotation_90_or_270(rotation)) {
2409                         pitch_tiles = pitch / tile_height;
2410                         swap(tile_width, tile_height);
2411                 } else {
2412                         pitch_tiles = pitch / (tile_width * cpp);
2413                 }
2414
2415                 tile_rows = *y / tile_height;
2416                 *y %= tile_height;
2417
2418                 tiles = *x / tile_width;
2419                 *x %= tile_width;
2420
2421                 offset = (tile_rows * pitch_tiles + tiles) * tile_size;
2422                 offset_aligned = offset & ~alignment;
2423
2424                 intel_adjust_tile_offset(x, y, tile_width, tile_height,
2425                                          tile_size, pitch_tiles,
2426                                          offset, offset_aligned);
2427         } else {
2428                 offset = *y * pitch + *x * cpp;
2429                 offset_aligned = offset & ~alignment;
2430
2431                 *y = (offset & alignment) / pitch;
2432                 *x = ((offset & alignment) - *y * pitch) / cpp;
2433         }
2434
2435         return offset_aligned;
2436 }
2437
2438 static int i9xx_format_to_fourcc(int format)
2439 {
2440         switch (format) {
2441         case DISPPLANE_8BPP:
2442                 return DRM_FORMAT_C8;
2443         case DISPPLANE_BGRX555:
2444                 return DRM_FORMAT_XRGB1555;
2445         case DISPPLANE_BGRX565:
2446                 return DRM_FORMAT_RGB565;
2447         default:
2448         case DISPPLANE_BGRX888:
2449                 return DRM_FORMAT_XRGB8888;
2450         case DISPPLANE_RGBX888:
2451                 return DRM_FORMAT_XBGR8888;
2452         case DISPPLANE_BGRX101010:
2453                 return DRM_FORMAT_XRGB2101010;
2454         case DISPPLANE_RGBX101010:
2455                 return DRM_FORMAT_XBGR2101010;
2456         }
2457 }
2458
2459 static int skl_format_to_fourcc(int format, bool rgb_order, bool alpha)
2460 {
2461         switch (format) {
2462         case PLANE_CTL_FORMAT_RGB_565:
2463                 return DRM_FORMAT_RGB565;
2464         default:
2465         case PLANE_CTL_FORMAT_XRGB_8888:
2466                 if (rgb_order) {
2467                         if (alpha)
2468                                 return DRM_FORMAT_ABGR8888;
2469                         else
2470                                 return DRM_FORMAT_XBGR8888;
2471                 } else {
2472                         if (alpha)
2473                                 return DRM_FORMAT_ARGB8888;
2474                         else
2475                                 return DRM_FORMAT_XRGB8888;
2476                 }
2477         case PLANE_CTL_FORMAT_XRGB_2101010:
2478                 if (rgb_order)
2479                         return DRM_FORMAT_XBGR2101010;
2480                 else
2481                         return DRM_FORMAT_XRGB2101010;
2482         }
2483 }
2484
2485 static bool
2486 intel_alloc_initial_plane_obj(struct intel_crtc *crtc,
2487                               struct intel_initial_plane_config *plane_config)
2488 {
2489         struct drm_device *dev = crtc->base.dev;
2490         struct drm_i915_private *dev_priv = to_i915(dev);
2491         struct drm_i915_gem_object *obj = NULL;
2492         struct drm_mode_fb_cmd2 mode_cmd = { 0 };
2493         struct drm_framebuffer *fb = &plane_config->fb->base;
2494         u32 base_aligned = round_down(plane_config->base, PAGE_SIZE);
2495         u32 size_aligned = round_up(plane_config->base + plane_config->size,
2496                                     PAGE_SIZE);
2497
2498         size_aligned -= base_aligned;
2499
2500         if (plane_config->size == 0)
2501                 return false;
2502
2503         /* If the FB is too big, just don't use it since fbdev is not very
2504          * important and we should probably use that space with FBC or other
2505          * features. */
2506         if (size_aligned * 2 > dev_priv->gtt.stolen_usable_size)
2507                 return false;
2508
2509         mutex_lock(&dev->struct_mutex);
2510
2511         obj = i915_gem_object_create_stolen_for_preallocated(dev,
2512                                                              base_aligned,
2513                                                              base_aligned,
2514                                                              size_aligned);
2515         if (!obj) {
2516                 mutex_unlock(&dev->struct_mutex);
2517                 return false;
2518         }
2519
2520         obj->tiling_mode = plane_config->tiling;
2521         if (obj->tiling_mode == I915_TILING_X)
2522                 obj->stride = fb->pitches[0];
2523
2524         mode_cmd.pixel_format = fb->pixel_format;
2525         mode_cmd.width = fb->width;
2526         mode_cmd.height = fb->height;
2527         mode_cmd.pitches[0] = fb->pitches[0];
2528         mode_cmd.modifier[0] = fb->modifier[0];
2529         mode_cmd.flags = DRM_MODE_FB_MODIFIERS;
2530
2531         if (intel_framebuffer_init(dev, to_intel_framebuffer(fb),
2532                                    &mode_cmd, obj)) {
2533                 DRM_DEBUG_KMS("intel fb init failed\n");
2534                 goto out_unref_obj;
2535         }
2536
2537         mutex_unlock(&dev->struct_mutex);
2538
2539         DRM_DEBUG_KMS("initial plane fb obj %p\n", obj);
2540         return true;
2541
2542 out_unref_obj:
2543         drm_gem_object_unreference(&obj->base);
2544         mutex_unlock(&dev->struct_mutex);
2545         return false;
2546 }
2547
2548 /* Update plane->state->fb to match plane->fb after driver-internal updates */
2549 static void
2550 update_state_fb(struct drm_plane *plane)
2551 {
2552         if (plane->fb == plane->state->fb)
2553                 return;
2554
2555         if (plane->state->fb)
2556                 drm_framebuffer_unreference(plane->state->fb);
2557         plane->state->fb = plane->fb;
2558         if (plane->state->fb)
2559                 drm_framebuffer_reference(plane->state->fb);
2560 }
2561
2562 static void
2563 intel_find_initial_plane_obj(struct intel_crtc *intel_crtc,
2564                              struct intel_initial_plane_config *plane_config)
2565 {
2566         struct drm_device *dev = intel_crtc->base.dev;
2567         struct drm_i915_private *dev_priv = dev->dev_private;
2568         struct drm_crtc *c;
2569         struct intel_crtc *i;
2570         struct drm_i915_gem_object *obj;
2571         struct drm_plane *primary = intel_crtc->base.primary;
2572         struct drm_plane_state *plane_state = primary->state;
2573         struct drm_crtc_state *crtc_state = intel_crtc->base.state;
2574         struct intel_plane *intel_plane = to_intel_plane(primary);
2575         struct intel_plane_state *intel_state =
2576                 to_intel_plane_state(plane_state);
2577         struct drm_framebuffer *fb;
2578
2579         if (!plane_config->fb)
2580                 return;
2581
2582         if (intel_alloc_initial_plane_obj(intel_crtc, plane_config)) {
2583                 fb = &plane_config->fb->base;
2584                 goto valid_fb;
2585         }
2586
2587         kfree(plane_config->fb);
2588
2589         /*
2590          * Failed to alloc the obj, check to see if we should share
2591          * an fb with another CRTC instead
2592          */
2593         for_each_crtc(dev, c) {
2594                 i = to_intel_crtc(c);
2595
2596                 if (c == &intel_crtc->base)
2597                         continue;
2598
2599                 if (!i->active)
2600                         continue;
2601
2602                 fb = c->primary->fb;
2603                 if (!fb)
2604                         continue;
2605
2606                 obj = intel_fb_obj(fb);
2607                 if (i915_gem_obj_ggtt_offset(obj) == plane_config->base) {
2608                         drm_framebuffer_reference(fb);
2609                         goto valid_fb;
2610                 }
2611         }
2612
2613         /*
2614          * We've failed to reconstruct the BIOS FB.  Current display state
2615          * indicates that the primary plane is visible, but has a NULL FB,
2616          * which will lead to problems later if we don't fix it up.  The
2617          * simplest solution is to just disable the primary plane now and
2618          * pretend the BIOS never had it enabled.
2619          */
2620         to_intel_plane_state(plane_state)->visible = false;
2621         crtc_state->plane_mask &= ~(1 << drm_plane_index(primary));
2622         intel_pre_disable_primary_noatomic(&intel_crtc->base);
2623         intel_plane->disable_plane(primary, &intel_crtc->base);
2624
2625         return;
2626
2627 valid_fb:
2628         plane_state->src_x = 0;
2629         plane_state->src_y = 0;
2630         plane_state->src_w = fb->width << 16;
2631         plane_state->src_h = fb->height << 16;
2632
2633         plane_state->crtc_x = 0;
2634         plane_state->crtc_y = 0;
2635         plane_state->crtc_w = fb->width;
2636         plane_state->crtc_h = fb->height;
2637
2638         intel_state->src.x1 = plane_state->src_x;
2639         intel_state->src.y1 = plane_state->src_y;
2640         intel_state->src.x2 = plane_state->src_x + plane_state->src_w;
2641         intel_state->src.y2 = plane_state->src_y + plane_state->src_h;
2642         intel_state->dst.x1 = plane_state->crtc_x;
2643         intel_state->dst.y1 = plane_state->crtc_y;
2644         intel_state->dst.x2 = plane_state->crtc_x + plane_state->crtc_w;
2645         intel_state->dst.y2 = plane_state->crtc_y + plane_state->crtc_h;
2646
2647         obj = intel_fb_obj(fb);
2648         if (obj->tiling_mode != I915_TILING_NONE)
2649                 dev_priv->preserve_bios_swizzle = true;
2650
2651         drm_framebuffer_reference(fb);
2652         primary->fb = primary->state->fb = fb;
2653         primary->crtc = primary->state->crtc = &intel_crtc->base;
2654         intel_crtc->base.state->plane_mask |= (1 << drm_plane_index(primary));
2655         obj->frontbuffer_bits |= to_intel_plane(primary)->frontbuffer_bit;
2656 }
2657
2658 static void i9xx_update_primary_plane(struct drm_plane *primary,
2659                                       const struct intel_crtc_state *crtc_state,
2660                                       const struct intel_plane_state *plane_state)
2661 {
2662         struct drm_device *dev = primary->dev;
2663         struct drm_i915_private *dev_priv = dev->dev_private;
2664         struct intel_crtc *intel_crtc = to_intel_crtc(crtc_state->base.crtc);
2665         struct drm_framebuffer *fb = plane_state->base.fb;
2666         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
2667         int plane = intel_crtc->plane;
2668         u32 linear_offset;
2669         u32 dspcntr;
2670         i915_reg_t reg = DSPCNTR(plane);
2671         unsigned int rotation = plane_state->base.rotation;
2672         int cpp = drm_format_plane_cpp(fb->pixel_format, 0);
2673         int x = plane_state->src.x1 >> 16;
2674         int y = plane_state->src.y1 >> 16;
2675
2676         dspcntr = DISPPLANE_GAMMA_ENABLE;
2677
2678         dspcntr |= DISPLAY_PLANE_ENABLE;
2679
2680         if (INTEL_INFO(dev)->gen < 4) {
2681                 if (intel_crtc->pipe == PIPE_B)
2682                         dspcntr |= DISPPLANE_SEL_PIPE_B;
2683
2684                 /* pipesrc and dspsize control the size that is scaled from,
2685                  * which should always be the user's requested size.
2686                  */
2687                 I915_WRITE(DSPSIZE(plane),
2688                            ((crtc_state->pipe_src_h - 1) << 16) |
2689                            (crtc_state->pipe_src_w - 1));
2690                 I915_WRITE(DSPPOS(plane), 0);
2691         } else if (IS_CHERRYVIEW(dev) && plane == PLANE_B) {
2692                 I915_WRITE(PRIMSIZE(plane),
2693                            ((crtc_state->pipe_src_h - 1) << 16) |
2694                            (crtc_state->pipe_src_w - 1));
2695                 I915_WRITE(PRIMPOS(plane), 0);
2696                 I915_WRITE(PRIMCNSTALPHA(plane), 0);
2697         }
2698
2699         switch (fb->pixel_format) {
2700         case DRM_FORMAT_C8:
2701                 dspcntr |= DISPPLANE_8BPP;
2702                 break;
2703         case DRM_FORMAT_XRGB1555:
2704                 dspcntr |= DISPPLANE_BGRX555;
2705                 break;
2706         case DRM_FORMAT_RGB565:
2707                 dspcntr |= DISPPLANE_BGRX565;
2708                 break;
2709         case DRM_FORMAT_XRGB8888:
2710                 dspcntr |= DISPPLANE_BGRX888;
2711                 break;
2712         case DRM_FORMAT_XBGR8888:
2713                 dspcntr |= DISPPLANE_RGBX888;
2714                 break;
2715         case DRM_FORMAT_XRGB2101010:
2716                 dspcntr |= DISPPLANE_BGRX101010;
2717                 break;
2718         case DRM_FORMAT_XBGR2101010:
2719                 dspcntr |= DISPPLANE_RGBX101010;
2720                 break;
2721         default:
2722                 BUG();
2723         }
2724
2725         if (INTEL_INFO(dev)->gen >= 4 &&
2726             obj->tiling_mode != I915_TILING_NONE)
2727                 dspcntr |= DISPPLANE_TILED;
2728
2729         if (IS_G4X(dev))
2730                 dspcntr |= DISPPLANE_TRICKLE_FEED_DISABLE;
2731
2732         linear_offset = y * fb->pitches[0] + x * cpp;
2733
2734         if (INTEL_INFO(dev)->gen >= 4) {
2735                 intel_crtc->dspaddr_offset =
2736                         intel_compute_tile_offset(&x, &y, fb, 0,
2737                                                   fb->pitches[0], rotation);
2738                 linear_offset -= intel_crtc->dspaddr_offset;
2739         } else {
2740                 intel_crtc->dspaddr_offset = linear_offset;
2741         }
2742
2743         if (rotation == BIT(DRM_ROTATE_180)) {
2744                 dspcntr |= DISPPLANE_ROTATE_180;
2745
2746                 x += (crtc_state->pipe_src_w - 1);
2747                 y += (crtc_state->pipe_src_h - 1);
2748
2749                 /* Finding the last pixel of the last line of the display
2750                 data and adding to linear_offset*/
2751                 linear_offset +=
2752                         (crtc_state->pipe_src_h - 1) * fb->pitches[0] +
2753                         (crtc_state->pipe_src_w - 1) * cpp;
2754         }
2755
2756         intel_crtc->adjusted_x = x;
2757         intel_crtc->adjusted_y = y;
2758
2759         I915_WRITE(reg, dspcntr);
2760
2761         I915_WRITE(DSPSTRIDE(plane), fb->pitches[0]);
2762         if (INTEL_INFO(dev)->gen >= 4) {
2763                 I915_WRITE(DSPSURF(plane),
2764                            i915_gem_obj_ggtt_offset(obj) + intel_crtc->dspaddr_offset);
2765                 I915_WRITE(DSPTILEOFF(plane), (y << 16) | x);
2766                 I915_WRITE(DSPLINOFF(plane), linear_offset);
2767         } else
2768                 I915_WRITE(DSPADDR(plane), i915_gem_obj_ggtt_offset(obj) + linear_offset);
2769         POSTING_READ(reg);
2770 }
2771
2772 static void i9xx_disable_primary_plane(struct drm_plane *primary,
2773                                        struct drm_crtc *crtc)
2774 {
2775         struct drm_device *dev = crtc->dev;
2776         struct drm_i915_private *dev_priv = dev->dev_private;
2777         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
2778         int plane = intel_crtc->plane;
2779
2780         I915_WRITE(DSPCNTR(plane), 0);
2781         if (INTEL_INFO(dev_priv)->gen >= 4)
2782                 I915_WRITE(DSPSURF(plane), 0);
2783         else
2784                 I915_WRITE(DSPADDR(plane), 0);
2785         POSTING_READ(DSPCNTR(plane));
2786 }
2787
2788 static void ironlake_update_primary_plane(struct drm_plane *primary,
2789                                           const struct intel_crtc_state *crtc_state,
2790                                           const struct intel_plane_state *plane_state)
2791 {
2792         struct drm_device *dev = primary->dev;
2793         struct drm_i915_private *dev_priv = dev->dev_private;
2794         struct intel_crtc *intel_crtc = to_intel_crtc(crtc_state->base.crtc);
2795         struct drm_framebuffer *fb = plane_state->base.fb;
2796         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
2797         int plane = intel_crtc->plane;
2798         u32 linear_offset;
2799         u32 dspcntr;
2800         i915_reg_t reg = DSPCNTR(plane);
2801         unsigned int rotation = plane_state->base.rotation;
2802         int cpp = drm_format_plane_cpp(fb->pixel_format, 0);
2803         int x = plane_state->src.x1 >> 16;
2804         int y = plane_state->src.y1 >> 16;
2805
2806         dspcntr = DISPPLANE_GAMMA_ENABLE;
2807         dspcntr |= DISPLAY_PLANE_ENABLE;
2808
2809         if (IS_HASWELL(dev) || IS_BROADWELL(dev))
2810                 dspcntr |= DISPPLANE_PIPE_CSC_ENABLE;
2811
2812         switch (fb->pixel_format) {
2813         case DRM_FORMAT_C8:
2814                 dspcntr |= DISPPLANE_8BPP;
2815                 break;
2816         case DRM_FORMAT_RGB565:
2817                 dspcntr |= DISPPLANE_BGRX565;
2818                 break;
2819         case DRM_FORMAT_XRGB8888:
2820                 dspcntr |= DISPPLANE_BGRX888;
2821                 break;
2822         case DRM_FORMAT_XBGR8888:
2823                 dspcntr |= DISPPLANE_RGBX888;
2824                 break;
2825         case DRM_FORMAT_XRGB2101010:
2826                 dspcntr |= DISPPLANE_BGRX101010;
2827                 break;
2828         case DRM_FORMAT_XBGR2101010:
2829                 dspcntr |= DISPPLANE_RGBX101010;
2830                 break;
2831         default:
2832                 BUG();
2833         }
2834
2835         if (obj->tiling_mode != I915_TILING_NONE)
2836                 dspcntr |= DISPPLANE_TILED;
2837
2838         if (!IS_HASWELL(dev) && !IS_BROADWELL(dev))
2839                 dspcntr |= DISPPLANE_TRICKLE_FEED_DISABLE;
2840
2841         linear_offset = y * fb->pitches[0] + x * cpp;
2842         intel_crtc->dspaddr_offset =
2843                 intel_compute_tile_offset(&x, &y, fb, 0,
2844                                           fb->pitches[0], rotation);
2845         linear_offset -= intel_crtc->dspaddr_offset;
2846         if (rotation == BIT(DRM_ROTATE_180)) {
2847                 dspcntr |= DISPPLANE_ROTATE_180;
2848
2849                 if (!IS_HASWELL(dev) && !IS_BROADWELL(dev)) {
2850                         x += (crtc_state->pipe_src_w - 1);
2851                         y += (crtc_state->pipe_src_h - 1);
2852
2853                         /* Finding the last pixel of the last line of the display
2854                         data and adding to linear_offset*/
2855                         linear_offset +=
2856                                 (crtc_state->pipe_src_h - 1) * fb->pitches[0] +
2857                                 (crtc_state->pipe_src_w - 1) * cpp;
2858                 }
2859         }
2860
2861         intel_crtc->adjusted_x = x;
2862         intel_crtc->adjusted_y = y;
2863
2864         I915_WRITE(reg, dspcntr);
2865
2866         I915_WRITE(DSPSTRIDE(plane), fb->pitches[0]);
2867         I915_WRITE(DSPSURF(plane),
2868                    i915_gem_obj_ggtt_offset(obj) + intel_crtc->dspaddr_offset);
2869         if (IS_HASWELL(dev) || IS_BROADWELL(dev)) {
2870                 I915_WRITE(DSPOFFSET(plane), (y << 16) | x);
2871         } else {
2872                 I915_WRITE(DSPTILEOFF(plane), (y << 16) | x);
2873                 I915_WRITE(DSPLINOFF(plane), linear_offset);
2874         }
2875         POSTING_READ(reg);
2876 }
2877
2878 u32 intel_fb_stride_alignment(const struct drm_i915_private *dev_priv,
2879                               uint64_t fb_modifier, uint32_t pixel_format)
2880 {
2881         if (fb_modifier == DRM_FORMAT_MOD_NONE) {
2882                 return 64;
2883         } else {
2884                 int cpp = drm_format_plane_cpp(pixel_format, 0);
2885
2886                 return intel_tile_width_bytes(dev_priv, fb_modifier, cpp);
2887         }
2888 }
2889
2890 u32 intel_plane_obj_offset(struct intel_plane *intel_plane,
2891                            struct drm_i915_gem_object *obj,
2892                            unsigned int plane)
2893 {
2894         struct i915_ggtt_view view;
2895         struct i915_vma *vma;
2896         u64 offset;
2897
2898         intel_fill_fb_ggtt_view(&view, intel_plane->base.state->fb,
2899                                 intel_plane->base.state->rotation);
2900
2901         vma = i915_gem_obj_to_ggtt_view(obj, &view);
2902         if (WARN(!vma, "ggtt vma for display object not found! (view=%u)\n",
2903                 view.type))
2904                 return -1;
2905
2906         offset = vma->node.start;
2907
2908         if (plane == 1) {
2909                 offset += vma->ggtt_view.params.rotated.uv_start_page *
2910                           PAGE_SIZE;
2911         }
2912
2913         WARN_ON(upper_32_bits(offset));
2914
2915         return lower_32_bits(offset);
2916 }
2917
2918 static void skl_detach_scaler(struct intel_crtc *intel_crtc, int id)
2919 {
2920         struct drm_device *dev = intel_crtc->base.dev;
2921         struct drm_i915_private *dev_priv = dev->dev_private;
2922
2923         I915_WRITE(SKL_PS_CTRL(intel_crtc->pipe, id), 0);
2924         I915_WRITE(SKL_PS_WIN_POS(intel_crtc->pipe, id), 0);
2925         I915_WRITE(SKL_PS_WIN_SZ(intel_crtc->pipe, id), 0);
2926 }
2927
2928 /*
2929  * This function detaches (aka. unbinds) unused scalers in hardware
2930  */
2931 static void skl_detach_scalers(struct intel_crtc *intel_crtc)
2932 {
2933         struct intel_crtc_scaler_state *scaler_state;
2934         int i;
2935
2936         scaler_state = &intel_crtc->config->scaler_state;
2937
2938         /* loop through and disable scalers that aren't in use */
2939         for (i = 0; i < intel_crtc->num_scalers; i++) {
2940                 if (!scaler_state->scalers[i].in_use)
2941                         skl_detach_scaler(intel_crtc, i);
2942         }
2943 }
2944
2945 u32 skl_plane_ctl_format(uint32_t pixel_format)
2946 {
2947         switch (pixel_format) {
2948         case DRM_FORMAT_C8:
2949                 return PLANE_CTL_FORMAT_INDEXED;
2950         case DRM_FORMAT_RGB565:
2951                 return PLANE_CTL_FORMAT_RGB_565;
2952         case DRM_FORMAT_XBGR8888:
2953                 return PLANE_CTL_FORMAT_XRGB_8888 | PLANE_CTL_ORDER_RGBX;
2954         case DRM_FORMAT_XRGB8888:
2955                 return PLANE_CTL_FORMAT_XRGB_8888;
2956         /*
2957          * XXX: For ARBG/ABGR formats we default to expecting scanout buffers
2958          * to be already pre-multiplied. We need to add a knob (or a different
2959          * DRM_FORMAT) for user-space to configure that.
2960          */
2961         case DRM_FORMAT_ABGR8888:
2962                 return PLANE_CTL_FORMAT_XRGB_8888 | PLANE_CTL_ORDER_RGBX |
2963                         PLANE_CTL_ALPHA_SW_PREMULTIPLY;
2964         case DRM_FORMAT_ARGB8888:
2965                 return PLANE_CTL_FORMAT_XRGB_8888 |
2966                         PLANE_CTL_ALPHA_SW_PREMULTIPLY;
2967         case DRM_FORMAT_XRGB2101010:
2968                 return PLANE_CTL_FORMAT_XRGB_2101010;
2969         case DRM_FORMAT_XBGR2101010:
2970                 return PLANE_CTL_ORDER_RGBX | PLANE_CTL_FORMAT_XRGB_2101010;
2971         case DRM_FORMAT_YUYV:
2972                 return PLANE_CTL_FORMAT_YUV422 | PLANE_CTL_YUV422_YUYV;
2973         case DRM_FORMAT_YVYU:
2974                 return PLANE_CTL_FORMAT_YUV422 | PLANE_CTL_YUV422_YVYU;
2975         case DRM_FORMAT_UYVY:
2976                 return PLANE_CTL_FORMAT_YUV422 | PLANE_CTL_YUV422_UYVY;
2977         case DRM_FORMAT_VYUY:
2978                 return PLANE_CTL_FORMAT_YUV422 | PLANE_CTL_YUV422_VYUY;
2979         default:
2980                 MISSING_CASE(pixel_format);
2981         }
2982
2983         return 0;
2984 }
2985
2986 u32 skl_plane_ctl_tiling(uint64_t fb_modifier)
2987 {
2988         switch (fb_modifier) {
2989         case DRM_FORMAT_MOD_NONE:
2990                 break;
2991         case I915_FORMAT_MOD_X_TILED:
2992                 return PLANE_CTL_TILED_X;
2993         case I915_FORMAT_MOD_Y_TILED:
2994                 return PLANE_CTL_TILED_Y;
2995         case I915_FORMAT_MOD_Yf_TILED:
2996                 return PLANE_CTL_TILED_YF;
2997         default:
2998                 MISSING_CASE(fb_modifier);
2999         }
3000
3001         return 0;
3002 }
3003
3004 u32 skl_plane_ctl_rotation(unsigned int rotation)
3005 {
3006         switch (rotation) {
3007         case BIT(DRM_ROTATE_0):
3008                 break;
3009         /*
3010          * DRM_ROTATE_ is counter clockwise to stay compatible with Xrandr
3011          * while i915 HW rotation is clockwise, thats why this swapping.
3012          */
3013         case BIT(DRM_ROTATE_90):
3014                 return PLANE_CTL_ROTATE_270;
3015         case BIT(DRM_ROTATE_180):
3016                 return PLANE_CTL_ROTATE_180;
3017         case BIT(DRM_ROTATE_270):
3018                 return PLANE_CTL_ROTATE_90;
3019         default:
3020                 MISSING_CASE(rotation);
3021         }
3022
3023         return 0;
3024 }
3025
3026 static void skylake_update_primary_plane(struct drm_plane *plane,
3027                                          const struct intel_crtc_state *crtc_state,
3028                                          const struct intel_plane_state *plane_state)
3029 {
3030         struct drm_device *dev = plane->dev;
3031         struct drm_i915_private *dev_priv = dev->dev_private;
3032         struct intel_crtc *intel_crtc = to_intel_crtc(crtc_state->base.crtc);
3033         struct drm_framebuffer *fb = plane_state->base.fb;
3034         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
3035         int pipe = intel_crtc->pipe;
3036         u32 plane_ctl, stride_div, stride;
3037         u32 tile_height, plane_offset, plane_size;
3038         unsigned int rotation = plane_state->base.rotation;
3039         int x_offset, y_offset;
3040         u32 surf_addr;
3041         int scaler_id = plane_state->scaler_id;
3042         int src_x = plane_state->src.x1 >> 16;
3043         int src_y = plane_state->src.y1 >> 16;
3044         int src_w = drm_rect_width(&plane_state->src) >> 16;
3045         int src_h = drm_rect_height(&plane_state->src) >> 16;
3046         int dst_x = plane_state->dst.x1;
3047         int dst_y = plane_state->dst.y1;
3048         int dst_w = drm_rect_width(&plane_state->dst);
3049         int dst_h = drm_rect_height(&plane_state->dst);
3050
3051         plane_ctl = PLANE_CTL_ENABLE |
3052                     PLANE_CTL_PIPE_GAMMA_ENABLE |
3053                     PLANE_CTL_PIPE_CSC_ENABLE;
3054
3055         plane_ctl |= skl_plane_ctl_format(fb->pixel_format);
3056         plane_ctl |= skl_plane_ctl_tiling(fb->modifier[0]);
3057         plane_ctl |= PLANE_CTL_PLANE_GAMMA_DISABLE;
3058         plane_ctl |= skl_plane_ctl_rotation(rotation);
3059
3060         stride_div = intel_fb_stride_alignment(dev_priv, fb->modifier[0],
3061                                                fb->pixel_format);
3062         surf_addr = intel_plane_obj_offset(to_intel_plane(plane), obj, 0);
3063
3064         WARN_ON(drm_rect_width(&plane_state->src) == 0);
3065
3066         if (intel_rotation_90_or_270(rotation)) {
3067                 int cpp = drm_format_plane_cpp(fb->pixel_format, 0);
3068
3069                 /* stride = Surface height in tiles */
3070                 tile_height = intel_tile_height(dev_priv, fb->modifier[0], cpp);
3071                 stride = DIV_ROUND_UP(fb->height, tile_height);
3072                 x_offset = stride * tile_height - src_y - src_h;
3073                 y_offset = src_x;
3074                 plane_size = (src_w - 1) << 16 | (src_h - 1);
3075         } else {
3076                 stride = fb->pitches[0] / stride_div;
3077                 x_offset = src_x;
3078                 y_offset = src_y;
3079                 plane_size = (src_h - 1) << 16 | (src_w - 1);
3080         }
3081         plane_offset = y_offset << 16 | x_offset;
3082
3083         intel_crtc->adjusted_x = x_offset;
3084         intel_crtc->adjusted_y = y_offset;
3085
3086         I915_WRITE(PLANE_CTL(pipe, 0), plane_ctl);
3087         I915_WRITE(PLANE_OFFSET(pipe, 0), plane_offset);
3088         I915_WRITE(PLANE_SIZE(pipe, 0), plane_size);
3089         I915_WRITE(PLANE_STRIDE(pipe, 0), stride);
3090
3091         if (scaler_id >= 0) {
3092                 uint32_t ps_ctrl = 0;
3093
3094                 WARN_ON(!dst_w || !dst_h);
3095                 ps_ctrl = PS_SCALER_EN | PS_PLANE_SEL(0) |
3096                         crtc_state->scaler_state.scalers[scaler_id].mode;
3097                 I915_WRITE(SKL_PS_CTRL(pipe, scaler_id), ps_ctrl);
3098                 I915_WRITE(SKL_PS_PWR_GATE(pipe, scaler_id), 0);
3099                 I915_WRITE(SKL_PS_WIN_POS(pipe, scaler_id), (dst_x << 16) | dst_y);
3100                 I915_WRITE(SKL_PS_WIN_SZ(pipe, scaler_id), (dst_w << 16) | dst_h);
3101                 I915_WRITE(PLANE_POS(pipe, 0), 0);
3102         } else {
3103                 I915_WRITE(PLANE_POS(pipe, 0), (dst_y << 16) | dst_x);
3104         }
3105
3106         I915_WRITE(PLANE_SURF(pipe, 0), surf_addr);
3107
3108         POSTING_READ(PLANE_SURF(pipe, 0));
3109 }
3110
3111 static void skylake_disable_primary_plane(struct drm_plane *primary,
3112                                           struct drm_crtc *crtc)
3113 {
3114         struct drm_device *dev = crtc->dev;
3115         struct drm_i915_private *dev_priv = dev->dev_private;
3116         int pipe = to_intel_crtc(crtc)->pipe;
3117
3118         I915_WRITE(PLANE_CTL(pipe, 0), 0);
3119         I915_WRITE(PLANE_SURF(pipe, 0), 0);
3120         POSTING_READ(PLANE_SURF(pipe, 0));
3121 }
3122
3123 /* Assume fb object is pinned & idle & fenced and just update base pointers */
3124 static int
3125 intel_pipe_set_base_atomic(struct drm_crtc *crtc, struct drm_framebuffer *fb,
3126                            int x, int y, enum mode_set_atomic state)
3127 {
3128         /* Support for kgdboc is disabled, this needs a major rework. */
3129         DRM_ERROR("legacy panic handler not supported any more.\n");
3130
3131         return -ENODEV;
3132 }
3133
3134 static void intel_complete_page_flips(struct drm_device *dev)
3135 {
3136         struct drm_crtc *crtc;
3137
3138         for_each_crtc(dev, crtc) {
3139                 struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
3140                 enum plane plane = intel_crtc->plane;
3141
3142                 intel_prepare_page_flip(dev, plane);
3143                 intel_finish_page_flip_plane(dev, plane);
3144         }
3145 }
3146
3147 static void intel_update_primary_planes(struct drm_device *dev)
3148 {
3149         struct drm_crtc *crtc;
3150
3151         for_each_crtc(dev, crtc) {
3152                 struct intel_plane *plane = to_intel_plane(crtc->primary);
3153                 struct intel_plane_state *plane_state;
3154
3155                 drm_modeset_lock_crtc(crtc, &plane->base);
3156                 plane_state = to_intel_plane_state(plane->base.state);
3157
3158                 if (plane_state->visible)
3159                         plane->update_plane(&plane->base,
3160                                             to_intel_crtc_state(crtc->state),
3161                                             plane_state);
3162
3163                 drm_modeset_unlock_crtc(crtc);
3164         }
3165 }
3166
3167 void intel_prepare_reset(struct drm_device *dev)
3168 {
3169         /* no reset support for gen2 */
3170         if (IS_GEN2(dev))
3171                 return;
3172
3173         /* reset doesn't touch the display */
3174         if (INTEL_INFO(dev)->gen >= 5 || IS_G4X(dev))
3175                 return;
3176
3177         drm_modeset_lock_all(dev);
3178         /*
3179          * Disabling the crtcs gracefully seems nicer. Also the
3180          * g33 docs say we should at least disable all the planes.
3181          */
3182         intel_display_suspend(dev);
3183 }
3184
3185 void intel_finish_reset(struct drm_device *dev)
3186 {
3187         struct drm_i915_private *dev_priv = to_i915(dev);
3188
3189         /*
3190          * Flips in the rings will be nuked by the reset,
3191          * so complete all pending flips so that user space
3192          * will get its events and not get stuck.
3193          */
3194         intel_complete_page_flips(dev);
3195
3196         /* no reset support for gen2 */
3197         if (IS_GEN2(dev))
3198                 return;
3199
3200         /* reset doesn't touch the display */
3201         if (INTEL_INFO(dev)->gen >= 5 || IS_G4X(dev)) {
3202                 /*
3203                  * Flips in the rings have been nuked by the reset,
3204                  * so update the base address of all primary
3205                  * planes to the the last fb to make sure we're
3206                  * showing the correct fb after a reset.
3207                  *
3208                  * FIXME: Atomic will make this obsolete since we won't schedule
3209                  * CS-based flips (which might get lost in gpu resets) any more.
3210                  */
3211                 intel_update_primary_planes(dev);
3212                 return;
3213         }
3214
3215         /*
3216          * The display has been reset as well,
3217          * so need a full re-initialization.
3218          */
3219         intel_runtime_pm_disable_interrupts(dev_priv);
3220         intel_runtime_pm_enable_interrupts(dev_priv);
3221
3222         intel_modeset_init_hw(dev);
3223
3224         spin_lock_irq(&dev_priv->irq_lock);
3225         if (dev_priv->display.hpd_irq_setup)
3226                 dev_priv->display.hpd_irq_setup(dev);
3227         spin_unlock_irq(&dev_priv->irq_lock);
3228
3229         intel_display_resume(dev);
3230
3231         intel_hpd_init(dev_priv);
3232
3233         drm_modeset_unlock_all(dev);
3234 }
3235
3236 static bool intel_crtc_has_pending_flip(struct drm_crtc *crtc)
3237 {
3238         struct drm_device *dev = crtc->dev;
3239         struct drm_i915_private *dev_priv = dev->dev_private;
3240         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
3241         bool pending;
3242
3243         if (i915_reset_in_progress(&dev_priv->gpu_error) ||
3244             intel_crtc->reset_counter != atomic_read(&dev_priv->gpu_error.reset_counter))
3245                 return false;
3246
3247         spin_lock_irq(&dev->event_lock);
3248         pending = to_intel_crtc(crtc)->unpin_work != NULL;
3249         spin_unlock_irq(&dev->event_lock);
3250
3251         return pending;
3252 }
3253
3254 static void intel_update_pipe_config(struct intel_crtc *crtc,
3255                                      struct intel_crtc_state *old_crtc_state)
3256 {
3257         struct drm_device *dev = crtc->base.dev;
3258         struct drm_i915_private *dev_priv = dev->dev_private;
3259         struct intel_crtc_state *pipe_config =
3260                 to_intel_crtc_state(crtc->base.state);
3261
3262         /* drm_atomic_helper_update_legacy_modeset_state might not be called. */
3263         crtc->base.mode = crtc->base.state->mode;
3264
3265         DRM_DEBUG_KMS("Updating pipe size %ix%i -> %ix%i\n",
3266                       old_crtc_state->pipe_src_w, old_crtc_state->pipe_src_h,
3267                       pipe_config->pipe_src_w, pipe_config->pipe_src_h);
3268
3269         if (HAS_DDI(dev))
3270                 intel_set_pipe_csc(&crtc->base);
3271
3272         /*
3273          * Update pipe size and adjust fitter if needed: the reason for this is
3274          * that in compute_mode_changes we check the native mode (not the pfit
3275          * mode) to see if we can flip rather than do a full mode set. In the
3276          * fastboot case, we'll flip, but if we don't update the pipesrc and
3277          * pfit state, we'll end up with a big fb scanned out into the wrong
3278          * sized surface.
3279          */
3280
3281         I915_WRITE(PIPESRC(crtc->pipe),
3282                    ((pipe_config->pipe_src_w - 1) << 16) |
3283                    (pipe_config->pipe_src_h - 1));
3284
3285         /* on skylake this is done by detaching scalers */
3286         if (INTEL_INFO(dev)->gen >= 9) {
3287                 skl_detach_scalers(crtc);
3288
3289                 if (pipe_config->pch_pfit.enabled)
3290                         skylake_pfit_enable(crtc);
3291         } else if (HAS_PCH_SPLIT(dev)) {
3292                 if (pipe_config->pch_pfit.enabled)
3293                         ironlake_pfit_enable(crtc);
3294                 else if (old_crtc_state->pch_pfit.enabled)
3295                         ironlake_pfit_disable(crtc, true);
3296         }
3297 }
3298
3299 static void intel_fdi_normal_train(struct drm_crtc *crtc)
3300 {
3301         struct drm_device *dev = crtc->dev;
3302         struct drm_i915_private *dev_priv = dev->dev_private;
3303         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
3304         int pipe = intel_crtc->pipe;
3305         i915_reg_t reg;
3306         u32 temp;
3307
3308         /* enable normal train */
3309         reg = FDI_TX_CTL(pipe);
3310         temp = I915_READ(reg);
3311         if (IS_IVYBRIDGE(dev)) {
3312                 temp &= ~FDI_LINK_TRAIN_NONE_IVB;
3313                 temp |= FDI_LINK_TRAIN_NONE_IVB | FDI_TX_ENHANCE_FRAME_ENABLE;
3314         } else {
3315                 temp &= ~FDI_LINK_TRAIN_NONE;
3316                 temp |= FDI_LINK_TRAIN_NONE | FDI_TX_ENHANCE_FRAME_ENABLE;
3317         }
3318         I915_WRITE(reg, temp);
3319
3320         reg = FDI_RX_CTL(pipe);
3321         temp = I915_READ(reg);
3322         if (HAS_PCH_CPT(dev)) {
3323                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
3324                 temp |= FDI_LINK_TRAIN_NORMAL_CPT;
3325         } else {
3326                 temp &= ~FDI_LINK_TRAIN_NONE;
3327                 temp |= FDI_LINK_TRAIN_NONE;
3328         }
3329         I915_WRITE(reg, temp | FDI_RX_ENHANCE_FRAME_ENABLE);
3330
3331         /* wait one idle pattern time */
3332         POSTING_READ(reg);
3333         udelay(1000);
3334
3335         /* IVB wants error correction enabled */
3336         if (IS_IVYBRIDGE(dev))
3337                 I915_WRITE(reg, I915_READ(reg) | FDI_FS_ERRC_ENABLE |
3338                            FDI_FE_ERRC_ENABLE);
3339 }
3340
3341 /* The FDI link training functions for ILK/Ibexpeak. */
3342 static void ironlake_fdi_link_train(struct drm_crtc *crtc)
3343 {
3344         struct drm_device *dev = crtc->dev;
3345         struct drm_i915_private *dev_priv = dev->dev_private;
3346         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
3347         int pipe = intel_crtc->pipe;
3348         i915_reg_t reg;
3349         u32 temp, tries;
3350
3351         /* FDI needs bits from pipe first */
3352         assert_pipe_enabled(dev_priv, pipe);
3353
3354         /* Train 1: umask FDI RX Interrupt symbol_lock and bit_lock bit
3355            for train result */
3356         reg = FDI_RX_IMR(pipe);
3357         temp = I915_READ(reg);
3358         temp &= ~FDI_RX_SYMBOL_LOCK;
3359         temp &= ~FDI_RX_BIT_LOCK;
3360         I915_WRITE(reg, temp);
3361         I915_READ(reg);
3362         udelay(150);
3363
3364         /* enable CPU FDI TX and PCH FDI RX */
3365         reg = FDI_TX_CTL(pipe);
3366         temp = I915_READ(reg);
3367         temp &= ~FDI_DP_PORT_WIDTH_MASK;
3368         temp |= FDI_DP_PORT_WIDTH(intel_crtc->config->fdi_lanes);
3369         temp &= ~FDI_LINK_TRAIN_NONE;
3370         temp |= FDI_LINK_TRAIN_PATTERN_1;
3371         I915_WRITE(reg, temp | FDI_TX_ENABLE);
3372
3373         reg = FDI_RX_CTL(pipe);
3374         temp = I915_READ(reg);
3375         temp &= ~FDI_LINK_TRAIN_NONE;
3376         temp |= FDI_LINK_TRAIN_PATTERN_1;
3377         I915_WRITE(reg, temp | FDI_RX_ENABLE);
3378
3379         POSTING_READ(reg);
3380         udelay(150);
3381
3382         /* Ironlake workaround, enable clock pointer after FDI enable*/
3383         I915_WRITE(FDI_RX_CHICKEN(pipe), FDI_RX_PHASE_SYNC_POINTER_OVR);
3384         I915_WRITE(FDI_RX_CHICKEN(pipe), FDI_RX_PHASE_SYNC_POINTER_OVR |
3385                    FDI_RX_PHASE_SYNC_POINTER_EN);
3386
3387         reg = FDI_RX_IIR(pipe);
3388         for (tries = 0; tries < 5; tries++) {
3389                 temp = I915_READ(reg);
3390                 DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
3391
3392                 if ((temp & FDI_RX_BIT_LOCK)) {
3393                         DRM_DEBUG_KMS("FDI train 1 done.\n");
3394                         I915_WRITE(reg, temp | FDI_RX_BIT_LOCK);
3395                         break;
3396                 }
3397         }
3398         if (tries == 5)
3399                 DRM_ERROR("FDI train 1 fail!\n");
3400
3401         /* Train 2 */
3402         reg = FDI_TX_CTL(pipe);
3403         temp = I915_READ(reg);
3404         temp &= ~FDI_LINK_TRAIN_NONE;
3405         temp |= FDI_LINK_TRAIN_PATTERN_2;
3406         I915_WRITE(reg, temp);
3407
3408         reg = FDI_RX_CTL(pipe);
3409         temp = I915_READ(reg);
3410         temp &= ~FDI_LINK_TRAIN_NONE;
3411         temp |= FDI_LINK_TRAIN_PATTERN_2;
3412         I915_WRITE(reg, temp);
3413
3414         POSTING_READ(reg);
3415         udelay(150);
3416
3417         reg = FDI_RX_IIR(pipe);
3418         for (tries = 0; tries < 5; tries++) {
3419                 temp = I915_READ(reg);
3420                 DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
3421
3422                 if (temp & FDI_RX_SYMBOL_LOCK) {
3423                         I915_WRITE(reg, temp | FDI_RX_SYMBOL_LOCK);
3424                         DRM_DEBUG_KMS("FDI train 2 done.\n");
3425                         break;
3426                 }
3427         }
3428         if (tries == 5)
3429                 DRM_ERROR("FDI train 2 fail!\n");
3430
3431         DRM_DEBUG_KMS("FDI train done\n");
3432
3433 }
3434
3435 static const int snb_b_fdi_train_param[] = {
3436         FDI_LINK_TRAIN_400MV_0DB_SNB_B,
3437         FDI_LINK_TRAIN_400MV_6DB_SNB_B,
3438         FDI_LINK_TRAIN_600MV_3_5DB_SNB_B,
3439         FDI_LINK_TRAIN_800MV_0DB_SNB_B,
3440 };
3441
3442 /* The FDI link training functions for SNB/Cougarpoint. */
3443 static void gen6_fdi_link_train(struct drm_crtc *crtc)
3444 {
3445         struct drm_device *dev = crtc->dev;
3446         struct drm_i915_private *dev_priv = dev->dev_private;
3447         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
3448         int pipe = intel_crtc->pipe;
3449         i915_reg_t reg;
3450         u32 temp, i, retry;
3451
3452         /* Train 1: umask FDI RX Interrupt symbol_lock and bit_lock bit
3453            for train result */
3454         reg = FDI_RX_IMR(pipe);
3455         temp = I915_READ(reg);
3456         temp &= ~FDI_RX_SYMBOL_LOCK;
3457         temp &= ~FDI_RX_BIT_LOCK;
3458         I915_WRITE(reg, temp);
3459
3460         POSTING_READ(reg);
3461         udelay(150);
3462
3463         /* enable CPU FDI TX and PCH FDI RX */
3464         reg = FDI_TX_CTL(pipe);
3465         temp = I915_READ(reg);
3466         temp &= ~FDI_DP_PORT_WIDTH_MASK;
3467         temp |= FDI_DP_PORT_WIDTH(intel_crtc->config->fdi_lanes);
3468         temp &= ~FDI_LINK_TRAIN_NONE;
3469         temp |= FDI_LINK_TRAIN_PATTERN_1;
3470         temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
3471         /* SNB-B */
3472         temp |= FDI_LINK_TRAIN_400MV_0DB_SNB_B;
3473         I915_WRITE(reg, temp | FDI_TX_ENABLE);
3474
3475         I915_WRITE(FDI_RX_MISC(pipe),
3476                    FDI_RX_TP1_TO_TP2_48 | FDI_RX_FDI_DELAY_90);
3477
3478         reg = FDI_RX_CTL(pipe);
3479         temp = I915_READ(reg);
3480         if (HAS_PCH_CPT(dev)) {
3481                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
3482                 temp |= FDI_LINK_TRAIN_PATTERN_1_CPT;
3483         } else {
3484                 temp &= ~FDI_LINK_TRAIN_NONE;
3485                 temp |= FDI_LINK_TRAIN_PATTERN_1;
3486         }
3487         I915_WRITE(reg, temp | FDI_RX_ENABLE);
3488
3489         POSTING_READ(reg);
3490         udelay(150);
3491
3492         for (i = 0; i < 4; i++) {
3493                 reg = FDI_TX_CTL(pipe);
3494                 temp = I915_READ(reg);
3495                 temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
3496                 temp |= snb_b_fdi_train_param[i];
3497                 I915_WRITE(reg, temp);
3498
3499                 POSTING_READ(reg);
3500                 udelay(500);
3501
3502                 for (retry = 0; retry < 5; retry++) {
3503                         reg = FDI_RX_IIR(pipe);
3504                         temp = I915_READ(reg);
3505                         DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
3506                         if (temp & FDI_RX_BIT_LOCK) {
3507                                 I915_WRITE(reg, temp | FDI_RX_BIT_LOCK);
3508                                 DRM_DEBUG_KMS("FDI train 1 done.\n");
3509                                 break;
3510                         }
3511                         udelay(50);
3512                 }
3513                 if (retry < 5)
3514                         break;
3515         }
3516         if (i == 4)
3517                 DRM_ERROR("FDI train 1 fail!\n");
3518
3519         /* Train 2 */
3520         reg = FDI_TX_CTL(pipe);
3521         temp = I915_READ(reg);
3522         temp &= ~FDI_LINK_TRAIN_NONE;
3523         temp |= FDI_LINK_TRAIN_PATTERN_2;
3524         if (IS_GEN6(dev)) {
3525                 temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
3526                 /* SNB-B */
3527                 temp |= FDI_LINK_TRAIN_400MV_0DB_SNB_B;
3528         }
3529         I915_WRITE(reg, temp);
3530
3531         reg = FDI_RX_CTL(pipe);
3532         temp = I915_READ(reg);
3533         if (HAS_PCH_CPT(dev)) {
3534                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
3535                 temp |= FDI_LINK_TRAIN_PATTERN_2_CPT;
3536         } else {
3537                 temp &= ~FDI_LINK_TRAIN_NONE;
3538                 temp |= FDI_LINK_TRAIN_PATTERN_2;
3539         }
3540         I915_WRITE(reg, temp);
3541
3542         POSTING_READ(reg);
3543         udelay(150);
3544
3545         for (i = 0; i < 4; i++) {
3546                 reg = FDI_TX_CTL(pipe);
3547                 temp = I915_READ(reg);
3548                 temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
3549                 temp |= snb_b_fdi_train_param[i];
3550                 I915_WRITE(reg, temp);
3551
3552                 POSTING_READ(reg);
3553                 udelay(500);
3554
3555                 for (retry = 0; retry < 5; retry++) {
3556                         reg = FDI_RX_IIR(pipe);
3557                         temp = I915_READ(reg);
3558                         DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
3559                         if (temp & FDI_RX_SYMBOL_LOCK) {
3560                                 I915_WRITE(reg, temp | FDI_RX_SYMBOL_LOCK);
3561                                 DRM_DEBUG_KMS("FDI train 2 done.\n");
3562                                 break;
3563                         }
3564                         udelay(50);
3565                 }
3566                 if (retry < 5)
3567                         break;
3568         }
3569         if (i == 4)
3570                 DRM_ERROR("FDI train 2 fail!\n");
3571
3572         DRM_DEBUG_KMS("FDI train done.\n");
3573 }
3574
3575 /* Manual link training for Ivy Bridge A0 parts */
3576 static void ivb_manual_fdi_link_train(struct drm_crtc *crtc)
3577 {
3578         struct drm_device *dev = crtc->dev;
3579         struct drm_i915_private *dev_priv = dev->dev_private;
3580         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
3581         int pipe = intel_crtc->pipe;
3582         i915_reg_t reg;
3583         u32 temp, i, j;
3584
3585         /* Train 1: umask FDI RX Interrupt symbol_lock and bit_lock bit
3586            for train result */
3587         reg = FDI_RX_IMR(pipe);
3588         temp = I915_READ(reg);
3589         temp &= ~FDI_RX_SYMBOL_LOCK;
3590         temp &= ~FDI_RX_BIT_LOCK;
3591         I915_WRITE(reg, temp);
3592
3593         POSTING_READ(reg);
3594         udelay(150);
3595
3596         DRM_DEBUG_KMS("FDI_RX_IIR before link train 0x%x\n",
3597                       I915_READ(FDI_RX_IIR(pipe)));
3598
3599         /* Try each vswing and preemphasis setting twice before moving on */
3600         for (j = 0; j < ARRAY_SIZE(snb_b_fdi_train_param) * 2; j++) {
3601                 /* disable first in case we need to retry */
3602                 reg = FDI_TX_CTL(pipe);
3603                 temp = I915_READ(reg);
3604                 temp &= ~(FDI_LINK_TRAIN_AUTO | FDI_LINK_TRAIN_NONE_IVB);
3605                 temp &= ~FDI_TX_ENABLE;
3606                 I915_WRITE(reg, temp);
3607
3608                 reg = FDI_RX_CTL(pipe);
3609                 temp = I915_READ(reg);
3610                 temp &= ~FDI_LINK_TRAIN_AUTO;
3611                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
3612                 temp &= ~FDI_RX_ENABLE;
3613                 I915_WRITE(reg, temp);
3614
3615                 /* enable CPU FDI TX and PCH FDI RX */
3616                 reg = FDI_TX_CTL(pipe);
3617                 temp = I915_READ(reg);
3618                 temp &= ~FDI_DP_PORT_WIDTH_MASK;
3619                 temp |= FDI_DP_PORT_WIDTH(intel_crtc->config->fdi_lanes);
3620                 temp |= FDI_LINK_TRAIN_PATTERN_1_IVB;
3621                 temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
3622                 temp |= snb_b_fdi_train_param[j/2];
3623                 temp |= FDI_COMPOSITE_SYNC;
3624                 I915_WRITE(reg, temp | FDI_TX_ENABLE);
3625
3626                 I915_WRITE(FDI_RX_MISC(pipe),
3627                            FDI_RX_TP1_TO_TP2_48 | FDI_RX_FDI_DELAY_90);
3628
3629                 reg = FDI_RX_CTL(pipe);
3630                 temp = I915_READ(reg);
3631                 temp |= FDI_LINK_TRAIN_PATTERN_1_CPT;
3632                 temp |= FDI_COMPOSITE_SYNC;
3633                 I915_WRITE(reg, temp | FDI_RX_ENABLE);
3634
3635                 POSTING_READ(reg);
3636                 udelay(1); /* should be 0.5us */
3637
3638                 for (i = 0; i < 4; i++) {
3639                         reg = FDI_RX_IIR(pipe);
3640                         temp = I915_READ(reg);
3641                         DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
3642
3643                         if (temp & FDI_RX_BIT_LOCK ||
3644                             (I915_READ(reg) & FDI_RX_BIT_LOCK)) {
3645                                 I915_WRITE(reg, temp | FDI_RX_BIT_LOCK);
3646                                 DRM_DEBUG_KMS("FDI train 1 done, level %i.\n",
3647                                               i);
3648                                 break;
3649                         }
3650                         udelay(1); /* should be 0.5us */
3651                 }
3652                 if (i == 4) {
3653                         DRM_DEBUG_KMS("FDI train 1 fail on vswing %d\n", j / 2);
3654                         continue;
3655                 }
3656
3657                 /* Train 2 */
3658                 reg = FDI_TX_CTL(pipe);
3659                 temp = I915_READ(reg);
3660                 temp &= ~FDI_LINK_TRAIN_NONE_IVB;
3661                 temp |= FDI_LINK_TRAIN_PATTERN_2_IVB;
3662                 I915_WRITE(reg, temp);
3663
3664                 reg = FDI_RX_CTL(pipe);
3665                 temp = I915_READ(reg);
3666                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
3667                 temp |= FDI_LINK_TRAIN_PATTERN_2_CPT;
3668                 I915_WRITE(reg, temp);
3669
3670                 POSTING_READ(reg);
3671                 udelay(2); /* should be 1.5us */
3672
3673                 for (i = 0; i < 4; i++) {
3674                         reg = FDI_RX_IIR(pipe);
3675                         temp = I915_READ(reg);
3676                         DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
3677
3678                         if (temp & FDI_RX_SYMBOL_LOCK ||
3679                             (I915_READ(reg) & FDI_RX_SYMBOL_LOCK)) {
3680                                 I915_WRITE(reg, temp | FDI_RX_SYMBOL_LOCK);
3681                                 DRM_DEBUG_KMS("FDI train 2 done, level %i.\n",
3682                                               i);
3683                                 goto train_done;
3684                         }
3685                         udelay(2); /* should be 1.5us */
3686                 }
3687                 if (i == 4)
3688                         DRM_DEBUG_KMS("FDI train 2 fail on vswing %d\n", j / 2);
3689         }
3690
3691 train_done:
3692         DRM_DEBUG_KMS("FDI train done.\n");
3693 }
3694
3695 static void ironlake_fdi_pll_enable(struct intel_crtc *intel_crtc)
3696 {
3697         struct drm_device *dev = intel_crtc->base.dev;
3698         struct drm_i915_private *dev_priv = dev->dev_private;
3699         int pipe = intel_crtc->pipe;
3700         i915_reg_t reg;
3701         u32 temp;
3702
3703         /* enable PCH FDI RX PLL, wait warmup plus DMI latency */
3704         reg = FDI_RX_CTL(pipe);
3705         temp = I915_READ(reg);
3706         temp &= ~(FDI_DP_PORT_WIDTH_MASK | (0x7 << 16));
3707         temp |= FDI_DP_PORT_WIDTH(intel_crtc->config->fdi_lanes);
3708         temp |= (I915_READ(PIPECONF(pipe)) & PIPECONF_BPC_MASK) << 11;
3709         I915_WRITE(reg, temp | FDI_RX_PLL_ENABLE);
3710
3711         POSTING_READ(reg);
3712         udelay(200);
3713
3714         /* Switch from Rawclk to PCDclk */
3715         temp = I915_READ(reg);
3716         I915_WRITE(reg, temp | FDI_PCDCLK);
3717
3718         POSTING_READ(reg);
3719         udelay(200);
3720
3721         /* Enable CPU FDI TX PLL, always on for Ironlake */
3722         reg = FDI_TX_CTL(pipe);
3723         temp = I915_READ(reg);
3724         if ((temp & FDI_TX_PLL_ENABLE) == 0) {
3725                 I915_WRITE(reg, temp | FDI_TX_PLL_ENABLE);
3726
3727                 POSTING_READ(reg);
3728                 udelay(100);
3729         }
3730 }
3731
3732 static void ironlake_fdi_pll_disable(struct intel_crtc *intel_crtc)
3733 {
3734         struct drm_device *dev = intel_crtc->base.dev;
3735         struct drm_i915_private *dev_priv = dev->dev_private;
3736         int pipe = intel_crtc->pipe;
3737         i915_reg_t reg;
3738         u32 temp;
3739
3740         /* Switch from PCDclk to Rawclk */
3741         reg = FDI_RX_CTL(pipe);
3742         temp = I915_READ(reg);
3743         I915_WRITE(reg, temp & ~FDI_PCDCLK);
3744
3745         /* Disable CPU FDI TX PLL */
3746         reg = FDI_TX_CTL(pipe);
3747         temp = I915_READ(reg);
3748         I915_WRITE(reg, temp & ~FDI_TX_PLL_ENABLE);
3749
3750         POSTING_READ(reg);
3751         udelay(100);
3752
3753         reg = FDI_RX_CTL(pipe);
3754         temp = I915_READ(reg);
3755         I915_WRITE(reg, temp & ~FDI_RX_PLL_ENABLE);
3756
3757         /* Wait for the clocks to turn off. */
3758         POSTING_READ(reg);
3759         udelay(100);
3760 }
3761
3762 static void ironlake_fdi_disable(struct drm_crtc *crtc)
3763 {
3764         struct drm_device *dev = crtc->dev;
3765         struct drm_i915_private *dev_priv = dev->dev_private;
3766         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
3767         int pipe = intel_crtc->pipe;
3768         i915_reg_t reg;
3769         u32 temp;
3770
3771         /* disable CPU FDI tx and PCH FDI rx */
3772         reg = FDI_TX_CTL(pipe);
3773         temp = I915_READ(reg);
3774         I915_WRITE(reg, temp & ~FDI_TX_ENABLE);
3775         POSTING_READ(reg);
3776
3777         reg = FDI_RX_CTL(pipe);
3778         temp = I915_READ(reg);
3779         temp &= ~(0x7 << 16);
3780         temp |= (I915_READ(PIPECONF(pipe)) & PIPECONF_BPC_MASK) << 11;
3781         I915_WRITE(reg, temp & ~FDI_RX_ENABLE);
3782
3783         POSTING_READ(reg);
3784         udelay(100);
3785
3786         /* Ironlake workaround, disable clock pointer after downing FDI */
3787         if (HAS_PCH_IBX(dev))
3788                 I915_WRITE(FDI_RX_CHICKEN(pipe), FDI_RX_PHASE_SYNC_POINTER_OVR);
3789
3790         /* still set train pattern 1 */
3791         reg = FDI_TX_CTL(pipe);
3792         temp = I915_READ(reg);
3793         temp &= ~FDI_LINK_TRAIN_NONE;
3794         temp |= FDI_LINK_TRAIN_PATTERN_1;
3795         I915_WRITE(reg, temp);
3796
3797         reg = FDI_RX_CTL(pipe);
3798         temp = I915_READ(reg);
3799         if (HAS_PCH_CPT(dev)) {
3800                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
3801                 temp |= FDI_LINK_TRAIN_PATTERN_1_CPT;
3802         } else {
3803                 temp &= ~FDI_LINK_TRAIN_NONE;
3804                 temp |= FDI_LINK_TRAIN_PATTERN_1;
3805         }
3806         /* BPC in FDI rx is consistent with that in PIPECONF */
3807         temp &= ~(0x07 << 16);
3808         temp |= (I915_READ(PIPECONF(pipe)) & PIPECONF_BPC_MASK) << 11;
3809         I915_WRITE(reg, temp);
3810
3811         POSTING_READ(reg);
3812         udelay(100);
3813 }
3814
3815 bool intel_has_pending_fb_unpin(struct drm_device *dev)
3816 {
3817         struct intel_crtc *crtc;
3818
3819         /* Note that we don't need to be called with mode_config.lock here
3820          * as our list of CRTC objects is static for the lifetime of the
3821          * device and so cannot disappear as we iterate. Similarly, we can
3822          * happily treat the predicates as racy, atomic checks as userspace
3823          * cannot claim and pin a new fb without at least acquring the
3824          * struct_mutex and so serialising with us.
3825          */
3826         for_each_intel_crtc(dev, crtc) {
3827                 if (atomic_read(&crtc->unpin_work_count) == 0)
3828                         continue;
3829
3830                 if (crtc->unpin_work)
3831                         intel_wait_for_vblank(dev, crtc->pipe);
3832
3833                 return true;
3834         }
3835
3836         return false;
3837 }
3838
3839 static void page_flip_completed(struct intel_crtc *intel_crtc)
3840 {
3841         struct drm_i915_private *dev_priv = to_i915(intel_crtc->base.dev);
3842         struct intel_unpin_work *work = intel_crtc->unpin_work;
3843
3844         /* ensure that the unpin work is consistent wrt ->pending. */
3845         smp_rmb();
3846         intel_crtc->unpin_work = NULL;
3847
3848         if (work->event)
3849                 drm_send_vblank_event(intel_crtc->base.dev,
3850                                       intel_crtc->pipe,
3851                                       work->event);
3852
3853         drm_crtc_vblank_put(&intel_crtc->base);
3854
3855         wake_up_all(&dev_priv->pending_flip_queue);
3856         queue_work(dev_priv->wq, &work->work);
3857
3858         trace_i915_flip_complete(intel_crtc->plane,
3859                                  work->pending_flip_obj);
3860 }
3861
3862 static int intel_crtc_wait_for_pending_flips(struct drm_crtc *crtc)
3863 {
3864         struct drm_device *dev = crtc->dev;
3865         struct drm_i915_private *dev_priv = dev->dev_private;
3866         long ret;
3867
3868         WARN_ON(waitqueue_active(&dev_priv->pending_flip_queue));
3869
3870         ret = wait_event_interruptible_timeout(
3871                                         dev_priv->pending_flip_queue,
3872                                         !intel_crtc_has_pending_flip(crtc),
3873                                         60*HZ);
3874
3875         if (ret < 0)
3876                 return ret;
3877
3878         if (ret == 0) {
3879                 struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
3880
3881                 spin_lock_irq(&dev->event_lock);
3882                 if (intel_crtc->unpin_work) {
3883                         WARN_ONCE(1, "Removing stuck page flip\n");
3884                         page_flip_completed(intel_crtc);
3885                 }
3886                 spin_unlock_irq(&dev->event_lock);
3887         }
3888
3889         return 0;
3890 }
3891
3892 static void lpt_disable_iclkip(struct drm_i915_private *dev_priv)
3893 {
3894         u32 temp;
3895
3896         I915_WRITE(PIXCLK_GATE, PIXCLK_GATE_GATE);
3897
3898         mutex_lock(&dev_priv->sb_lock);
3899
3900         temp = intel_sbi_read(dev_priv, SBI_SSCCTL6, SBI_ICLK);
3901         temp |= SBI_SSCCTL_DISABLE;
3902         intel_sbi_write(dev_priv, SBI_SSCCTL6, temp, SBI_ICLK);
3903
3904         mutex_unlock(&dev_priv->sb_lock);
3905 }
3906
3907 /* Program iCLKIP clock to the desired frequency */
3908 static void lpt_program_iclkip(struct drm_crtc *crtc)
3909 {
3910         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
3911         int clock = to_intel_crtc(crtc)->config->base.adjusted_mode.crtc_clock;
3912         u32 divsel, phaseinc, auxdiv, phasedir = 0;
3913         u32 temp;
3914
3915         lpt_disable_iclkip(dev_priv);
3916
3917         /* The iCLK virtual clock root frequency is in MHz,
3918          * but the adjusted_mode->crtc_clock in in KHz. To get the
3919          * divisors, it is necessary to divide one by another, so we
3920          * convert the virtual clock precision to KHz here for higher
3921          * precision.
3922          */
3923         for (auxdiv = 0; auxdiv < 2; auxdiv++) {
3924                 u32 iclk_virtual_root_freq = 172800 * 1000;
3925                 u32 iclk_pi_range = 64;
3926                 u32 desired_divisor;
3927
3928                 desired_divisor = DIV_ROUND_CLOSEST(iclk_virtual_root_freq,
3929                                                     clock << auxdiv);
3930                 divsel = (desired_divisor / iclk_pi_range) - 2;
3931                 phaseinc = desired_divisor % iclk_pi_range;
3932
3933                 /*
3934                  * Near 20MHz is a corner case which is
3935                  * out of range for the 7-bit divisor
3936                  */
3937                 if (divsel <= 0x7f)
3938                         break;
3939         }
3940
3941         /* This should not happen with any sane values */
3942         WARN_ON(SBI_SSCDIVINTPHASE_DIVSEL(divsel) &
3943                 ~SBI_SSCDIVINTPHASE_DIVSEL_MASK);
3944         WARN_ON(SBI_SSCDIVINTPHASE_DIR(phasedir) &
3945                 ~SBI_SSCDIVINTPHASE_INCVAL_MASK);
3946
3947         DRM_DEBUG_KMS("iCLKIP clock: found settings for %dKHz refresh rate: auxdiv=%x, divsel=%x, phasedir=%x, phaseinc=%x\n",
3948                         clock,
3949                         auxdiv,
3950                         divsel,
3951                         phasedir,
3952                         phaseinc);
3953
3954         mutex_lock(&dev_priv->sb_lock);
3955
3956         /* Program SSCDIVINTPHASE6 */
3957         temp = intel_sbi_read(dev_priv, SBI_SSCDIVINTPHASE6, SBI_ICLK);
3958         temp &= ~SBI_SSCDIVINTPHASE_DIVSEL_MASK;
3959         temp |= SBI_SSCDIVINTPHASE_DIVSEL(divsel);
3960         temp &= ~SBI_SSCDIVINTPHASE_INCVAL_MASK;
3961         temp |= SBI_SSCDIVINTPHASE_INCVAL(phaseinc);
3962         temp |= SBI_SSCDIVINTPHASE_DIR(phasedir);
3963         temp |= SBI_SSCDIVINTPHASE_PROPAGATE;
3964         intel_sbi_write(dev_priv, SBI_SSCDIVINTPHASE6, temp, SBI_ICLK);
3965
3966         /* Program SSCAUXDIV */
3967         temp = intel_sbi_read(dev_priv, SBI_SSCAUXDIV6, SBI_ICLK);
3968         temp &= ~SBI_SSCAUXDIV_FINALDIV2SEL(1);
3969         temp |= SBI_SSCAUXDIV_FINALDIV2SEL(auxdiv);
3970         intel_sbi_write(dev_priv, SBI_SSCAUXDIV6, temp, SBI_ICLK);
3971
3972         /* Enable modulator and associated divider */
3973         temp = intel_sbi_read(dev_priv, SBI_SSCCTL6, SBI_ICLK);
3974         temp &= ~SBI_SSCCTL_DISABLE;
3975         intel_sbi_write(dev_priv, SBI_SSCCTL6, temp, SBI_ICLK);
3976
3977         mutex_unlock(&dev_priv->sb_lock);
3978
3979         /* Wait for initialization time */
3980         udelay(24);
3981
3982         I915_WRITE(PIXCLK_GATE, PIXCLK_GATE_UNGATE);
3983 }
3984
3985 int lpt_get_iclkip(struct drm_i915_private *dev_priv)
3986 {
3987         u32 divsel, phaseinc, auxdiv;
3988         u32 iclk_virtual_root_freq = 172800 * 1000;
3989         u32 iclk_pi_range = 64;
3990         u32 desired_divisor;
3991         u32 temp;
3992
3993         if ((I915_READ(PIXCLK_GATE) & PIXCLK_GATE_UNGATE) == 0)
3994                 return 0;
3995
3996         mutex_lock(&dev_priv->sb_lock);
3997
3998         temp = intel_sbi_read(dev_priv, SBI_SSCCTL6, SBI_ICLK);
3999         if (temp & SBI_SSCCTL_DISABLE) {
4000                 mutex_unlock(&dev_priv->sb_lock);
4001                 return 0;
4002         }
4003
4004         temp = intel_sbi_read(dev_priv, SBI_SSCDIVINTPHASE6, SBI_ICLK);
4005         divsel = (temp & SBI_SSCDIVINTPHASE_DIVSEL_MASK) >>
4006                 SBI_SSCDIVINTPHASE_DIVSEL_SHIFT;
4007         phaseinc = (temp & SBI_SSCDIVINTPHASE_INCVAL_MASK) >>
4008                 SBI_SSCDIVINTPHASE_INCVAL_SHIFT;
4009
4010         temp = intel_sbi_read(dev_priv, SBI_SSCAUXDIV6, SBI_ICLK);
4011         auxdiv = (temp & SBI_SSCAUXDIV_FINALDIV2SEL_MASK) >>
4012                 SBI_SSCAUXDIV_FINALDIV2SEL_SHIFT;
4013
4014         mutex_unlock(&dev_priv->sb_lock);
4015
4016         desired_divisor = (divsel + 2) * iclk_pi_range + phaseinc;
4017
4018         return DIV_ROUND_CLOSEST(iclk_virtual_root_freq,
4019                                  desired_divisor << auxdiv);
4020 }
4021
4022 static void ironlake_pch_transcoder_set_timings(struct intel_crtc *crtc,
4023                                                 enum pipe pch_transcoder)
4024 {
4025         struct drm_device *dev = crtc->base.dev;
4026         struct drm_i915_private *dev_priv = dev->dev_private;
4027         enum transcoder cpu_transcoder = crtc->config->cpu_transcoder;
4028
4029         I915_WRITE(PCH_TRANS_HTOTAL(pch_transcoder),
4030                    I915_READ(HTOTAL(cpu_transcoder)));
4031         I915_WRITE(PCH_TRANS_HBLANK(pch_transcoder),
4032                    I915_READ(HBLANK(cpu_transcoder)));
4033         I915_WRITE(PCH_TRANS_HSYNC(pch_transcoder),
4034                    I915_READ(HSYNC(cpu_transcoder)));
4035
4036         I915_WRITE(PCH_TRANS_VTOTAL(pch_transcoder),
4037                    I915_READ(VTOTAL(cpu_transcoder)));
4038         I915_WRITE(PCH_TRANS_VBLANK(pch_transcoder),
4039                    I915_READ(VBLANK(cpu_transcoder)));
4040         I915_WRITE(PCH_TRANS_VSYNC(pch_transcoder),
4041                    I915_READ(VSYNC(cpu_transcoder)));
4042         I915_WRITE(PCH_TRANS_VSYNCSHIFT(pch_transcoder),
4043                    I915_READ(VSYNCSHIFT(cpu_transcoder)));
4044 }
4045
4046 static void cpt_set_fdi_bc_bifurcation(struct drm_device *dev, bool enable)
4047 {
4048         struct drm_i915_private *dev_priv = dev->dev_private;
4049         uint32_t temp;
4050
4051         temp = I915_READ(SOUTH_CHICKEN1);
4052         if (!!(temp & FDI_BC_BIFURCATION_SELECT) == enable)
4053                 return;
4054
4055         WARN_ON(I915_READ(FDI_RX_CTL(PIPE_B)) & FDI_RX_ENABLE);
4056         WARN_ON(I915_READ(FDI_RX_CTL(PIPE_C)) & FDI_RX_ENABLE);
4057
4058         temp &= ~FDI_BC_BIFURCATION_SELECT;
4059         if (enable)
4060                 temp |= FDI_BC_BIFURCATION_SELECT;
4061
4062         DRM_DEBUG_KMS("%sabling fdi C rx\n", enable ? "en" : "dis");
4063         I915_WRITE(SOUTH_CHICKEN1, temp);
4064         POSTING_READ(SOUTH_CHICKEN1);
4065 }
4066
4067 static void ivybridge_update_fdi_bc_bifurcation(struct intel_crtc *intel_crtc)
4068 {
4069         struct drm_device *dev = intel_crtc->base.dev;
4070
4071         switch (intel_crtc->pipe) {
4072         case PIPE_A:
4073                 break;
4074         case PIPE_B:
4075                 if (intel_crtc->config->fdi_lanes > 2)
4076                         cpt_set_fdi_bc_bifurcation(dev, false);
4077                 else
4078                         cpt_set_fdi_bc_bifurcation(dev, true);
4079
4080                 break;
4081         case PIPE_C:
4082                 cpt_set_fdi_bc_bifurcation(dev, true);
4083
4084                 break;
4085         default:
4086                 BUG();
4087         }
4088 }
4089
4090 /* Return which DP Port should be selected for Transcoder DP control */
4091 static enum port
4092 intel_trans_dp_port_sel(struct drm_crtc *crtc)
4093 {
4094         struct drm_device *dev = crtc->dev;
4095         struct intel_encoder *encoder;
4096
4097         for_each_encoder_on_crtc(dev, crtc, encoder) {
4098                 if (encoder->type == INTEL_OUTPUT_DISPLAYPORT ||
4099                     encoder->type == INTEL_OUTPUT_EDP)
4100                         return enc_to_dig_port(&encoder->base)->port;
4101         }
4102
4103         return -1;
4104 }
4105
4106 /*
4107  * Enable PCH resources required for PCH ports:
4108  *   - PCH PLLs
4109  *   - FDI training & RX/TX
4110  *   - update transcoder timings
4111  *   - DP transcoding bits
4112  *   - transcoder
4113  */
4114 static void ironlake_pch_enable(struct drm_crtc *crtc)
4115 {
4116         struct drm_device *dev = crtc->dev;
4117         struct drm_i915_private *dev_priv = dev->dev_private;
4118         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4119         int pipe = intel_crtc->pipe;
4120         u32 temp;
4121
4122         assert_pch_transcoder_disabled(dev_priv, pipe);
4123
4124         if (IS_IVYBRIDGE(dev))
4125                 ivybridge_update_fdi_bc_bifurcation(intel_crtc);
4126
4127         /* Write the TU size bits before fdi link training, so that error
4128          * detection works. */
4129         I915_WRITE(FDI_RX_TUSIZE1(pipe),
4130                    I915_READ(PIPE_DATA_M1(pipe)) & TU_SIZE_MASK);
4131
4132         /*
4133          * Sometimes spurious CPU pipe underruns happen during FDI
4134          * training, at least with VGA+HDMI cloning. Suppress them.
4135          */
4136         intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, false);
4137
4138         /* For PCH output, training FDI link */
4139         dev_priv->display.fdi_link_train(crtc);
4140
4141         /* We need to program the right clock selection before writing the pixel
4142          * mutliplier into the DPLL. */
4143         if (HAS_PCH_CPT(dev)) {
4144                 u32 sel;
4145
4146                 temp = I915_READ(PCH_DPLL_SEL);
4147                 temp |= TRANS_DPLL_ENABLE(pipe);
4148                 sel = TRANS_DPLLB_SEL(pipe);
4149                 if (intel_crtc->config->shared_dpll ==
4150                     intel_get_shared_dpll_by_id(dev_priv, DPLL_ID_PCH_PLL_B))
4151                         temp |= sel;
4152                 else
4153                         temp &= ~sel;
4154                 I915_WRITE(PCH_DPLL_SEL, temp);
4155         }
4156
4157         /* XXX: pch pll's can be enabled any time before we enable the PCH
4158          * transcoder, and we actually should do this to not upset any PCH
4159          * transcoder that already use the clock when we share it.
4160          *
4161          * Note that enable_shared_dpll tries to do the right thing, but
4162          * get_shared_dpll unconditionally resets the pll - we need that to have
4163          * the right LVDS enable sequence. */
4164         intel_enable_shared_dpll(intel_crtc);
4165
4166         /* set transcoder timing, panel must allow it */
4167         assert_panel_unlocked(dev_priv, pipe);
4168         ironlake_pch_transcoder_set_timings(intel_crtc, pipe);
4169
4170         intel_fdi_normal_train(crtc);
4171
4172         intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
4173
4174         /* For PCH DP, enable TRANS_DP_CTL */
4175         if (HAS_PCH_CPT(dev) && intel_crtc->config->has_dp_encoder) {
4176                 const struct drm_display_mode *adjusted_mode =
4177                         &intel_crtc->config->base.adjusted_mode;
4178                 u32 bpc = (I915_READ(PIPECONF(pipe)) & PIPECONF_BPC_MASK) >> 5;
4179                 i915_reg_t reg = TRANS_DP_CTL(pipe);
4180                 temp = I915_READ(reg);
4181                 temp &= ~(TRANS_DP_PORT_SEL_MASK |
4182                           TRANS_DP_SYNC_MASK |
4183                           TRANS_DP_BPC_MASK);
4184                 temp |= TRANS_DP_OUTPUT_ENABLE;
4185                 temp |= bpc << 9; /* same format but at 11:9 */
4186
4187                 if (adjusted_mode->flags & DRM_MODE_FLAG_PHSYNC)
4188                         temp |= TRANS_DP_HSYNC_ACTIVE_HIGH;
4189                 if (adjusted_mode->flags & DRM_MODE_FLAG_PVSYNC)
4190                         temp |= TRANS_DP_VSYNC_ACTIVE_HIGH;
4191
4192                 switch (intel_trans_dp_port_sel(crtc)) {
4193                 case PORT_B:
4194                         temp |= TRANS_DP_PORT_SEL_B;
4195                         break;
4196                 case PORT_C:
4197                         temp |= TRANS_DP_PORT_SEL_C;
4198                         break;
4199                 case PORT_D:
4200                         temp |= TRANS_DP_PORT_SEL_D;
4201                         break;
4202                 default:
4203                         BUG();
4204                 }
4205
4206                 I915_WRITE(reg, temp);
4207         }
4208
4209         ironlake_enable_pch_transcoder(dev_priv, pipe);
4210 }
4211
4212 static void lpt_pch_enable(struct drm_crtc *crtc)
4213 {
4214         struct drm_device *dev = crtc->dev;
4215         struct drm_i915_private *dev_priv = dev->dev_private;
4216         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4217         enum transcoder cpu_transcoder = intel_crtc->config->cpu_transcoder;
4218
4219         assert_pch_transcoder_disabled(dev_priv, TRANSCODER_A);
4220
4221         lpt_program_iclkip(crtc);
4222
4223         /* Set transcoder timing. */
4224         ironlake_pch_transcoder_set_timings(intel_crtc, PIPE_A);
4225
4226         lpt_enable_pch_transcoder(dev_priv, cpu_transcoder);
4227 }
4228
4229 static void cpt_verify_modeset(struct drm_device *dev, int pipe)
4230 {
4231         struct drm_i915_private *dev_priv = dev->dev_private;
4232         i915_reg_t dslreg = PIPEDSL(pipe);
4233         u32 temp;
4234
4235         temp = I915_READ(dslreg);
4236         udelay(500);
4237         if (wait_for(I915_READ(dslreg) != temp, 5)) {
4238                 if (wait_for(I915_READ(dslreg) != temp, 5))
4239                         DRM_ERROR("mode set failed: pipe %c stuck\n", pipe_name(pipe));
4240         }
4241 }
4242
4243 static int
4244 skl_update_scaler(struct intel_crtc_state *crtc_state, bool force_detach,
4245                   unsigned scaler_user, int *scaler_id, unsigned int rotation,
4246                   int src_w, int src_h, int dst_w, int dst_h)
4247 {
4248         struct intel_crtc_scaler_state *scaler_state =
4249                 &crtc_state->scaler_state;
4250         struct intel_crtc *intel_crtc =
4251                 to_intel_crtc(crtc_state->base.crtc);
4252         int need_scaling;
4253
4254         need_scaling = intel_rotation_90_or_270(rotation) ?
4255                 (src_h != dst_w || src_w != dst_h):
4256                 (src_w != dst_w || src_h != dst_h);
4257
4258         /*
4259          * if plane is being disabled or scaler is no more required or force detach
4260          *  - free scaler binded to this plane/crtc
4261          *  - in order to do this, update crtc->scaler_usage
4262          *
4263          * Here scaler state in crtc_state is set free so that
4264          * scaler can be assigned to other user. Actual register
4265          * update to free the scaler is done in plane/panel-fit programming.
4266          * For this purpose crtc/plane_state->scaler_id isn't reset here.
4267          */
4268         if (force_detach || !need_scaling) {
4269                 if (*scaler_id >= 0) {
4270                         scaler_state->scaler_users &= ~(1 << scaler_user);
4271                         scaler_state->scalers[*scaler_id].in_use = 0;
4272
4273                         DRM_DEBUG_KMS("scaler_user index %u.%u: "
4274                                 "Staged freeing scaler id %d scaler_users = 0x%x\n",
4275                                 intel_crtc->pipe, scaler_user, *scaler_id,
4276                                 scaler_state->scaler_users);
4277                         *scaler_id = -1;
4278                 }
4279                 return 0;
4280         }
4281
4282         /* range checks */
4283         if (src_w < SKL_MIN_SRC_W || src_h < SKL_MIN_SRC_H ||
4284                 dst_w < SKL_MIN_DST_W || dst_h < SKL_MIN_DST_H ||
4285
4286                 src_w > SKL_MAX_SRC_W || src_h > SKL_MAX_SRC_H ||
4287                 dst_w > SKL_MAX_DST_W || dst_h > SKL_MAX_DST_H) {
4288                 DRM_DEBUG_KMS("scaler_user index %u.%u: src %ux%u dst %ux%u "
4289                         "size is out of scaler range\n",
4290                         intel_crtc->pipe, scaler_user, src_w, src_h, dst_w, dst_h);
4291                 return -EINVAL;
4292         }
4293
4294         /* mark this plane as a scaler user in crtc_state */
4295         scaler_state->scaler_users |= (1 << scaler_user);
4296         DRM_DEBUG_KMS("scaler_user index %u.%u: "
4297                 "staged scaling request for %ux%u->%ux%u scaler_users = 0x%x\n",
4298                 intel_crtc->pipe, scaler_user, src_w, src_h, dst_w, dst_h,
4299                 scaler_state->scaler_users);
4300
4301         return 0;
4302 }
4303
4304 /**
4305  * skl_update_scaler_crtc - Stages update to scaler state for a given crtc.
4306  *
4307  * @state: crtc's scaler state
4308  *
4309  * Return
4310  *     0 - scaler_usage updated successfully
4311  *    error - requested scaling cannot be supported or other error condition
4312  */
4313 int skl_update_scaler_crtc(struct intel_crtc_state *state)
4314 {
4315         struct intel_crtc *intel_crtc = to_intel_crtc(state->base.crtc);
4316         const struct drm_display_mode *adjusted_mode = &state->base.adjusted_mode;
4317
4318         DRM_DEBUG_KMS("Updating scaler for [CRTC:%i] scaler_user index %u.%u\n",
4319                       intel_crtc->base.base.id, intel_crtc->pipe, SKL_CRTC_INDEX);
4320
4321         return skl_update_scaler(state, !state->base.active, SKL_CRTC_INDEX,
4322                 &state->scaler_state.scaler_id, BIT(DRM_ROTATE_0),
4323                 state->pipe_src_w, state->pipe_src_h,
4324                 adjusted_mode->crtc_hdisplay, adjusted_mode->crtc_vdisplay);
4325 }
4326
4327 /**
4328  * skl_update_scaler_plane - Stages update to scaler state for a given plane.
4329  *
4330  * @state: crtc's scaler state
4331  * @plane_state: atomic plane state to update
4332  *
4333  * Return
4334  *     0 - scaler_usage updated successfully
4335  *    error - requested scaling cannot be supported or other error condition
4336  */
4337 static int skl_update_scaler_plane(struct intel_crtc_state *crtc_state,
4338                                    struct intel_plane_state *plane_state)
4339 {
4340
4341         struct intel_crtc *intel_crtc = to_intel_crtc(crtc_state->base.crtc);
4342         struct intel_plane *intel_plane =
4343                 to_intel_plane(plane_state->base.plane);
4344         struct drm_framebuffer *fb = plane_state->base.fb;
4345         int ret;
4346
4347         bool force_detach = !fb || !plane_state->visible;
4348
4349         DRM_DEBUG_KMS("Updating scaler for [PLANE:%d] scaler_user index %u.%u\n",
4350                       intel_plane->base.base.id, intel_crtc->pipe,
4351                       drm_plane_index(&intel_plane->base));
4352
4353         ret = skl_update_scaler(crtc_state, force_detach,
4354                                 drm_plane_index(&intel_plane->base),
4355                                 &plane_state->scaler_id,
4356                                 plane_state->base.rotation,
4357                                 drm_rect_width(&plane_state->src) >> 16,
4358                                 drm_rect_height(&plane_state->src) >> 16,
4359                                 drm_rect_width(&plane_state->dst),
4360                                 drm_rect_height(&plane_state->dst));
4361
4362         if (ret || plane_state->scaler_id < 0)
4363                 return ret;
4364
4365         /* check colorkey */
4366         if (plane_state->ckey.flags != I915_SET_COLORKEY_NONE) {
4367                 DRM_DEBUG_KMS("[PLANE:%d] scaling with color key not allowed",
4368                               intel_plane->base.base.id);
4369                 return -EINVAL;
4370         }
4371
4372         /* Check src format */
4373         switch (fb->pixel_format) {
4374         case DRM_FORMAT_RGB565:
4375         case DRM_FORMAT_XBGR8888:
4376         case DRM_FORMAT_XRGB8888:
4377         case DRM_FORMAT_ABGR8888:
4378         case DRM_FORMAT_ARGB8888:
4379         case DRM_FORMAT_XRGB2101010:
4380         case DRM_FORMAT_XBGR2101010:
4381         case DRM_FORMAT_YUYV:
4382         case DRM_FORMAT_YVYU:
4383         case DRM_FORMAT_UYVY:
4384         case DRM_FORMAT_VYUY:
4385                 break;
4386         default:
4387                 DRM_DEBUG_KMS("[PLANE:%d] FB:%d unsupported scaling format 0x%x\n",
4388                         intel_plane->base.base.id, fb->base.id, fb->pixel_format);
4389                 return -EINVAL;
4390         }
4391
4392         return 0;
4393 }
4394
4395 static void skylake_scaler_disable(struct intel_crtc *crtc)
4396 {
4397         int i;
4398
4399         for (i = 0; i < crtc->num_scalers; i++)
4400                 skl_detach_scaler(crtc, i);
4401 }
4402
4403 static void skylake_pfit_enable(struct intel_crtc *crtc)
4404 {
4405         struct drm_device *dev = crtc->base.dev;
4406         struct drm_i915_private *dev_priv = dev->dev_private;
4407         int pipe = crtc->pipe;
4408         struct intel_crtc_scaler_state *scaler_state =
4409                 &crtc->config->scaler_state;
4410
4411         DRM_DEBUG_KMS("for crtc_state = %p\n", crtc->config);
4412
4413         if (crtc->config->pch_pfit.enabled) {
4414                 int id;
4415
4416                 if (WARN_ON(crtc->config->scaler_state.scaler_id < 0)) {
4417                         DRM_ERROR("Requesting pfit without getting a scaler first\n");
4418                         return;
4419                 }
4420
4421                 id = scaler_state->scaler_id;
4422                 I915_WRITE(SKL_PS_CTRL(pipe, id), PS_SCALER_EN |
4423                         PS_FILTER_MEDIUM | scaler_state->scalers[id].mode);
4424                 I915_WRITE(SKL_PS_WIN_POS(pipe, id), crtc->config->pch_pfit.pos);
4425                 I915_WRITE(SKL_PS_WIN_SZ(pipe, id), crtc->config->pch_pfit.size);
4426
4427                 DRM_DEBUG_KMS("for crtc_state = %p scaler_id = %d\n", crtc->config, id);
4428         }
4429 }
4430
4431 static void ironlake_pfit_enable(struct intel_crtc *crtc)
4432 {
4433         struct drm_device *dev = crtc->base.dev;
4434         struct drm_i915_private *dev_priv = dev->dev_private;
4435         int pipe = crtc->pipe;
4436
4437         if (crtc->config->pch_pfit.enabled) {
4438                 /* Force use of hard-coded filter coefficients
4439                  * as some pre-programmed values are broken,
4440                  * e.g. x201.
4441                  */
4442                 if (IS_IVYBRIDGE(dev) || IS_HASWELL(dev))
4443                         I915_WRITE(PF_CTL(pipe), PF_ENABLE | PF_FILTER_MED_3x3 |
4444                                                  PF_PIPE_SEL_IVB(pipe));
4445                 else
4446                         I915_WRITE(PF_CTL(pipe), PF_ENABLE | PF_FILTER_MED_3x3);
4447                 I915_WRITE(PF_WIN_POS(pipe), crtc->config->pch_pfit.pos);
4448                 I915_WRITE(PF_WIN_SZ(pipe), crtc->config->pch_pfit.size);
4449         }
4450 }
4451
4452 void hsw_enable_ips(struct intel_crtc *crtc)
4453 {
4454         struct drm_device *dev = crtc->base.dev;
4455         struct drm_i915_private *dev_priv = dev->dev_private;
4456
4457         if (!crtc->config->ips_enabled)
4458                 return;
4459
4460         /* We can only enable IPS after we enable a plane and wait for a vblank */
4461         intel_wait_for_vblank(dev, crtc->pipe);
4462
4463         assert_plane_enabled(dev_priv, crtc->plane);
4464         if (IS_BROADWELL(dev)) {
4465                 mutex_lock(&dev_priv->rps.hw_lock);
4466                 WARN_ON(sandybridge_pcode_write(dev_priv, DISPLAY_IPS_CONTROL, 0xc0000000));
4467                 mutex_unlock(&dev_priv->rps.hw_lock);
4468                 /* Quoting Art Runyan: "its not safe to expect any particular
4469                  * value in IPS_CTL bit 31 after enabling IPS through the
4470                  * mailbox." Moreover, the mailbox may return a bogus state,
4471                  * so we need to just enable it and continue on.
4472                  */
4473         } else {
4474                 I915_WRITE(IPS_CTL, IPS_ENABLE);
4475                 /* The bit only becomes 1 in the next vblank, so this wait here
4476                  * is essentially intel_wait_for_vblank. If we don't have this
4477                  * and don't wait for vblanks until the end of crtc_enable, then
4478                  * the HW state readout code will complain that the expected
4479                  * IPS_CTL value is not the one we read. */
4480                 if (wait_for(I915_READ_NOTRACE(IPS_CTL) & IPS_ENABLE, 50))
4481                         DRM_ERROR("Timed out waiting for IPS enable\n");
4482         }
4483 }
4484
4485 void hsw_disable_ips(struct intel_crtc *crtc)
4486 {
4487         struct drm_device *dev = crtc->base.dev;
4488         struct drm_i915_private *dev_priv = dev->dev_private;
4489
4490         if (!crtc->config->ips_enabled)
4491                 return;
4492
4493         assert_plane_enabled(dev_priv, crtc->plane);
4494         if (IS_BROADWELL(dev)) {
4495                 mutex_lock(&dev_priv->rps.hw_lock);
4496                 WARN_ON(sandybridge_pcode_write(dev_priv, DISPLAY_IPS_CONTROL, 0));
4497                 mutex_unlock(&dev_priv->rps.hw_lock);
4498                 /* wait for pcode to finish disabling IPS, which may take up to 42ms */
4499                 if (wait_for((I915_READ(IPS_CTL) & IPS_ENABLE) == 0, 42))
4500                         DRM_ERROR("Timed out waiting for IPS disable\n");
4501         } else {
4502                 I915_WRITE(IPS_CTL, 0);
4503                 POSTING_READ(IPS_CTL);
4504         }
4505
4506         /* We need to wait for a vblank before we can disable the plane. */
4507         intel_wait_for_vblank(dev, crtc->pipe);
4508 }
4509
4510 /** Loads the palette/gamma unit for the CRTC with the prepared values */
4511 static void intel_crtc_load_lut(struct drm_crtc *crtc)
4512 {
4513         struct drm_device *dev = crtc->dev;
4514         struct drm_i915_private *dev_priv = dev->dev_private;
4515         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4516         enum pipe pipe = intel_crtc->pipe;
4517         int i;
4518         bool reenable_ips = false;
4519
4520         /* The clocks have to be on to load the palette. */
4521         if (!crtc->state->active)
4522                 return;
4523
4524         if (HAS_GMCH_DISPLAY(dev_priv->dev)) {
4525                 if (intel_crtc->config->has_dsi_encoder)
4526                         assert_dsi_pll_enabled(dev_priv);
4527                 else
4528                         assert_pll_enabled(dev_priv, pipe);
4529         }
4530
4531         /* Workaround : Do not read or write the pipe palette/gamma data while
4532          * GAMMA_MODE is configured for split gamma and IPS_CTL has IPS enabled.
4533          */
4534         if (IS_HASWELL(dev) && intel_crtc->config->ips_enabled &&
4535             ((I915_READ(GAMMA_MODE(pipe)) & GAMMA_MODE_MODE_MASK) ==
4536              GAMMA_MODE_MODE_SPLIT)) {
4537                 hsw_disable_ips(intel_crtc);
4538                 reenable_ips = true;
4539         }
4540
4541         for (i = 0; i < 256; i++) {
4542                 i915_reg_t palreg;
4543
4544                 if (HAS_GMCH_DISPLAY(dev))
4545                         palreg = PALETTE(pipe, i);
4546                 else
4547                         palreg = LGC_PALETTE(pipe, i);
4548
4549                 I915_WRITE(palreg,
4550                            (intel_crtc->lut_r[i] << 16) |
4551                            (intel_crtc->lut_g[i] << 8) |
4552                            intel_crtc->lut_b[i]);
4553         }
4554
4555         if (reenable_ips)
4556                 hsw_enable_ips(intel_crtc);
4557 }
4558
4559 static void intel_crtc_dpms_overlay_disable(struct intel_crtc *intel_crtc)
4560 {
4561         if (intel_crtc->overlay) {
4562                 struct drm_device *dev = intel_crtc->base.dev;
4563                 struct drm_i915_private *dev_priv = dev->dev_private;
4564
4565                 mutex_lock(&dev->struct_mutex);
4566                 dev_priv->mm.interruptible = false;
4567                 (void) intel_overlay_switch_off(intel_crtc->overlay);
4568                 dev_priv->mm.interruptible = true;
4569                 mutex_unlock(&dev->struct_mutex);
4570         }
4571
4572         /* Let userspace switch the overlay on again. In most cases userspace
4573          * has to recompute where to put it anyway.
4574          */
4575 }
4576
4577 /**
4578  * intel_post_enable_primary - Perform operations after enabling primary plane
4579  * @crtc: the CRTC whose primary plane was just enabled
4580  *
4581  * Performs potentially sleeping operations that must be done after the primary
4582  * plane is enabled, such as updating FBC and IPS.  Note that this may be
4583  * called due to an explicit primary plane update, or due to an implicit
4584  * re-enable that is caused when a sprite plane is updated to no longer
4585  * completely hide the primary plane.
4586  */
4587 static void
4588 intel_post_enable_primary(struct drm_crtc *crtc)
4589 {
4590         struct drm_device *dev = crtc->dev;
4591         struct drm_i915_private *dev_priv = dev->dev_private;
4592         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4593         int pipe = intel_crtc->pipe;
4594
4595         /*
4596          * FIXME IPS should be fine as long as one plane is
4597          * enabled, but in practice it seems to have problems
4598          * when going from primary only to sprite only and vice
4599          * versa.
4600          */
4601         hsw_enable_ips(intel_crtc);
4602
4603         /*
4604          * Gen2 reports pipe underruns whenever all planes are disabled.
4605          * So don't enable underrun reporting before at least some planes
4606          * are enabled.
4607          * FIXME: Need to fix the logic to work when we turn off all planes
4608          * but leave the pipe running.
4609          */
4610         if (IS_GEN2(dev))
4611                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
4612
4613         /* Underruns don't always raise interrupts, so check manually. */
4614         intel_check_cpu_fifo_underruns(dev_priv);
4615         intel_check_pch_fifo_underruns(dev_priv);
4616 }
4617
4618 /* FIXME move all this to pre_plane_update() with proper state tracking */
4619 static void
4620 intel_pre_disable_primary(struct drm_crtc *crtc)
4621 {
4622         struct drm_device *dev = crtc->dev;
4623         struct drm_i915_private *dev_priv = dev->dev_private;
4624         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4625         int pipe = intel_crtc->pipe;
4626
4627         /*
4628          * Gen2 reports pipe underruns whenever all planes are disabled.
4629          * So diasble underrun reporting before all the planes get disabled.
4630          * FIXME: Need to fix the logic to work when we turn off all planes
4631          * but leave the pipe running.
4632          */
4633         if (IS_GEN2(dev))
4634                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, false);
4635
4636         /*
4637          * FIXME IPS should be fine as long as one plane is
4638          * enabled, but in practice it seems to have problems
4639          * when going from primary only to sprite only and vice
4640          * versa.
4641          */
4642         hsw_disable_ips(intel_crtc);
4643 }
4644
4645 /* FIXME get rid of this and use pre_plane_update */
4646 static void
4647 intel_pre_disable_primary_noatomic(struct drm_crtc *crtc)
4648 {
4649         struct drm_device *dev = crtc->dev;
4650         struct drm_i915_private *dev_priv = dev->dev_private;
4651         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4652         int pipe = intel_crtc->pipe;
4653
4654         intel_pre_disable_primary(crtc);
4655
4656         /*
4657          * Vblank time updates from the shadow to live plane control register
4658          * are blocked if the memory self-refresh mode is active at that
4659          * moment. So to make sure the plane gets truly disabled, disable
4660          * first the self-refresh mode. The self-refresh enable bit in turn
4661          * will be checked/applied by the HW only at the next frame start
4662          * event which is after the vblank start event, so we need to have a
4663          * wait-for-vblank between disabling the plane and the pipe.
4664          */
4665         if (HAS_GMCH_DISPLAY(dev)) {
4666                 intel_set_memory_cxsr(dev_priv, false);
4667                 dev_priv->wm.vlv.cxsr = false;
4668                 intel_wait_for_vblank(dev, pipe);
4669         }
4670 }
4671
4672 static void intel_post_plane_update(struct intel_crtc_state *old_crtc_state)
4673 {
4674         struct intel_crtc *crtc = to_intel_crtc(old_crtc_state->base.crtc);
4675         struct drm_atomic_state *old_state = old_crtc_state->base.state;
4676         struct intel_crtc_state *pipe_config =
4677                 to_intel_crtc_state(crtc->base.state);
4678         struct drm_device *dev = crtc->base.dev;
4679         struct drm_plane *primary = crtc->base.primary;
4680         struct drm_plane_state *old_pri_state =
4681                 drm_atomic_get_existing_plane_state(old_state, primary);
4682
4683         intel_frontbuffer_flip(dev, pipe_config->fb_bits);
4684
4685         crtc->wm.cxsr_allowed = true;
4686
4687         if (pipe_config->update_wm_post && pipe_config->base.active)
4688                 intel_update_watermarks(&crtc->base);
4689
4690         if (old_pri_state) {
4691                 struct intel_plane_state *primary_state =
4692                         to_intel_plane_state(primary->state);
4693                 struct intel_plane_state *old_primary_state =
4694                         to_intel_plane_state(old_pri_state);
4695
4696                 intel_fbc_post_update(crtc);
4697
4698                 if (primary_state->visible &&
4699                     (needs_modeset(&pipe_config->base) ||
4700                      !old_primary_state->visible))
4701                         intel_post_enable_primary(&crtc->base);
4702         }
4703 }
4704
4705 static void intel_pre_plane_update(struct intel_crtc_state *old_crtc_state)
4706 {
4707         struct intel_crtc *crtc = to_intel_crtc(old_crtc_state->base.crtc);
4708         struct drm_device *dev = crtc->base.dev;
4709         struct drm_i915_private *dev_priv = dev->dev_private;
4710         struct intel_crtc_state *pipe_config =
4711                 to_intel_crtc_state(crtc->base.state);
4712         struct drm_atomic_state *old_state = old_crtc_state->base.state;
4713         struct drm_plane *primary = crtc->base.primary;
4714         struct drm_plane_state *old_pri_state =
4715                 drm_atomic_get_existing_plane_state(old_state, primary);
4716         bool modeset = needs_modeset(&pipe_config->base);
4717
4718         if (old_pri_state) {
4719                 struct intel_plane_state *primary_state =
4720                         to_intel_plane_state(primary->state);
4721                 struct intel_plane_state *old_primary_state =
4722                         to_intel_plane_state(old_pri_state);
4723
4724                 intel_fbc_pre_update(crtc);
4725
4726                 if (old_primary_state->visible &&
4727                     (modeset || !primary_state->visible))
4728                         intel_pre_disable_primary(&crtc->base);
4729         }
4730
4731         if (pipe_config->disable_cxsr) {
4732                 crtc->wm.cxsr_allowed = false;
4733
4734                 /*
4735                  * Vblank time updates from the shadow to live plane control register
4736                  * are blocked if the memory self-refresh mode is active at that
4737                  * moment. So to make sure the plane gets truly disabled, disable
4738                  * first the self-refresh mode. The self-refresh enable bit in turn
4739                  * will be checked/applied by the HW only at the next frame start
4740                  * event which is after the vblank start event, so we need to have a
4741                  * wait-for-vblank between disabling the plane and the pipe.
4742                  */
4743                 if (old_crtc_state->base.active) {
4744                         intel_set_memory_cxsr(dev_priv, false);
4745                         dev_priv->wm.vlv.cxsr = false;
4746                         intel_wait_for_vblank(dev, crtc->pipe);
4747                 }
4748         }
4749
4750         /*
4751          * IVB workaround: must disable low power watermarks for at least
4752          * one frame before enabling scaling.  LP watermarks can be re-enabled
4753          * when scaling is disabled.
4754          *
4755          * WaCxSRDisabledForSpriteScaling:ivb
4756          */
4757         if (pipe_config->disable_lp_wm) {
4758                 ilk_disable_lp_wm(dev);
4759                 intel_wait_for_vblank(dev, crtc->pipe);
4760         }
4761
4762         /*
4763          * If we're doing a modeset, we're done.  No need to do any pre-vblank
4764          * watermark programming here.
4765          */
4766         if (needs_modeset(&pipe_config->base))
4767                 return;
4768
4769         /*
4770          * For platforms that support atomic watermarks, program the
4771          * 'intermediate' watermarks immediately.  On pre-gen9 platforms, these
4772          * will be the intermediate values that are safe for both pre- and
4773          * post- vblank; when vblank happens, the 'active' values will be set
4774          * to the final 'target' values and we'll do this again to get the
4775          * optimal watermarks.  For gen9+ platforms, the values we program here
4776          * will be the final target values which will get automatically latched
4777          * at vblank time; no further programming will be necessary.
4778          *
4779          * If a platform hasn't been transitioned to atomic watermarks yet,
4780          * we'll continue to update watermarks the old way, if flags tell
4781          * us to.
4782          */
4783         if (dev_priv->display.initial_watermarks != NULL)
4784                 dev_priv->display.initial_watermarks(pipe_config);
4785         else if (pipe_config->update_wm_pre)
4786                 intel_update_watermarks(&crtc->base);
4787 }
4788
4789 static void intel_crtc_disable_planes(struct drm_crtc *crtc, unsigned plane_mask)
4790 {
4791         struct drm_device *dev = crtc->dev;
4792         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4793         struct drm_plane *p;
4794         int pipe = intel_crtc->pipe;
4795
4796         intel_crtc_dpms_overlay_disable(intel_crtc);
4797
4798         drm_for_each_plane_mask(p, dev, plane_mask)
4799                 to_intel_plane(p)->disable_plane(p, crtc);
4800
4801         /*
4802          * FIXME: Once we grow proper nuclear flip support out of this we need
4803          * to compute the mask of flip planes precisely. For the time being
4804          * consider this a flip to a NULL plane.
4805          */
4806         intel_frontbuffer_flip(dev, INTEL_FRONTBUFFER_ALL_MASK(pipe));
4807 }
4808
4809 static void ironlake_crtc_enable(struct drm_crtc *crtc)
4810 {
4811         struct drm_device *dev = crtc->dev;
4812         struct drm_i915_private *dev_priv = dev->dev_private;
4813         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4814         struct intel_encoder *encoder;
4815         int pipe = intel_crtc->pipe;
4816
4817         if (WARN_ON(intel_crtc->active))
4818                 return;
4819
4820         if (intel_crtc->config->has_pch_encoder)
4821                 intel_set_pch_fifo_underrun_reporting(dev_priv, pipe, false);
4822
4823         if (intel_crtc->config->has_pch_encoder)
4824                 intel_prepare_shared_dpll(intel_crtc);
4825
4826         if (intel_crtc->config->has_dp_encoder)
4827                 intel_dp_set_m_n(intel_crtc, M1_N1);
4828
4829         intel_set_pipe_timings(intel_crtc);
4830
4831         if (intel_crtc->config->has_pch_encoder) {
4832                 intel_cpu_transcoder_set_m_n(intel_crtc,
4833                                      &intel_crtc->config->fdi_m_n, NULL);
4834         }
4835
4836         ironlake_set_pipeconf(crtc);
4837
4838         intel_crtc->active = true;
4839
4840         intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
4841
4842         for_each_encoder_on_crtc(dev, crtc, encoder)
4843                 if (encoder->pre_enable)
4844                         encoder->pre_enable(encoder);
4845
4846         if (intel_crtc->config->has_pch_encoder) {
4847                 /* Note: FDI PLL enabling _must_ be done before we enable the
4848                  * cpu pipes, hence this is separate from all the other fdi/pch
4849                  * enabling. */
4850                 ironlake_fdi_pll_enable(intel_crtc);
4851         } else {
4852                 assert_fdi_tx_disabled(dev_priv, pipe);
4853                 assert_fdi_rx_disabled(dev_priv, pipe);
4854         }
4855
4856         ironlake_pfit_enable(intel_crtc);
4857
4858         /*
4859          * On ILK+ LUT must be loaded before the pipe is running but with
4860          * clocks enabled
4861          */
4862         intel_crtc_load_lut(crtc);
4863
4864         if (dev_priv->display.initial_watermarks != NULL)
4865                 dev_priv->display.initial_watermarks(intel_crtc->config);
4866         intel_enable_pipe(intel_crtc);
4867
4868         if (intel_crtc->config->has_pch_encoder)
4869                 ironlake_pch_enable(crtc);
4870
4871         assert_vblank_disabled(crtc);
4872         drm_crtc_vblank_on(crtc);
4873
4874         for_each_encoder_on_crtc(dev, crtc, encoder)
4875                 encoder->enable(encoder);
4876
4877         if (HAS_PCH_CPT(dev))
4878                 cpt_verify_modeset(dev, intel_crtc->pipe);
4879
4880         /* Must wait for vblank to avoid spurious PCH FIFO underruns */
4881         if (intel_crtc->config->has_pch_encoder)
4882                 intel_wait_for_vblank(dev, pipe);
4883         intel_set_pch_fifo_underrun_reporting(dev_priv, pipe, true);
4884 }
4885
4886 /* IPS only exists on ULT machines and is tied to pipe A. */
4887 static bool hsw_crtc_supports_ips(struct intel_crtc *crtc)
4888 {
4889         return HAS_IPS(crtc->base.dev) && crtc->pipe == PIPE_A;
4890 }
4891
4892 static void haswell_crtc_enable(struct drm_crtc *crtc)
4893 {
4894         struct drm_device *dev = crtc->dev;
4895         struct drm_i915_private *dev_priv = dev->dev_private;
4896         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4897         struct intel_encoder *encoder;
4898         int pipe = intel_crtc->pipe, hsw_workaround_pipe;
4899         struct intel_crtc_state *pipe_config =
4900                 to_intel_crtc_state(crtc->state);
4901
4902         if (WARN_ON(intel_crtc->active))
4903                 return;
4904
4905         if (intel_crtc->config->has_pch_encoder)
4906                 intel_set_pch_fifo_underrun_reporting(dev_priv, TRANSCODER_A,
4907                                                       false);
4908
4909         if (intel_crtc->config->shared_dpll)
4910                 intel_enable_shared_dpll(intel_crtc);
4911
4912         if (intel_crtc->config->has_dp_encoder)
4913                 intel_dp_set_m_n(intel_crtc, M1_N1);
4914
4915         intel_set_pipe_timings(intel_crtc);
4916
4917         if (intel_crtc->config->cpu_transcoder != TRANSCODER_EDP) {
4918                 I915_WRITE(PIPE_MULT(intel_crtc->config->cpu_transcoder),
4919                            intel_crtc->config->pixel_multiplier - 1);
4920         }
4921
4922         if (intel_crtc->config->has_pch_encoder) {
4923                 intel_cpu_transcoder_set_m_n(intel_crtc,
4924                                      &intel_crtc->config->fdi_m_n, NULL);
4925         }
4926
4927         haswell_set_pipeconf(crtc);
4928
4929         intel_set_pipe_csc(crtc);
4930
4931         intel_crtc->active = true;
4932
4933         if (intel_crtc->config->has_pch_encoder)
4934                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, false);
4935         else
4936                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
4937
4938         for_each_encoder_on_crtc(dev, crtc, encoder) {
4939                 if (encoder->pre_enable)
4940                         encoder->pre_enable(encoder);
4941         }
4942
4943         if (intel_crtc->config->has_pch_encoder)
4944                 dev_priv->display.fdi_link_train(crtc);
4945
4946         if (!intel_crtc->config->has_dsi_encoder)
4947                 intel_ddi_enable_pipe_clock(intel_crtc);
4948
4949         if (INTEL_INFO(dev)->gen >= 9)
4950                 skylake_pfit_enable(intel_crtc);
4951         else
4952                 ironlake_pfit_enable(intel_crtc);
4953
4954         /*
4955          * On ILK+ LUT must be loaded before the pipe is running but with
4956          * clocks enabled
4957          */
4958         intel_crtc_load_lut(crtc);
4959
4960         intel_ddi_set_pipe_settings(crtc);
4961         if (!intel_crtc->config->has_dsi_encoder)
4962                 intel_ddi_enable_transcoder_func(crtc);
4963
4964         if (dev_priv->display.initial_watermarks != NULL)
4965                 dev_priv->display.initial_watermarks(pipe_config);
4966         else
4967                 intel_update_watermarks(crtc);
4968         intel_enable_pipe(intel_crtc);
4969
4970         if (intel_crtc->config->has_pch_encoder)
4971                 lpt_pch_enable(crtc);
4972
4973         if (intel_crtc->config->dp_encoder_is_mst)
4974                 intel_ddi_set_vc_payload_alloc(crtc, true);
4975
4976         assert_vblank_disabled(crtc);
4977         drm_crtc_vblank_on(crtc);
4978
4979         for_each_encoder_on_crtc(dev, crtc, encoder) {
4980                 encoder->enable(encoder);
4981                 intel_opregion_notify_encoder(encoder, true);
4982         }
4983
4984         if (intel_crtc->config->has_pch_encoder) {
4985                 intel_wait_for_vblank(dev, pipe);
4986                 intel_wait_for_vblank(dev, pipe);
4987                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
4988                 intel_set_pch_fifo_underrun_reporting(dev_priv, TRANSCODER_A,
4989                                                       true);
4990         }
4991
4992         /* If we change the relative order between pipe/planes enabling, we need
4993          * to change the workaround. */
4994         hsw_workaround_pipe = pipe_config->hsw_workaround_pipe;
4995         if (IS_HASWELL(dev) && hsw_workaround_pipe != INVALID_PIPE) {
4996                 intel_wait_for_vblank(dev, hsw_workaround_pipe);
4997                 intel_wait_for_vblank(dev, hsw_workaround_pipe);
4998         }
4999 }
5000
5001 static void ironlake_pfit_disable(struct intel_crtc *crtc, bool force)
5002 {
5003         struct drm_device *dev = crtc->base.dev;
5004         struct drm_i915_private *dev_priv = dev->dev_private;
5005         int pipe = crtc->pipe;
5006
5007         /* To avoid upsetting the power well on haswell only disable the pfit if
5008          * it's in use. The hw state code will make sure we get this right. */
5009         if (force || crtc->config->pch_pfit.enabled) {
5010                 I915_WRITE(PF_CTL(pipe), 0);
5011                 I915_WRITE(PF_WIN_POS(pipe), 0);
5012                 I915_WRITE(PF_WIN_SZ(pipe), 0);
5013         }
5014 }
5015
5016 static void ironlake_crtc_disable(struct drm_crtc *crtc)
5017 {
5018         struct drm_device *dev = crtc->dev;
5019         struct drm_i915_private *dev_priv = dev->dev_private;
5020         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5021         struct intel_encoder *encoder;
5022         int pipe = intel_crtc->pipe;
5023
5024         if (intel_crtc->config->has_pch_encoder)
5025                 intel_set_pch_fifo_underrun_reporting(dev_priv, pipe, false);
5026
5027         for_each_encoder_on_crtc(dev, crtc, encoder)
5028                 encoder->disable(encoder);
5029
5030         drm_crtc_vblank_off(crtc);
5031         assert_vblank_disabled(crtc);
5032
5033         /*
5034          * Sometimes spurious CPU pipe underruns happen when the
5035          * pipe is already disabled, but FDI RX/TX is still enabled.
5036          * Happens at least with VGA+HDMI cloning. Suppress them.
5037          */
5038         if (intel_crtc->config->has_pch_encoder)
5039                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, false);
5040
5041         intel_disable_pipe(intel_crtc);
5042
5043         ironlake_pfit_disable(intel_crtc, false);
5044
5045         if (intel_crtc->config->has_pch_encoder) {
5046                 ironlake_fdi_disable(crtc);
5047                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
5048         }
5049
5050         for_each_encoder_on_crtc(dev, crtc, encoder)
5051                 if (encoder->post_disable)
5052                         encoder->post_disable(encoder);
5053
5054         if (intel_crtc->config->has_pch_encoder) {
5055                 ironlake_disable_pch_transcoder(dev_priv, pipe);
5056
5057                 if (HAS_PCH_CPT(dev)) {
5058                         i915_reg_t reg;
5059                         u32 temp;
5060
5061                         /* disable TRANS_DP_CTL */
5062                         reg = TRANS_DP_CTL(pipe);
5063                         temp = I915_READ(reg);
5064                         temp &= ~(TRANS_DP_OUTPUT_ENABLE |
5065                                   TRANS_DP_PORT_SEL_MASK);
5066                         temp |= TRANS_DP_PORT_SEL_NONE;
5067                         I915_WRITE(reg, temp);
5068
5069                         /* disable DPLL_SEL */
5070                         temp = I915_READ(PCH_DPLL_SEL);
5071                         temp &= ~(TRANS_DPLL_ENABLE(pipe) | TRANS_DPLLB_SEL(pipe));
5072                         I915_WRITE(PCH_DPLL_SEL, temp);
5073                 }
5074
5075                 ironlake_fdi_pll_disable(intel_crtc);
5076         }
5077
5078         intel_set_pch_fifo_underrun_reporting(dev_priv, pipe, true);
5079 }
5080
5081 static void haswell_crtc_disable(struct drm_crtc *crtc)
5082 {
5083         struct drm_device *dev = crtc->dev;
5084         struct drm_i915_private *dev_priv = dev->dev_private;
5085         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5086         struct intel_encoder *encoder;
5087         enum transcoder cpu_transcoder = intel_crtc->config->cpu_transcoder;
5088
5089         if (intel_crtc->config->has_pch_encoder)
5090                 intel_set_pch_fifo_underrun_reporting(dev_priv, TRANSCODER_A,
5091                                                       false);
5092
5093         for_each_encoder_on_crtc(dev, crtc, encoder) {
5094                 intel_opregion_notify_encoder(encoder, false);
5095                 encoder->disable(encoder);
5096         }
5097
5098         drm_crtc_vblank_off(crtc);
5099         assert_vblank_disabled(crtc);
5100
5101         intel_disable_pipe(intel_crtc);
5102
5103         if (intel_crtc->config->dp_encoder_is_mst)
5104                 intel_ddi_set_vc_payload_alloc(crtc, false);
5105
5106         if (!intel_crtc->config->has_dsi_encoder)
5107                 intel_ddi_disable_transcoder_func(dev_priv, cpu_transcoder);
5108
5109         if (INTEL_INFO(dev)->gen >= 9)
5110                 skylake_scaler_disable(intel_crtc);
5111         else
5112                 ironlake_pfit_disable(intel_crtc, false);
5113
5114         if (!intel_crtc->config->has_dsi_encoder)
5115                 intel_ddi_disable_pipe_clock(intel_crtc);
5116
5117         for_each_encoder_on_crtc(dev, crtc, encoder)
5118                 if (encoder->post_disable)
5119                         encoder->post_disable(encoder);
5120
5121         if (intel_crtc->config->has_pch_encoder) {
5122                 lpt_disable_pch_transcoder(dev_priv);
5123                 lpt_disable_iclkip(dev_priv);
5124                 intel_ddi_fdi_disable(crtc);
5125
5126                 intel_set_pch_fifo_underrun_reporting(dev_priv, TRANSCODER_A,
5127                                                       true);
5128         }
5129 }
5130
5131 static void i9xx_pfit_enable(struct intel_crtc *crtc)
5132 {
5133         struct drm_device *dev = crtc->base.dev;
5134         struct drm_i915_private *dev_priv = dev->dev_private;
5135         struct intel_crtc_state *pipe_config = crtc->config;
5136
5137         if (!pipe_config->gmch_pfit.control)
5138                 return;
5139
5140         /*
5141          * The panel fitter should only be adjusted whilst the pipe is disabled,
5142          * according to register description and PRM.
5143          */
5144         WARN_ON(I915_READ(PFIT_CONTROL) & PFIT_ENABLE);
5145         assert_pipe_disabled(dev_priv, crtc->pipe);
5146
5147         I915_WRITE(PFIT_PGM_RATIOS, pipe_config->gmch_pfit.pgm_ratios);
5148         I915_WRITE(PFIT_CONTROL, pipe_config->gmch_pfit.control);
5149
5150         /* Border color in case we don't scale up to the full screen. Black by
5151          * default, change to something else for debugging. */
5152         I915_WRITE(BCLRPAT(crtc->pipe), 0);
5153 }
5154
5155 static enum intel_display_power_domain port_to_power_domain(enum port port)
5156 {
5157         switch (port) {
5158         case PORT_A:
5159                 return POWER_DOMAIN_PORT_DDI_A_LANES;
5160         case PORT_B:
5161                 return POWER_DOMAIN_PORT_DDI_B_LANES;
5162         case PORT_C:
5163                 return POWER_DOMAIN_PORT_DDI_C_LANES;
5164         case PORT_D:
5165                 return POWER_DOMAIN_PORT_DDI_D_LANES;
5166         case PORT_E:
5167                 return POWER_DOMAIN_PORT_DDI_E_LANES;
5168         default:
5169                 MISSING_CASE(port);
5170                 return POWER_DOMAIN_PORT_OTHER;
5171         }
5172 }
5173
5174 static enum intel_display_power_domain port_to_aux_power_domain(enum port port)
5175 {
5176         switch (port) {
5177         case PORT_A:
5178                 return POWER_DOMAIN_AUX_A;
5179         case PORT_B:
5180                 return POWER_DOMAIN_AUX_B;
5181         case PORT_C:
5182                 return POWER_DOMAIN_AUX_C;
5183         case PORT_D:
5184                 return POWER_DOMAIN_AUX_D;
5185         case PORT_E:
5186                 /* FIXME: Check VBT for actual wiring of PORT E */
5187                 return POWER_DOMAIN_AUX_D;
5188         default:
5189                 MISSING_CASE(port);
5190                 return POWER_DOMAIN_AUX_A;
5191         }
5192 }
5193
5194 enum intel_display_power_domain
5195 intel_display_port_power_domain(struct intel_encoder *intel_encoder)
5196 {
5197         struct drm_device *dev = intel_encoder->base.dev;
5198         struct intel_digital_port *intel_dig_port;
5199
5200         switch (intel_encoder->type) {
5201         case INTEL_OUTPUT_UNKNOWN:
5202                 /* Only DDI platforms should ever use this output type */
5203                 WARN_ON_ONCE(!HAS_DDI(dev));
5204         case INTEL_OUTPUT_DISPLAYPORT:
5205         case INTEL_OUTPUT_HDMI:
5206         case INTEL_OUTPUT_EDP:
5207                 intel_dig_port = enc_to_dig_port(&intel_encoder->base);
5208                 return port_to_power_domain(intel_dig_port->port);
5209         case INTEL_OUTPUT_DP_MST:
5210                 intel_dig_port = enc_to_mst(&intel_encoder->base)->primary;
5211                 return port_to_power_domain(intel_dig_port->port);
5212         case INTEL_OUTPUT_ANALOG:
5213                 return POWER_DOMAIN_PORT_CRT;
5214         case INTEL_OUTPUT_DSI:
5215                 return POWER_DOMAIN_PORT_DSI;
5216         default:
5217                 return POWER_DOMAIN_PORT_OTHER;
5218         }
5219 }
5220
5221 enum intel_display_power_domain
5222 intel_display_port_aux_power_domain(struct intel_encoder *intel_encoder)
5223 {
5224         struct drm_device *dev = intel_encoder->base.dev;
5225         struct intel_digital_port *intel_dig_port;
5226
5227         switch (intel_encoder->type) {
5228         case INTEL_OUTPUT_UNKNOWN:
5229         case INTEL_OUTPUT_HDMI:
5230                 /*
5231                  * Only DDI platforms should ever use these output types.
5232                  * We can get here after the HDMI detect code has already set
5233                  * the type of the shared encoder. Since we can't be sure
5234                  * what's the status of the given connectors, play safe and
5235                  * run the DP detection too.
5236                  */
5237                 WARN_ON_ONCE(!HAS_DDI(dev));
5238         case INTEL_OUTPUT_DISPLAYPORT:
5239         case INTEL_OUTPUT_EDP:
5240                 intel_dig_port = enc_to_dig_port(&intel_encoder->base);
5241                 return port_to_aux_power_domain(intel_dig_port->port);
5242         case INTEL_OUTPUT_DP_MST:
5243                 intel_dig_port = enc_to_mst(&intel_encoder->base)->primary;
5244                 return port_to_aux_power_domain(intel_dig_port->port);
5245         default:
5246                 MISSING_CASE(intel_encoder->type);
5247                 return POWER_DOMAIN_AUX_A;
5248         }
5249 }
5250
5251 static unsigned long get_crtc_power_domains(struct drm_crtc *crtc,
5252                                             struct intel_crtc_state *crtc_state)
5253 {
5254         struct drm_device *dev = crtc->dev;
5255         struct drm_encoder *encoder;
5256         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5257         enum pipe pipe = intel_crtc->pipe;
5258         unsigned long mask;
5259         enum transcoder transcoder = crtc_state->cpu_transcoder;
5260
5261         if (!crtc_state->base.active)
5262                 return 0;
5263
5264         mask = BIT(POWER_DOMAIN_PIPE(pipe));
5265         mask |= BIT(POWER_DOMAIN_TRANSCODER(transcoder));
5266         if (crtc_state->pch_pfit.enabled ||
5267             crtc_state->pch_pfit.force_thru)
5268                 mask |= BIT(POWER_DOMAIN_PIPE_PANEL_FITTER(pipe));
5269
5270         drm_for_each_encoder_mask(encoder, dev, crtc_state->base.encoder_mask) {
5271                 struct intel_encoder *intel_encoder = to_intel_encoder(encoder);
5272
5273                 mask |= BIT(intel_display_port_power_domain(intel_encoder));
5274         }
5275
5276         if (crtc_state->shared_dpll)
5277                 mask |= BIT(POWER_DOMAIN_PLLS);
5278
5279         return mask;
5280 }
5281
5282 static unsigned long
5283 modeset_get_crtc_power_domains(struct drm_crtc *crtc,
5284                                struct intel_crtc_state *crtc_state)
5285 {
5286         struct drm_i915_private *dev_priv = crtc->dev->dev_private;
5287         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5288         enum intel_display_power_domain domain;
5289         unsigned long domains, new_domains, old_domains;
5290
5291         old_domains = intel_crtc->enabled_power_domains;
5292         intel_crtc->enabled_power_domains = new_domains =
5293                 get_crtc_power_domains(crtc, crtc_state);
5294
5295         domains = new_domains & ~old_domains;
5296
5297         for_each_power_domain(domain, domains)
5298                 intel_display_power_get(dev_priv, domain);
5299
5300         return old_domains & ~new_domains;
5301 }
5302
5303 static void modeset_put_power_domains(struct drm_i915_private *dev_priv,
5304                                       unsigned long domains)
5305 {
5306         enum intel_display_power_domain domain;
5307
5308         for_each_power_domain(domain, domains)
5309                 intel_display_power_put(dev_priv, domain);
5310 }
5311
5312 static int intel_compute_max_dotclk(struct drm_i915_private *dev_priv)
5313 {
5314         int max_cdclk_freq = dev_priv->max_cdclk_freq;
5315
5316         if (INTEL_INFO(dev_priv)->gen >= 9 ||
5317             IS_HASWELL(dev_priv) || IS_BROADWELL(dev_priv))
5318                 return max_cdclk_freq;
5319         else if (IS_CHERRYVIEW(dev_priv))
5320                 return max_cdclk_freq*95/100;
5321         else if (INTEL_INFO(dev_priv)->gen < 4)
5322                 return 2*max_cdclk_freq*90/100;
5323         else
5324                 return max_cdclk_freq*90/100;
5325 }
5326
5327 static void intel_update_max_cdclk(struct drm_device *dev)
5328 {
5329         struct drm_i915_private *dev_priv = dev->dev_private;
5330
5331         if (IS_SKYLAKE(dev) || IS_KABYLAKE(dev)) {
5332                 u32 limit = I915_READ(SKL_DFSM) & SKL_DFSM_CDCLK_LIMIT_MASK;
5333
5334                 if (limit == SKL_DFSM_CDCLK_LIMIT_675)
5335                         dev_priv->max_cdclk_freq = 675000;
5336                 else if (limit == SKL_DFSM_CDCLK_LIMIT_540)
5337                         dev_priv->max_cdclk_freq = 540000;
5338                 else if (limit == SKL_DFSM_CDCLK_LIMIT_450)
5339                         dev_priv->max_cdclk_freq = 450000;
5340                 else
5341                         dev_priv->max_cdclk_freq = 337500;
5342         } else if (IS_BROADWELL(dev))  {
5343                 /*
5344                  * FIXME with extra cooling we can allow
5345                  * 540 MHz for ULX and 675 Mhz for ULT.
5346                  * How can we know if extra cooling is
5347                  * available? PCI ID, VTB, something else?
5348                  */
5349                 if (I915_READ(FUSE_STRAP) & HSW_CDCLK_LIMIT)
5350                         dev_priv->max_cdclk_freq = 450000;
5351                 else if (IS_BDW_ULX(dev))
5352                         dev_priv->max_cdclk_freq = 450000;
5353                 else if (IS_BDW_ULT(dev))
5354                         dev_priv->max_cdclk_freq = 540000;
5355                 else
5356                         dev_priv->max_cdclk_freq = 675000;
5357         } else if (IS_CHERRYVIEW(dev)) {
5358                 dev_priv->max_cdclk_freq = 320000;
5359         } else if (IS_VALLEYVIEW(dev)) {
5360                 dev_priv->max_cdclk_freq = 400000;
5361         } else {
5362                 /* otherwise assume cdclk is fixed */
5363                 dev_priv->max_cdclk_freq = dev_priv->cdclk_freq;
5364         }
5365
5366         dev_priv->max_dotclk_freq = intel_compute_max_dotclk(dev_priv);
5367
5368         DRM_DEBUG_DRIVER("Max CD clock rate: %d kHz\n",
5369                          dev_priv->max_cdclk_freq);
5370
5371         DRM_DEBUG_DRIVER("Max dotclock rate: %d kHz\n",
5372                          dev_priv->max_dotclk_freq);
5373 }
5374
5375 static void intel_update_cdclk(struct drm_device *dev)
5376 {
5377         struct drm_i915_private *dev_priv = dev->dev_private;
5378
5379         dev_priv->cdclk_freq = dev_priv->display.get_display_clock_speed(dev);
5380         DRM_DEBUG_DRIVER("Current CD clock rate: %d kHz\n",
5381                          dev_priv->cdclk_freq);
5382
5383         /*
5384          * Program the gmbus_freq based on the cdclk frequency.
5385          * BSpec erroneously claims we should aim for 4MHz, but
5386          * in fact 1MHz is the correct frequency.
5387          */
5388         if (IS_VALLEYVIEW(dev) || IS_CHERRYVIEW(dev)) {
5389                 /*
5390                  * Program the gmbus_freq based on the cdclk frequency.
5391                  * BSpec erroneously claims we should aim for 4MHz, but
5392                  * in fact 1MHz is the correct frequency.
5393                  */
5394                 I915_WRITE(GMBUSFREQ_VLV, DIV_ROUND_UP(dev_priv->cdclk_freq, 1000));
5395         }
5396
5397         if (dev_priv->max_cdclk_freq == 0)
5398                 intel_update_max_cdclk(dev);
5399 }
5400
5401 static void broxton_set_cdclk(struct drm_device *dev, int frequency)
5402 {
5403         struct drm_i915_private *dev_priv = dev->dev_private;
5404         uint32_t divider;
5405         uint32_t ratio;
5406         uint32_t current_freq;
5407         int ret;
5408
5409         /* frequency = 19.2MHz * ratio / 2 / div{1,1.5,2,4} */
5410         switch (frequency) {
5411         case 144000:
5412                 divider = BXT_CDCLK_CD2X_DIV_SEL_4;
5413                 ratio = BXT_DE_PLL_RATIO(60);
5414                 break;
5415         case 288000:
5416                 divider = BXT_CDCLK_CD2X_DIV_SEL_2;
5417                 ratio = BXT_DE_PLL_RATIO(60);
5418                 break;
5419         case 384000:
5420                 divider = BXT_CDCLK_CD2X_DIV_SEL_1_5;
5421                 ratio = BXT_DE_PLL_RATIO(60);
5422                 break;
5423         case 576000:
5424                 divider = BXT_CDCLK_CD2X_DIV_SEL_1;
5425                 ratio = BXT_DE_PLL_RATIO(60);
5426                 break;
5427         case 624000:
5428                 divider = BXT_CDCLK_CD2X_DIV_SEL_1;
5429                 ratio = BXT_DE_PLL_RATIO(65);
5430                 break;
5431         case 19200:
5432                 /*
5433                  * Bypass frequency with DE PLL disabled. Init ratio, divider
5434                  * to suppress GCC warning.
5435                  */
5436                 ratio = 0;
5437                 divider = 0;
5438                 break;
5439         default:
5440                 DRM_ERROR("unsupported CDCLK freq %d", frequency);
5441
5442                 return;
5443         }
5444
5445         mutex_lock(&dev_priv->rps.hw_lock);
5446         /* Inform power controller of upcoming frequency change */
5447         ret = sandybridge_pcode_write(dev_priv, HSW_PCODE_DE_WRITE_FREQ_REQ,
5448                                       0x80000000);
5449         mutex_unlock(&dev_priv->rps.hw_lock);
5450
5451         if (ret) {
5452                 DRM_ERROR("PCode CDCLK freq change notify failed (err %d, freq %d)\n",
5453                           ret, frequency);
5454                 return;
5455         }
5456
5457         current_freq = I915_READ(CDCLK_CTL) & CDCLK_FREQ_DECIMAL_MASK;
5458         /* convert from .1 fixpoint MHz with -1MHz offset to kHz */
5459         current_freq = current_freq * 500 + 1000;
5460
5461         /*
5462          * DE PLL has to be disabled when
5463          * - setting to 19.2MHz (bypass, PLL isn't used)
5464          * - before setting to 624MHz (PLL needs toggling)
5465          * - before setting to any frequency from 624MHz (PLL needs toggling)
5466          */
5467         if (frequency == 19200 || frequency == 624000 ||
5468             current_freq == 624000) {
5469                 I915_WRITE(BXT_DE_PLL_ENABLE, ~BXT_DE_PLL_PLL_ENABLE);
5470                 /* Timeout 200us */
5471                 if (wait_for(!(I915_READ(BXT_DE_PLL_ENABLE) & BXT_DE_PLL_LOCK),
5472                              1))
5473                         DRM_ERROR("timout waiting for DE PLL unlock\n");
5474         }
5475
5476         if (frequency != 19200) {
5477                 uint32_t val;
5478
5479                 val = I915_READ(BXT_DE_PLL_CTL);
5480                 val &= ~BXT_DE_PLL_RATIO_MASK;
5481                 val |= ratio;
5482                 I915_WRITE(BXT_DE_PLL_CTL, val);
5483
5484                 I915_WRITE(BXT_DE_PLL_ENABLE, BXT_DE_PLL_PLL_ENABLE);
5485                 /* Timeout 200us */
5486                 if (wait_for(I915_READ(BXT_DE_PLL_ENABLE) & BXT_DE_PLL_LOCK, 1))
5487                         DRM_ERROR("timeout waiting for DE PLL lock\n");
5488
5489                 val = I915_READ(CDCLK_CTL);
5490                 val &= ~BXT_CDCLK_CD2X_DIV_SEL_MASK;
5491                 val |= divider;
5492                 /*
5493                  * Disable SSA Precharge when CD clock frequency < 500 MHz,
5494                  * enable otherwise.
5495                  */
5496                 val &= ~BXT_CDCLK_SSA_PRECHARGE_ENABLE;
5497                 if (frequency >= 500000)
5498                         val |= BXT_CDCLK_SSA_PRECHARGE_ENABLE;
5499
5500                 val &= ~CDCLK_FREQ_DECIMAL_MASK;
5501                 /* convert from kHz to .1 fixpoint MHz with -1MHz offset */
5502                 val |= (frequency - 1000) / 500;
5503                 I915_WRITE(CDCLK_CTL, val);
5504         }
5505
5506         mutex_lock(&dev_priv->rps.hw_lock);
5507         ret = sandybridge_pcode_write(dev_priv, HSW_PCODE_DE_WRITE_FREQ_REQ,
5508                                       DIV_ROUND_UP(frequency, 25000));
5509         mutex_unlock(&dev_priv->rps.hw_lock);
5510
5511         if (ret) {
5512                 DRM_ERROR("PCode CDCLK freq set failed, (err %d, freq %d)\n",
5513                           ret, frequency);
5514                 return;
5515         }
5516
5517         intel_update_cdclk(dev);
5518 }
5519
5520 void broxton_init_cdclk(struct drm_device *dev)
5521 {
5522         struct drm_i915_private *dev_priv = dev->dev_private;
5523         uint32_t val;
5524
5525         /*
5526          * NDE_RSTWRN_OPT RST PCH Handshake En must always be 0b on BXT
5527          * or else the reset will hang because there is no PCH to respond.
5528          * Move the handshake programming to initialization sequence.
5529          * Previously was left up to BIOS.
5530          */
5531         val = I915_READ(HSW_NDE_RSTWRN_OPT);
5532         val &= ~RESET_PCH_HANDSHAKE_ENABLE;
5533         I915_WRITE(HSW_NDE_RSTWRN_OPT, val);
5534
5535         /* Enable PG1 for cdclk */
5536         intel_display_power_get(dev_priv, POWER_DOMAIN_PLLS);
5537
5538         /* check if cd clock is enabled */
5539         if (I915_READ(BXT_DE_PLL_ENABLE) & BXT_DE_PLL_PLL_ENABLE) {
5540                 DRM_DEBUG_KMS("Display already initialized\n");
5541                 return;
5542         }
5543
5544         /*
5545          * FIXME:
5546          * - The initial CDCLK needs to be read from VBT.
5547          *   Need to make this change after VBT has changes for BXT.
5548          * - check if setting the max (or any) cdclk freq is really necessary
5549          *   here, it belongs to modeset time
5550          */
5551         broxton_set_cdclk(dev, 624000);
5552
5553         I915_WRITE(DBUF_CTL, I915_READ(DBUF_CTL) | DBUF_POWER_REQUEST);
5554         POSTING_READ(DBUF_CTL);
5555
5556         udelay(10);
5557
5558         if (!(I915_READ(DBUF_CTL) & DBUF_POWER_STATE))
5559                 DRM_ERROR("DBuf power enable timeout!\n");
5560 }
5561
5562 void broxton_uninit_cdclk(struct drm_device *dev)
5563 {
5564         struct drm_i915_private *dev_priv = dev->dev_private;
5565
5566         I915_WRITE(DBUF_CTL, I915_READ(DBUF_CTL) & ~DBUF_POWER_REQUEST);
5567         POSTING_READ(DBUF_CTL);
5568
5569         udelay(10);
5570
5571         if (I915_READ(DBUF_CTL) & DBUF_POWER_STATE)
5572                 DRM_ERROR("DBuf power disable timeout!\n");
5573
5574         /* Set minimum (bypass) frequency, in effect turning off the DE PLL */
5575         broxton_set_cdclk(dev, 19200);
5576
5577         intel_display_power_put(dev_priv, POWER_DOMAIN_PLLS);
5578 }
5579
5580 static const struct skl_cdclk_entry {
5581         unsigned int freq;
5582         unsigned int vco;
5583 } skl_cdclk_frequencies[] = {
5584         { .freq = 308570, .vco = 8640 },
5585         { .freq = 337500, .vco = 8100 },
5586         { .freq = 432000, .vco = 8640 },
5587         { .freq = 450000, .vco = 8100 },
5588         { .freq = 540000, .vco = 8100 },
5589         { .freq = 617140, .vco = 8640 },
5590         { .freq = 675000, .vco = 8100 },
5591 };
5592
5593 static unsigned int skl_cdclk_decimal(unsigned int freq)
5594 {
5595         return (freq - 1000) / 500;
5596 }
5597
5598 static unsigned int skl_cdclk_get_vco(unsigned int freq)
5599 {
5600         unsigned int i;
5601
5602         for (i = 0; i < ARRAY_SIZE(skl_cdclk_frequencies); i++) {
5603                 const struct skl_cdclk_entry *e = &skl_cdclk_frequencies[i];
5604
5605                 if (e->freq == freq)
5606                         return e->vco;
5607         }
5608
5609         return 8100;
5610 }
5611
5612 static void
5613 skl_dpll0_enable(struct drm_i915_private *dev_priv, unsigned int required_vco)
5614 {
5615         unsigned int min_freq;
5616         u32 val;
5617
5618         /* select the minimum CDCLK before enabling DPLL 0 */
5619         val = I915_READ(CDCLK_CTL);
5620         val &= ~CDCLK_FREQ_SEL_MASK | ~CDCLK_FREQ_DECIMAL_MASK;
5621         val |= CDCLK_FREQ_337_308;
5622
5623         if (required_vco == 8640)
5624                 min_freq = 308570;
5625         else
5626                 min_freq = 337500;
5627
5628         val = CDCLK_FREQ_337_308 | skl_cdclk_decimal(min_freq);
5629
5630         I915_WRITE(CDCLK_CTL, val);
5631         POSTING_READ(CDCLK_CTL);
5632
5633         /*
5634          * We always enable DPLL0 with the lowest link rate possible, but still
5635          * taking into account the VCO required to operate the eDP panel at the
5636          * desired frequency. The usual DP link rates operate with a VCO of
5637          * 8100 while the eDP 1.4 alternate link rates need a VCO of 8640.
5638          * The modeset code is responsible for the selection of the exact link
5639          * rate later on, with the constraint of choosing a frequency that
5640          * works with required_vco.
5641          */
5642         val = I915_READ(DPLL_CTRL1);
5643
5644         val &= ~(DPLL_CTRL1_HDMI_MODE(SKL_DPLL0) | DPLL_CTRL1_SSC(SKL_DPLL0) |
5645                  DPLL_CTRL1_LINK_RATE_MASK(SKL_DPLL0));
5646         val |= DPLL_CTRL1_OVERRIDE(SKL_DPLL0);
5647         if (required_vco == 8640)
5648                 val |= DPLL_CTRL1_LINK_RATE(DPLL_CTRL1_LINK_RATE_1080,
5649                                             SKL_DPLL0);
5650         else
5651                 val |= DPLL_CTRL1_LINK_RATE(DPLL_CTRL1_LINK_RATE_810,
5652                                             SKL_DPLL0);
5653
5654         I915_WRITE(DPLL_CTRL1, val);
5655         POSTING_READ(DPLL_CTRL1);
5656
5657         I915_WRITE(LCPLL1_CTL, I915_READ(LCPLL1_CTL) | LCPLL_PLL_ENABLE);
5658
5659         if (wait_for(I915_READ(LCPLL1_CTL) & LCPLL_PLL_LOCK, 5))
5660                 DRM_ERROR("DPLL0 not locked\n");
5661 }
5662
5663 static bool skl_cdclk_pcu_ready(struct drm_i915_private *dev_priv)
5664 {
5665         int ret;
5666         u32 val;
5667
5668         /* inform PCU we want to change CDCLK */
5669         val = SKL_CDCLK_PREPARE_FOR_CHANGE;
5670         mutex_lock(&dev_priv->rps.hw_lock);
5671         ret = sandybridge_pcode_read(dev_priv, SKL_PCODE_CDCLK_CONTROL, &val);
5672         mutex_unlock(&dev_priv->rps.hw_lock);
5673
5674         return ret == 0 && (val & SKL_CDCLK_READY_FOR_CHANGE);
5675 }
5676
5677 static bool skl_cdclk_wait_for_pcu_ready(struct drm_i915_private *dev_priv)
5678 {
5679         unsigned int i;
5680
5681         for (i = 0; i < 15; i++) {
5682                 if (skl_cdclk_pcu_ready(dev_priv))
5683                         return true;
5684                 udelay(10);
5685         }
5686
5687         return false;
5688 }
5689
5690 static void skl_set_cdclk(struct drm_i915_private *dev_priv, unsigned int freq)
5691 {
5692         struct drm_device *dev = dev_priv->dev;
5693         u32 freq_select, pcu_ack;
5694
5695         DRM_DEBUG_DRIVER("Changing CDCLK to %dKHz\n", freq);
5696
5697         if (!skl_cdclk_wait_for_pcu_ready(dev_priv)) {
5698                 DRM_ERROR("failed to inform PCU about cdclk change\n");
5699                 return;
5700         }
5701
5702         /* set CDCLK_CTL */
5703         switch(freq) {
5704         case 450000:
5705         case 432000:
5706                 freq_select = CDCLK_FREQ_450_432;
5707                 pcu_ack = 1;
5708                 break;
5709         case 540000:
5710                 freq_select = CDCLK_FREQ_540;
5711                 pcu_ack = 2;
5712                 break;
5713         case 308570:
5714         case 337500:
5715         default:
5716                 freq_select = CDCLK_FREQ_337_308;
5717                 pcu_ack = 0;
5718                 break;
5719         case 617140:
5720         case 675000:
5721                 freq_select = CDCLK_FREQ_675_617;
5722                 pcu_ack = 3;
5723                 break;
5724         }
5725
5726         I915_WRITE(CDCLK_CTL, freq_select | skl_cdclk_decimal(freq));
5727         POSTING_READ(CDCLK_CTL);
5728
5729         /* inform PCU of the change */
5730         mutex_lock(&dev_priv->rps.hw_lock);
5731         sandybridge_pcode_write(dev_priv, SKL_PCODE_CDCLK_CONTROL, pcu_ack);
5732         mutex_unlock(&dev_priv->rps.hw_lock);
5733
5734         intel_update_cdclk(dev);
5735 }
5736
5737 void skl_uninit_cdclk(struct drm_i915_private *dev_priv)
5738 {
5739         /* disable DBUF power */
5740         I915_WRITE(DBUF_CTL, I915_READ(DBUF_CTL) & ~DBUF_POWER_REQUEST);
5741         POSTING_READ(DBUF_CTL);
5742
5743         udelay(10);
5744
5745         if (I915_READ(DBUF_CTL) & DBUF_POWER_STATE)
5746                 DRM_ERROR("DBuf power disable timeout\n");
5747
5748         /* disable DPLL0 */
5749         I915_WRITE(LCPLL1_CTL, I915_READ(LCPLL1_CTL) & ~LCPLL_PLL_ENABLE);
5750         if (wait_for(!(I915_READ(LCPLL1_CTL) & LCPLL_PLL_LOCK), 1))
5751                 DRM_ERROR("Couldn't disable DPLL0\n");
5752 }
5753
5754 void skl_init_cdclk(struct drm_i915_private *dev_priv)
5755 {
5756         unsigned int required_vco;
5757
5758         /* DPLL0 not enabled (happens on early BIOS versions) */
5759         if (!(I915_READ(LCPLL1_CTL) & LCPLL_PLL_ENABLE)) {
5760                 /* enable DPLL0 */
5761                 required_vco = skl_cdclk_get_vco(dev_priv->skl_boot_cdclk);
5762                 skl_dpll0_enable(dev_priv, required_vco);
5763         }
5764
5765         /* set CDCLK to the frequency the BIOS chose */
5766         skl_set_cdclk(dev_priv, dev_priv->skl_boot_cdclk);
5767
5768         /* enable DBUF power */
5769         I915_WRITE(DBUF_CTL, I915_READ(DBUF_CTL) | DBUF_POWER_REQUEST);
5770         POSTING_READ(DBUF_CTL);
5771
5772         udelay(10);
5773
5774         if (!(I915_READ(DBUF_CTL) & DBUF_POWER_STATE))
5775                 DRM_ERROR("DBuf power enable timeout\n");
5776 }
5777
5778 int skl_sanitize_cdclk(struct drm_i915_private *dev_priv)
5779 {
5780         uint32_t lcpll1 = I915_READ(LCPLL1_CTL);
5781         uint32_t cdctl = I915_READ(CDCLK_CTL);
5782         int freq = dev_priv->skl_boot_cdclk;
5783
5784         /*
5785          * check if the pre-os intialized the display
5786          * There is SWF18 scratchpad register defined which is set by the
5787          * pre-os which can be used by the OS drivers to check the status
5788          */
5789         if ((I915_READ(SWF_ILK(0x18)) & 0x00FFFFFF) == 0)
5790                 goto sanitize;
5791
5792         /* Is PLL enabled and locked ? */
5793         if (!((lcpll1 & LCPLL_PLL_ENABLE) && (lcpll1 & LCPLL_PLL_LOCK)))
5794                 goto sanitize;
5795
5796         /* DPLL okay; verify the cdclock
5797          *
5798          * Noticed in some instances that the freq selection is correct but
5799          * decimal part is programmed wrong from BIOS where pre-os does not
5800          * enable display. Verify the same as well.
5801          */
5802         if (cdctl == ((cdctl & CDCLK_FREQ_SEL_MASK) | skl_cdclk_decimal(freq)))
5803                 /* All well; nothing to sanitize */
5804                 return false;
5805 sanitize:
5806         /*
5807          * As of now initialize with max cdclk till
5808          * we get dynamic cdclk support
5809          * */
5810         dev_priv->skl_boot_cdclk = dev_priv->max_cdclk_freq;
5811         skl_init_cdclk(dev_priv);
5812
5813         /* we did have to sanitize */
5814         return true;
5815 }
5816
5817 /* Adjust CDclk dividers to allow high res or save power if possible */
5818 static void valleyview_set_cdclk(struct drm_device *dev, int cdclk)
5819 {
5820         struct drm_i915_private *dev_priv = dev->dev_private;
5821         u32 val, cmd;
5822
5823         WARN_ON(dev_priv->display.get_display_clock_speed(dev)
5824                                         != dev_priv->cdclk_freq);
5825
5826         if (cdclk >= 320000) /* jump to highest voltage for 400MHz too */
5827                 cmd = 2;
5828         else if (cdclk == 266667)
5829                 cmd = 1;
5830         else
5831                 cmd = 0;
5832
5833         mutex_lock(&dev_priv->rps.hw_lock);
5834         val = vlv_punit_read(dev_priv, PUNIT_REG_DSPFREQ);
5835         val &= ~DSPFREQGUAR_MASK;
5836         val |= (cmd << DSPFREQGUAR_SHIFT);
5837         vlv_punit_write(dev_priv, PUNIT_REG_DSPFREQ, val);
5838         if (wait_for((vlv_punit_read(dev_priv, PUNIT_REG_DSPFREQ) &
5839                       DSPFREQSTAT_MASK) == (cmd << DSPFREQSTAT_SHIFT),
5840                      50)) {
5841                 DRM_ERROR("timed out waiting for CDclk change\n");
5842         }
5843         mutex_unlock(&dev_priv->rps.hw_lock);
5844
5845         mutex_lock(&dev_priv->sb_lock);
5846
5847         if (cdclk == 400000) {
5848                 u32 divider;
5849
5850                 divider = DIV_ROUND_CLOSEST(dev_priv->hpll_freq << 1, cdclk) - 1;
5851
5852                 /* adjust cdclk divider */
5853                 val = vlv_cck_read(dev_priv, CCK_DISPLAY_CLOCK_CONTROL);
5854                 val &= ~CCK_FREQUENCY_VALUES;
5855                 val |= divider;
5856                 vlv_cck_write(dev_priv, CCK_DISPLAY_CLOCK_CONTROL, val);
5857
5858                 if (wait_for((vlv_cck_read(dev_priv, CCK_DISPLAY_CLOCK_CONTROL) &
5859                               CCK_FREQUENCY_STATUS) == (divider << CCK_FREQUENCY_STATUS_SHIFT),
5860                              50))
5861                         DRM_ERROR("timed out waiting for CDclk change\n");
5862         }
5863
5864         /* adjust self-refresh exit latency value */
5865         val = vlv_bunit_read(dev_priv, BUNIT_REG_BISOC);
5866         val &= ~0x7f;
5867
5868         /*
5869          * For high bandwidth configs, we set a higher latency in the bunit
5870          * so that the core display fetch happens in time to avoid underruns.
5871          */
5872         if (cdclk == 400000)
5873                 val |= 4500 / 250; /* 4.5 usec */
5874         else
5875                 val |= 3000 / 250; /* 3.0 usec */
5876         vlv_bunit_write(dev_priv, BUNIT_REG_BISOC, val);
5877
5878         mutex_unlock(&dev_priv->sb_lock);
5879
5880         intel_update_cdclk(dev);
5881 }
5882
5883 static void cherryview_set_cdclk(struct drm_device *dev, int cdclk)
5884 {
5885         struct drm_i915_private *dev_priv = dev->dev_private;
5886         u32 val, cmd;
5887
5888         WARN_ON(dev_priv->display.get_display_clock_speed(dev)
5889                                                 != dev_priv->cdclk_freq);
5890
5891         switch (cdclk) {
5892         case 333333:
5893         case 320000:
5894         case 266667:
5895         case 200000:
5896                 break;
5897         default:
5898                 MISSING_CASE(cdclk);
5899                 return;
5900         }
5901
5902         /*
5903          * Specs are full of misinformation, but testing on actual
5904          * hardware has shown that we just need to write the desired
5905          * CCK divider into the Punit register.
5906          */
5907         cmd = DIV_ROUND_CLOSEST(dev_priv->hpll_freq << 1, cdclk) - 1;
5908
5909         mutex_lock(&dev_priv->rps.hw_lock);
5910         val = vlv_punit_read(dev_priv, PUNIT_REG_DSPFREQ);
5911         val &= ~DSPFREQGUAR_MASK_CHV;
5912         val |= (cmd << DSPFREQGUAR_SHIFT_CHV);
5913         vlv_punit_write(dev_priv, PUNIT_REG_DSPFREQ, val);
5914         if (wait_for((vlv_punit_read(dev_priv, PUNIT_REG_DSPFREQ) &
5915                       DSPFREQSTAT_MASK_CHV) == (cmd << DSPFREQSTAT_SHIFT_CHV),
5916                      50)) {
5917                 DRM_ERROR("timed out waiting for CDclk change\n");
5918         }
5919         mutex_unlock(&dev_priv->rps.hw_lock);
5920
5921         intel_update_cdclk(dev);
5922 }
5923
5924 static int valleyview_calc_cdclk(struct drm_i915_private *dev_priv,
5925                                  int max_pixclk)
5926 {
5927         int freq_320 = (dev_priv->hpll_freq <<  1) % 320000 != 0 ? 333333 : 320000;
5928         int limit = IS_CHERRYVIEW(dev_priv) ? 95 : 90;
5929
5930         /*
5931          * Really only a few cases to deal with, as only 4 CDclks are supported:
5932          *   200MHz
5933          *   267MHz
5934          *   320/333MHz (depends on HPLL freq)
5935          *   400MHz (VLV only)
5936          * So we check to see whether we're above 90% (VLV) or 95% (CHV)
5937          * of the lower bin and adjust if needed.
5938          *
5939          * We seem to get an unstable or solid color picture at 200MHz.
5940          * Not sure what's wrong. For now use 200MHz only when all pipes
5941          * are off.
5942          */
5943         if (!IS_CHERRYVIEW(dev_priv) &&
5944             max_pixclk > freq_320*limit/100)
5945                 return 400000;
5946         else if (max_pixclk > 266667*limit/100)
5947                 return freq_320;
5948         else if (max_pixclk > 0)
5949                 return 266667;
5950         else
5951                 return 200000;
5952 }
5953
5954 static int broxton_calc_cdclk(struct drm_i915_private *dev_priv,
5955                               int max_pixclk)
5956 {
5957         /*
5958          * FIXME:
5959          * - remove the guardband, it's not needed on BXT
5960          * - set 19.2MHz bypass frequency if there are no active pipes
5961          */
5962         if (max_pixclk > 576000*9/10)
5963                 return 624000;
5964         else if (max_pixclk > 384000*9/10)
5965                 return 576000;
5966         else if (max_pixclk > 288000*9/10)
5967                 return 384000;
5968         else if (max_pixclk > 144000*9/10)
5969                 return 288000;
5970         else
5971                 return 144000;
5972 }
5973
5974 /* Compute the max pixel clock for new configuration. */
5975 static int intel_mode_max_pixclk(struct drm_device *dev,
5976                                  struct drm_atomic_state *state)
5977 {
5978         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
5979         struct drm_i915_private *dev_priv = dev->dev_private;
5980         struct drm_crtc *crtc;
5981         struct drm_crtc_state *crtc_state;
5982         unsigned max_pixclk = 0, i;
5983         enum pipe pipe;
5984
5985         memcpy(intel_state->min_pixclk, dev_priv->min_pixclk,
5986                sizeof(intel_state->min_pixclk));
5987
5988         for_each_crtc_in_state(state, crtc, crtc_state, i) {
5989                 int pixclk = 0;
5990
5991                 if (crtc_state->enable)
5992                         pixclk = crtc_state->adjusted_mode.crtc_clock;
5993
5994                 intel_state->min_pixclk[i] = pixclk;
5995         }
5996
5997         for_each_pipe(dev_priv, pipe)
5998                 max_pixclk = max(intel_state->min_pixclk[pipe], max_pixclk);
5999
6000         return max_pixclk;
6001 }
6002
6003 static int valleyview_modeset_calc_cdclk(struct drm_atomic_state *state)
6004 {
6005         struct drm_device *dev = state->dev;
6006         struct drm_i915_private *dev_priv = dev->dev_private;
6007         int max_pixclk = intel_mode_max_pixclk(dev, state);
6008         struct intel_atomic_state *intel_state =
6009                 to_intel_atomic_state(state);
6010
6011         if (max_pixclk < 0)
6012                 return max_pixclk;
6013
6014         intel_state->cdclk = intel_state->dev_cdclk =
6015                 valleyview_calc_cdclk(dev_priv, max_pixclk);
6016
6017         if (!intel_state->active_crtcs)
6018                 intel_state->dev_cdclk = valleyview_calc_cdclk(dev_priv, 0);
6019
6020         return 0;
6021 }
6022
6023 static int broxton_modeset_calc_cdclk(struct drm_atomic_state *state)
6024 {
6025         struct drm_device *dev = state->dev;
6026         struct drm_i915_private *dev_priv = dev->dev_private;
6027         int max_pixclk = intel_mode_max_pixclk(dev, state);
6028         struct intel_atomic_state *intel_state =
6029                 to_intel_atomic_state(state);
6030
6031         if (max_pixclk < 0)
6032                 return max_pixclk;
6033
6034         intel_state->cdclk = intel_state->dev_cdclk =
6035                 broxton_calc_cdclk(dev_priv, max_pixclk);
6036
6037         if (!intel_state->active_crtcs)
6038                 intel_state->dev_cdclk = broxton_calc_cdclk(dev_priv, 0);
6039
6040         return 0;
6041 }
6042
6043 static void vlv_program_pfi_credits(struct drm_i915_private *dev_priv)
6044 {
6045         unsigned int credits, default_credits;
6046
6047         if (IS_CHERRYVIEW(dev_priv))
6048                 default_credits = PFI_CREDIT(12);
6049         else
6050                 default_credits = PFI_CREDIT(8);
6051
6052         if (dev_priv->cdclk_freq >= dev_priv->czclk_freq) {
6053                 /* CHV suggested value is 31 or 63 */
6054                 if (IS_CHERRYVIEW(dev_priv))
6055                         credits = PFI_CREDIT_63;
6056                 else
6057                         credits = PFI_CREDIT(15);
6058         } else {
6059                 credits = default_credits;
6060         }
6061
6062         /*
6063          * WA - write default credits before re-programming
6064          * FIXME: should we also set the resend bit here?
6065          */
6066         I915_WRITE(GCI_CONTROL, VGA_FAST_MODE_DISABLE |
6067                    default_credits);
6068
6069         I915_WRITE(GCI_CONTROL, VGA_FAST_MODE_DISABLE |
6070                    credits | PFI_CREDIT_RESEND);
6071
6072         /*
6073          * FIXME is this guaranteed to clear
6074          * immediately or should we poll for it?
6075          */
6076         WARN_ON(I915_READ(GCI_CONTROL) & PFI_CREDIT_RESEND);
6077 }
6078
6079 static void valleyview_modeset_commit_cdclk(struct drm_atomic_state *old_state)
6080 {
6081         struct drm_device *dev = old_state->dev;
6082         struct drm_i915_private *dev_priv = dev->dev_private;
6083         struct intel_atomic_state *old_intel_state =
6084                 to_intel_atomic_state(old_state);
6085         unsigned req_cdclk = old_intel_state->dev_cdclk;
6086
6087         /*
6088          * FIXME: We can end up here with all power domains off, yet
6089          * with a CDCLK frequency other than the minimum. To account
6090          * for this take the PIPE-A power domain, which covers the HW
6091          * blocks needed for the following programming. This can be
6092          * removed once it's guaranteed that we get here either with
6093          * the minimum CDCLK set, or the required power domains
6094          * enabled.
6095          */
6096         intel_display_power_get(dev_priv, POWER_DOMAIN_PIPE_A);
6097
6098         if (IS_CHERRYVIEW(dev))
6099                 cherryview_set_cdclk(dev, req_cdclk);
6100         else
6101                 valleyview_set_cdclk(dev, req_cdclk);
6102
6103         vlv_program_pfi_credits(dev_priv);
6104
6105         intel_display_power_put(dev_priv, POWER_DOMAIN_PIPE_A);
6106 }
6107
6108 static void valleyview_crtc_enable(struct drm_crtc *crtc)
6109 {
6110         struct drm_device *dev = crtc->dev;
6111         struct drm_i915_private *dev_priv = to_i915(dev);
6112         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
6113         struct intel_encoder *encoder;
6114         int pipe = intel_crtc->pipe;
6115
6116         if (WARN_ON(intel_crtc->active))
6117                 return;
6118
6119         if (intel_crtc->config->has_dp_encoder)
6120                 intel_dp_set_m_n(intel_crtc, M1_N1);
6121
6122         intel_set_pipe_timings(intel_crtc);
6123
6124         if (IS_CHERRYVIEW(dev) && pipe == PIPE_B) {
6125                 struct drm_i915_private *dev_priv = dev->dev_private;
6126
6127                 I915_WRITE(CHV_BLEND(pipe), CHV_BLEND_LEGACY);
6128                 I915_WRITE(CHV_CANVAS(pipe), 0);
6129         }
6130
6131         i9xx_set_pipeconf(intel_crtc);
6132
6133         intel_crtc->active = true;
6134
6135         intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
6136
6137         for_each_encoder_on_crtc(dev, crtc, encoder)
6138                 if (encoder->pre_pll_enable)
6139                         encoder->pre_pll_enable(encoder);
6140
6141         if (!intel_crtc->config->has_dsi_encoder) {
6142                 if (IS_CHERRYVIEW(dev)) {
6143                         chv_prepare_pll(intel_crtc, intel_crtc->config);
6144                         chv_enable_pll(intel_crtc, intel_crtc->config);
6145                 } else {
6146                         vlv_prepare_pll(intel_crtc, intel_crtc->config);
6147                         vlv_enable_pll(intel_crtc, intel_crtc->config);
6148                 }
6149         }
6150
6151         for_each_encoder_on_crtc(dev, crtc, encoder)
6152                 if (encoder->pre_enable)
6153                         encoder->pre_enable(encoder);
6154
6155         i9xx_pfit_enable(intel_crtc);
6156
6157         intel_crtc_load_lut(crtc);
6158
6159         intel_update_watermarks(crtc);
6160         intel_enable_pipe(intel_crtc);
6161
6162         assert_vblank_disabled(crtc);
6163         drm_crtc_vblank_on(crtc);
6164
6165         for_each_encoder_on_crtc(dev, crtc, encoder)
6166                 encoder->enable(encoder);
6167 }
6168
6169 static void i9xx_set_pll_dividers(struct intel_crtc *crtc)
6170 {
6171         struct drm_device *dev = crtc->base.dev;
6172         struct drm_i915_private *dev_priv = dev->dev_private;
6173
6174         I915_WRITE(FP0(crtc->pipe), crtc->config->dpll_hw_state.fp0);
6175         I915_WRITE(FP1(crtc->pipe), crtc->config->dpll_hw_state.fp1);
6176 }
6177
6178 static void i9xx_crtc_enable(struct drm_crtc *crtc)
6179 {
6180         struct drm_device *dev = crtc->dev;
6181         struct drm_i915_private *dev_priv = to_i915(dev);
6182         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
6183         struct intel_encoder *encoder;
6184         int pipe = intel_crtc->pipe;
6185
6186         if (WARN_ON(intel_crtc->active))
6187                 return;
6188
6189         i9xx_set_pll_dividers(intel_crtc);
6190
6191         if (intel_crtc->config->has_dp_encoder)
6192                 intel_dp_set_m_n(intel_crtc, M1_N1);
6193
6194         intel_set_pipe_timings(intel_crtc);
6195
6196         i9xx_set_pipeconf(intel_crtc);
6197
6198         intel_crtc->active = true;
6199
6200         if (!IS_GEN2(dev))
6201                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
6202
6203         for_each_encoder_on_crtc(dev, crtc, encoder)
6204                 if (encoder->pre_enable)
6205                         encoder->pre_enable(encoder);
6206
6207         i9xx_enable_pll(intel_crtc);
6208
6209         i9xx_pfit_enable(intel_crtc);
6210
6211         intel_crtc_load_lut(crtc);
6212
6213         intel_update_watermarks(crtc);
6214         intel_enable_pipe(intel_crtc);
6215
6216         assert_vblank_disabled(crtc);
6217         drm_crtc_vblank_on(crtc);
6218
6219         for_each_encoder_on_crtc(dev, crtc, encoder)
6220                 encoder->enable(encoder);
6221 }
6222
6223 static void i9xx_pfit_disable(struct intel_crtc *crtc)
6224 {
6225         struct drm_device *dev = crtc->base.dev;
6226         struct drm_i915_private *dev_priv = dev->dev_private;
6227
6228         if (!crtc->config->gmch_pfit.control)
6229                 return;
6230
6231         assert_pipe_disabled(dev_priv, crtc->pipe);
6232
6233         DRM_DEBUG_DRIVER("disabling pfit, current: 0x%08x\n",
6234                          I915_READ(PFIT_CONTROL));
6235         I915_WRITE(PFIT_CONTROL, 0);
6236 }
6237
6238 static void i9xx_crtc_disable(struct drm_crtc *crtc)
6239 {
6240         struct drm_device *dev = crtc->dev;
6241         struct drm_i915_private *dev_priv = dev->dev_private;
6242         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
6243         struct intel_encoder *encoder;
6244         int pipe = intel_crtc->pipe;
6245
6246         /*
6247          * On gen2 planes are double buffered but the pipe isn't, so we must
6248          * wait for planes to fully turn off before disabling the pipe.
6249          * We also need to wait on all gmch platforms because of the
6250          * self-refresh mode constraint explained above.
6251          */
6252         intel_wait_for_vblank(dev, pipe);
6253
6254         for_each_encoder_on_crtc(dev, crtc, encoder)
6255                 encoder->disable(encoder);
6256
6257         drm_crtc_vblank_off(crtc);
6258         assert_vblank_disabled(crtc);
6259
6260         intel_disable_pipe(intel_crtc);
6261
6262         i9xx_pfit_disable(intel_crtc);
6263
6264         for_each_encoder_on_crtc(dev, crtc, encoder)
6265                 if (encoder->post_disable)
6266                         encoder->post_disable(encoder);
6267
6268         if (!intel_crtc->config->has_dsi_encoder) {
6269                 if (IS_CHERRYVIEW(dev))
6270                         chv_disable_pll(dev_priv, pipe);
6271                 else if (IS_VALLEYVIEW(dev))
6272                         vlv_disable_pll(dev_priv, pipe);
6273                 else
6274                         i9xx_disable_pll(intel_crtc);
6275         }
6276
6277         for_each_encoder_on_crtc(dev, crtc, encoder)
6278                 if (encoder->post_pll_disable)
6279                         encoder->post_pll_disable(encoder);
6280
6281         if (!IS_GEN2(dev))
6282                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, false);
6283 }
6284
6285 static void intel_crtc_disable_noatomic(struct drm_crtc *crtc)
6286 {
6287         struct intel_encoder *encoder;
6288         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
6289         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
6290         enum intel_display_power_domain domain;
6291         unsigned long domains;
6292
6293         if (!intel_crtc->active)
6294                 return;
6295
6296         if (to_intel_plane_state(crtc->primary->state)->visible) {
6297                 WARN_ON(intel_crtc->unpin_work);
6298
6299                 intel_pre_disable_primary_noatomic(crtc);
6300
6301                 intel_crtc_disable_planes(crtc, 1 << drm_plane_index(crtc->primary));
6302                 to_intel_plane_state(crtc->primary->state)->visible = false;
6303         }
6304
6305         dev_priv->display.crtc_disable(crtc);
6306
6307         DRM_DEBUG_KMS("[CRTC:%d] hw state adjusted, was enabled, now disabled\n",
6308                       crtc->base.id);
6309
6310         WARN_ON(drm_atomic_set_mode_for_crtc(crtc->state, NULL) < 0);
6311         crtc->state->active = false;
6312         intel_crtc->active = false;
6313         crtc->enabled = false;
6314         crtc->state->connector_mask = 0;
6315         crtc->state->encoder_mask = 0;
6316
6317         for_each_encoder_on_crtc(crtc->dev, crtc, encoder)
6318                 encoder->base.crtc = NULL;
6319
6320         intel_fbc_disable(intel_crtc);
6321         intel_update_watermarks(crtc);
6322         intel_disable_shared_dpll(intel_crtc);
6323
6324         domains = intel_crtc->enabled_power_domains;
6325         for_each_power_domain(domain, domains)
6326                 intel_display_power_put(dev_priv, domain);
6327         intel_crtc->enabled_power_domains = 0;
6328
6329         dev_priv->active_crtcs &= ~(1 << intel_crtc->pipe);
6330         dev_priv->min_pixclk[intel_crtc->pipe] = 0;
6331 }
6332
6333 /*
6334  * turn all crtc's off, but do not adjust state
6335  * This has to be paired with a call to intel_modeset_setup_hw_state.
6336  */
6337 int intel_display_suspend(struct drm_device *dev)
6338 {
6339         struct drm_i915_private *dev_priv = to_i915(dev);
6340         struct drm_atomic_state *state;
6341         int ret;
6342
6343         state = drm_atomic_helper_suspend(dev);
6344         ret = PTR_ERR_OR_ZERO(state);
6345         if (ret)
6346                 DRM_ERROR("Suspending crtc's failed with %i\n", ret);
6347         else
6348                 dev_priv->modeset_restore_state = state;
6349         return ret;
6350 }
6351
6352 void intel_encoder_destroy(struct drm_encoder *encoder)
6353 {
6354         struct intel_encoder *intel_encoder = to_intel_encoder(encoder);
6355
6356         drm_encoder_cleanup(encoder);
6357         kfree(intel_encoder);
6358 }
6359
6360 /* Cross check the actual hw state with our own modeset state tracking (and it's
6361  * internal consistency). */
6362 static void intel_connector_check_state(struct intel_connector *connector)
6363 {
6364         struct drm_crtc *crtc = connector->base.state->crtc;
6365
6366         DRM_DEBUG_KMS("[CONNECTOR:%d:%s]\n",
6367                       connector->base.base.id,
6368                       connector->base.name);
6369
6370         if (connector->get_hw_state(connector)) {
6371                 struct intel_encoder *encoder = connector->encoder;
6372                 struct drm_connector_state *conn_state = connector->base.state;
6373
6374                 I915_STATE_WARN(!crtc,
6375                          "connector enabled without attached crtc\n");
6376
6377                 if (!crtc)
6378                         return;
6379
6380                 I915_STATE_WARN(!crtc->state->active,
6381                       "connector is active, but attached crtc isn't\n");
6382
6383                 if (!encoder || encoder->type == INTEL_OUTPUT_DP_MST)
6384                         return;
6385
6386                 I915_STATE_WARN(conn_state->best_encoder != &encoder->base,
6387                         "atomic encoder doesn't match attached encoder\n");
6388
6389                 I915_STATE_WARN(conn_state->crtc != encoder->base.crtc,
6390                         "attached encoder crtc differs from connector crtc\n");
6391         } else {
6392                 I915_STATE_WARN(crtc && crtc->state->active,
6393                         "attached crtc is active, but connector isn't\n");
6394                 I915_STATE_WARN(!crtc && connector->base.state->best_encoder,
6395                         "best encoder set without crtc!\n");
6396         }
6397 }
6398
6399 int intel_connector_init(struct intel_connector *connector)
6400 {
6401         drm_atomic_helper_connector_reset(&connector->base);
6402
6403         if (!connector->base.state)
6404                 return -ENOMEM;
6405
6406         return 0;
6407 }
6408
6409 struct intel_connector *intel_connector_alloc(void)
6410 {
6411         struct intel_connector *connector;
6412
6413         connector = kzalloc(sizeof *connector, GFP_KERNEL);
6414         if (!connector)
6415                 return NULL;
6416
6417         if (intel_connector_init(connector) < 0) {
6418                 kfree(connector);
6419                 return NULL;
6420         }
6421
6422         return connector;
6423 }
6424
6425 /* Simple connector->get_hw_state implementation for encoders that support only
6426  * one connector and no cloning and hence the encoder state determines the state
6427  * of the connector. */
6428 bool intel_connector_get_hw_state(struct intel_connector *connector)
6429 {
6430         enum pipe pipe = 0;
6431         struct intel_encoder *encoder = connector->encoder;
6432
6433         return encoder->get_hw_state(encoder, &pipe);
6434 }
6435
6436 static int pipe_required_fdi_lanes(struct intel_crtc_state *crtc_state)
6437 {
6438         if (crtc_state->base.enable && crtc_state->has_pch_encoder)
6439                 return crtc_state->fdi_lanes;
6440
6441         return 0;
6442 }
6443
6444 static int ironlake_check_fdi_lanes(struct drm_device *dev, enum pipe pipe,
6445                                      struct intel_crtc_state *pipe_config)
6446 {
6447         struct drm_atomic_state *state = pipe_config->base.state;
6448         struct intel_crtc *other_crtc;
6449         struct intel_crtc_state *other_crtc_state;
6450
6451         DRM_DEBUG_KMS("checking fdi config on pipe %c, lanes %i\n",
6452                       pipe_name(pipe), pipe_config->fdi_lanes);
6453         if (pipe_config->fdi_lanes > 4) {
6454                 DRM_DEBUG_KMS("invalid fdi lane config on pipe %c: %i lanes\n",
6455                               pipe_name(pipe), pipe_config->fdi_lanes);
6456                 return -EINVAL;
6457         }
6458
6459         if (IS_HASWELL(dev) || IS_BROADWELL(dev)) {
6460                 if (pipe_config->fdi_lanes > 2) {
6461                         DRM_DEBUG_KMS("only 2 lanes on haswell, required: %i lanes\n",
6462                                       pipe_config->fdi_lanes);
6463                         return -EINVAL;
6464                 } else {
6465                         return 0;
6466                 }
6467         }
6468
6469         if (INTEL_INFO(dev)->num_pipes == 2)
6470                 return 0;
6471
6472         /* Ivybridge 3 pipe is really complicated */
6473         switch (pipe) {
6474         case PIPE_A:
6475                 return 0;
6476         case PIPE_B:
6477                 if (pipe_config->fdi_lanes <= 2)
6478                         return 0;
6479
6480                 other_crtc = to_intel_crtc(intel_get_crtc_for_pipe(dev, PIPE_C));
6481                 other_crtc_state =
6482                         intel_atomic_get_crtc_state(state, other_crtc);
6483                 if (IS_ERR(other_crtc_state))
6484                         return PTR_ERR(other_crtc_state);
6485
6486                 if (pipe_required_fdi_lanes(other_crtc_state) > 0) {
6487                         DRM_DEBUG_KMS("invalid shared fdi lane config on pipe %c: %i lanes\n",
6488                                       pipe_name(pipe), pipe_config->fdi_lanes);
6489                         return -EINVAL;
6490                 }
6491                 return 0;
6492         case PIPE_C:
6493                 if (pipe_config->fdi_lanes > 2) {
6494                         DRM_DEBUG_KMS("only 2 lanes on pipe %c: required %i lanes\n",
6495                                       pipe_name(pipe), pipe_config->fdi_lanes);
6496                         return -EINVAL;
6497                 }
6498
6499                 other_crtc = to_intel_crtc(intel_get_crtc_for_pipe(dev, PIPE_B));
6500                 other_crtc_state =
6501                         intel_atomic_get_crtc_state(state, other_crtc);
6502                 if (IS_ERR(other_crtc_state))
6503                         return PTR_ERR(other_crtc_state);
6504
6505                 if (pipe_required_fdi_lanes(other_crtc_state) > 2) {
6506                         DRM_DEBUG_KMS("fdi link B uses too many lanes to enable link C\n");
6507                         return -EINVAL;
6508                 }
6509                 return 0;
6510         default:
6511                 BUG();
6512         }
6513 }
6514
6515 #define RETRY 1
6516 static int ironlake_fdi_compute_config(struct intel_crtc *intel_crtc,
6517                                        struct intel_crtc_state *pipe_config)
6518 {
6519         struct drm_device *dev = intel_crtc->base.dev;
6520         const struct drm_display_mode *adjusted_mode = &pipe_config->base.adjusted_mode;
6521         int lane, link_bw, fdi_dotclock, ret;
6522         bool needs_recompute = false;
6523
6524 retry:
6525         /* FDI is a binary signal running at ~2.7GHz, encoding
6526          * each output octet as 10 bits. The actual frequency
6527          * is stored as a divider into a 100MHz clock, and the
6528          * mode pixel clock is stored in units of 1KHz.
6529          * Hence the bw of each lane in terms of the mode signal
6530          * is:
6531          */
6532         link_bw = intel_fdi_link_freq(to_i915(dev), pipe_config);
6533
6534         fdi_dotclock = adjusted_mode->crtc_clock;
6535
6536         lane = ironlake_get_lanes_required(fdi_dotclock, link_bw,
6537                                            pipe_config->pipe_bpp);
6538
6539         pipe_config->fdi_lanes = lane;
6540
6541         intel_link_compute_m_n(pipe_config->pipe_bpp, lane, fdi_dotclock,
6542                                link_bw, &pipe_config->fdi_m_n);
6543
6544         ret = ironlake_check_fdi_lanes(dev, intel_crtc->pipe, pipe_config);
6545         if (ret == -EINVAL && pipe_config->pipe_bpp > 6*3) {
6546                 pipe_config->pipe_bpp -= 2*3;
6547                 DRM_DEBUG_KMS("fdi link bw constraint, reducing pipe bpp to %i\n",
6548                               pipe_config->pipe_bpp);
6549                 needs_recompute = true;
6550                 pipe_config->bw_constrained = true;
6551
6552                 goto retry;
6553         }
6554
6555         if (needs_recompute)
6556                 return RETRY;
6557
6558         return ret;
6559 }
6560
6561 static bool pipe_config_supports_ips(struct drm_i915_private *dev_priv,
6562                                      struct intel_crtc_state *pipe_config)
6563 {
6564         if (pipe_config->pipe_bpp > 24)
6565                 return false;
6566
6567         /* HSW can handle pixel rate up to cdclk? */
6568         if (IS_HASWELL(dev_priv->dev))
6569                 return true;
6570
6571         /*
6572          * We compare against max which means we must take
6573          * the increased cdclk requirement into account when
6574          * calculating the new cdclk.
6575          *
6576          * Should measure whether using a lower cdclk w/o IPS
6577          */
6578         return ilk_pipe_pixel_rate(pipe_config) <=
6579                 dev_priv->max_cdclk_freq * 95 / 100;
6580 }
6581
6582 static void hsw_compute_ips_config(struct intel_crtc *crtc,
6583                                    struct intel_crtc_state *pipe_config)
6584 {
6585         struct drm_device *dev = crtc->base.dev;
6586         struct drm_i915_private *dev_priv = dev->dev_private;
6587
6588         pipe_config->ips_enabled = i915.enable_ips &&
6589                 hsw_crtc_supports_ips(crtc) &&
6590                 pipe_config_supports_ips(dev_priv, pipe_config);
6591 }
6592
6593 static bool intel_crtc_supports_double_wide(const struct intel_crtc *crtc)
6594 {
6595         const struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
6596
6597         /* GDG double wide on either pipe, otherwise pipe A only */
6598         return INTEL_INFO(dev_priv)->gen < 4 &&
6599                 (crtc->pipe == PIPE_A || IS_I915G(dev_priv));
6600 }
6601
6602 static int intel_crtc_compute_config(struct intel_crtc *crtc,
6603                                      struct intel_crtc_state *pipe_config)
6604 {
6605         struct drm_device *dev = crtc->base.dev;
6606         struct drm_i915_private *dev_priv = dev->dev_private;
6607         const struct drm_display_mode *adjusted_mode = &pipe_config->base.adjusted_mode;
6608
6609         /* FIXME should check pixel clock limits on all platforms */
6610         if (INTEL_INFO(dev)->gen < 4) {
6611                 int clock_limit = dev_priv->max_cdclk_freq * 9 / 10;
6612
6613                 /*
6614                  * Enable double wide mode when the dot clock
6615                  * is > 90% of the (display) core speed.
6616                  */
6617                 if (intel_crtc_supports_double_wide(crtc) &&
6618                     adjusted_mode->crtc_clock > clock_limit) {
6619                         clock_limit *= 2;
6620                         pipe_config->double_wide = true;
6621                 }
6622
6623                 if (adjusted_mode->crtc_clock > clock_limit) {
6624                         DRM_DEBUG_KMS("requested pixel clock (%d kHz) too high (max: %d kHz, double wide: %s)\n",
6625                                       adjusted_mode->crtc_clock, clock_limit,
6626                                       yesno(pipe_config->double_wide));
6627                         return -EINVAL;
6628                 }
6629         }
6630
6631         /*
6632          * Pipe horizontal size must be even in:
6633          * - DVO ganged mode
6634          * - LVDS dual channel mode
6635          * - Double wide pipe
6636          */
6637         if ((intel_pipe_will_have_type(pipe_config, INTEL_OUTPUT_LVDS) &&
6638              intel_is_dual_link_lvds(dev)) || pipe_config->double_wide)
6639                 pipe_config->pipe_src_w &= ~1;
6640
6641         /* Cantiga+ cannot handle modes with a hsync front porch of 0.
6642          * WaPruneModeWithIncorrectHsyncOffset:ctg,elk,ilk,snb,ivb,vlv,hsw.
6643          */
6644         if ((INTEL_INFO(dev)->gen > 4 || IS_G4X(dev)) &&
6645                 adjusted_mode->crtc_hsync_start == adjusted_mode->crtc_hdisplay)
6646                 return -EINVAL;
6647
6648         if (HAS_IPS(dev))
6649                 hsw_compute_ips_config(crtc, pipe_config);
6650
6651         if (pipe_config->has_pch_encoder)
6652                 return ironlake_fdi_compute_config(crtc, pipe_config);
6653
6654         return 0;
6655 }
6656
6657 static int skylake_get_display_clock_speed(struct drm_device *dev)
6658 {
6659         struct drm_i915_private *dev_priv = to_i915(dev);
6660         uint32_t lcpll1 = I915_READ(LCPLL1_CTL);
6661         uint32_t cdctl = I915_READ(CDCLK_CTL);
6662         uint32_t linkrate;
6663
6664         if (!(lcpll1 & LCPLL_PLL_ENABLE))
6665                 return 24000; /* 24MHz is the cd freq with NSSC ref */
6666
6667         if ((cdctl & CDCLK_FREQ_SEL_MASK) == CDCLK_FREQ_540)
6668                 return 540000;
6669
6670         linkrate = (I915_READ(DPLL_CTRL1) &
6671                     DPLL_CTRL1_LINK_RATE_MASK(SKL_DPLL0)) >> 1;
6672
6673         if (linkrate == DPLL_CTRL1_LINK_RATE_2160 ||
6674             linkrate == DPLL_CTRL1_LINK_RATE_1080) {
6675                 /* vco 8640 */
6676                 switch (cdctl & CDCLK_FREQ_SEL_MASK) {
6677                 case CDCLK_FREQ_450_432:
6678                         return 432000;
6679                 case CDCLK_FREQ_337_308:
6680                         return 308570;
6681                 case CDCLK_FREQ_675_617:
6682                         return 617140;
6683                 default:
6684                         WARN(1, "Unknown cd freq selection\n");
6685                 }
6686         } else {
6687                 /* vco 8100 */
6688                 switch (cdctl & CDCLK_FREQ_SEL_MASK) {
6689                 case CDCLK_FREQ_450_432:
6690                         return 450000;
6691                 case CDCLK_FREQ_337_308:
6692                         return 337500;
6693                 case CDCLK_FREQ_675_617:
6694                         return 675000;
6695                 default:
6696                         WARN(1, "Unknown cd freq selection\n");
6697                 }
6698         }
6699
6700         /* error case, do as if DPLL0 isn't enabled */
6701         return 24000;
6702 }
6703
6704 static int broxton_get_display_clock_speed(struct drm_device *dev)
6705 {
6706         struct drm_i915_private *dev_priv = to_i915(dev);
6707         uint32_t cdctl = I915_READ(CDCLK_CTL);
6708         uint32_t pll_ratio = I915_READ(BXT_DE_PLL_CTL) & BXT_DE_PLL_RATIO_MASK;
6709         uint32_t pll_enab = I915_READ(BXT_DE_PLL_ENABLE);
6710         int cdclk;
6711
6712         if (!(pll_enab & BXT_DE_PLL_PLL_ENABLE))
6713                 return 19200;
6714
6715         cdclk = 19200 * pll_ratio / 2;
6716
6717         switch (cdctl & BXT_CDCLK_CD2X_DIV_SEL_MASK) {
6718         case BXT_CDCLK_CD2X_DIV_SEL_1:
6719                 return cdclk;  /* 576MHz or 624MHz */
6720         case BXT_CDCLK_CD2X_DIV_SEL_1_5:
6721                 return cdclk * 2 / 3; /* 384MHz */
6722         case BXT_CDCLK_CD2X_DIV_SEL_2:
6723                 return cdclk / 2; /* 288MHz */
6724         case BXT_CDCLK_CD2X_DIV_SEL_4:
6725                 return cdclk / 4; /* 144MHz */
6726         }
6727
6728         /* error case, do as if DE PLL isn't enabled */
6729         return 19200;
6730 }
6731
6732 static int broadwell_get_display_clock_speed(struct drm_device *dev)
6733 {
6734         struct drm_i915_private *dev_priv = dev->dev_private;
6735         uint32_t lcpll = I915_READ(LCPLL_CTL);
6736         uint32_t freq = lcpll & LCPLL_CLK_FREQ_MASK;
6737
6738         if (lcpll & LCPLL_CD_SOURCE_FCLK)
6739                 return 800000;
6740         else if (I915_READ(FUSE_STRAP) & HSW_CDCLK_LIMIT)
6741                 return 450000;
6742         else if (freq == LCPLL_CLK_FREQ_450)
6743                 return 450000;
6744         else if (freq == LCPLL_CLK_FREQ_54O_BDW)
6745                 return 540000;
6746         else if (freq == LCPLL_CLK_FREQ_337_5_BDW)
6747                 return 337500;
6748         else
6749                 return 675000;
6750 }
6751
6752 static int haswell_get_display_clock_speed(struct drm_device *dev)
6753 {
6754         struct drm_i915_private *dev_priv = dev->dev_private;
6755         uint32_t lcpll = I915_READ(LCPLL_CTL);
6756         uint32_t freq = lcpll & LCPLL_CLK_FREQ_MASK;
6757
6758         if (lcpll & LCPLL_CD_SOURCE_FCLK)
6759                 return 800000;
6760         else if (I915_READ(FUSE_STRAP) & HSW_CDCLK_LIMIT)
6761                 return 450000;
6762         else if (freq == LCPLL_CLK_FREQ_450)
6763                 return 450000;
6764         else if (IS_HSW_ULT(dev))
6765                 return 337500;
6766         else
6767                 return 540000;
6768 }
6769
6770 static int valleyview_get_display_clock_speed(struct drm_device *dev)
6771 {
6772         return vlv_get_cck_clock_hpll(to_i915(dev), "cdclk",
6773                                       CCK_DISPLAY_CLOCK_CONTROL);
6774 }
6775
6776 static int ilk_get_display_clock_speed(struct drm_device *dev)
6777 {
6778         return 450000;
6779 }
6780
6781 static int i945_get_display_clock_speed(struct drm_device *dev)
6782 {
6783         return 400000;
6784 }
6785
6786 static int i915_get_display_clock_speed(struct drm_device *dev)
6787 {
6788         return 333333;
6789 }
6790
6791 static int i9xx_misc_get_display_clock_speed(struct drm_device *dev)
6792 {
6793         return 200000;
6794 }
6795
6796 static int pnv_get_display_clock_speed(struct drm_device *dev)
6797 {
6798         u16 gcfgc = 0;
6799
6800         pci_read_config_word(dev->pdev, GCFGC, &gcfgc);
6801
6802         switch (gcfgc & GC_DISPLAY_CLOCK_MASK) {
6803         case GC_DISPLAY_CLOCK_267_MHZ_PNV:
6804                 return 266667;
6805         case GC_DISPLAY_CLOCK_333_MHZ_PNV:
6806                 return 333333;
6807         case GC_DISPLAY_CLOCK_444_MHZ_PNV:
6808                 return 444444;
6809         case GC_DISPLAY_CLOCK_200_MHZ_PNV:
6810                 return 200000;
6811         default:
6812                 DRM_ERROR("Unknown pnv display core clock 0x%04x\n", gcfgc);
6813         case GC_DISPLAY_CLOCK_133_MHZ_PNV:
6814                 return 133333;
6815         case GC_DISPLAY_CLOCK_167_MHZ_PNV:
6816                 return 166667;
6817         }
6818 }
6819
6820 static int i915gm_get_display_clock_speed(struct drm_device *dev)
6821 {
6822         u16 gcfgc = 0;
6823
6824         pci_read_config_word(dev->pdev, GCFGC, &gcfgc);
6825
6826         if (gcfgc & GC_LOW_FREQUENCY_ENABLE)
6827                 return 133333;
6828         else {
6829                 switch (gcfgc & GC_DISPLAY_CLOCK_MASK) {
6830                 case GC_DISPLAY_CLOCK_333_MHZ:
6831                         return 333333;
6832                 default:
6833                 case GC_DISPLAY_CLOCK_190_200_MHZ:
6834                         return 190000;
6835                 }
6836         }
6837 }
6838
6839 static int i865_get_display_clock_speed(struct drm_device *dev)
6840 {
6841         return 266667;
6842 }
6843
6844 static int i85x_get_display_clock_speed(struct drm_device *dev)
6845 {
6846         u16 hpllcc = 0;
6847
6848         /*
6849          * 852GM/852GMV only supports 133 MHz and the HPLLCC
6850          * encoding is different :(
6851          * FIXME is this the right way to detect 852GM/852GMV?
6852          */
6853         if (dev->pdev->revision == 0x1)
6854                 return 133333;
6855
6856         pci_bus_read_config_word(dev->pdev->bus,
6857                                  PCI_DEVFN(0, 3), HPLLCC, &hpllcc);
6858
6859         /* Assume that the hardware is in the high speed state.  This
6860          * should be the default.
6861          */
6862         switch (hpllcc & GC_CLOCK_CONTROL_MASK) {
6863         case GC_CLOCK_133_200:
6864         case GC_CLOCK_133_200_2:
6865         case GC_CLOCK_100_200:
6866                 return 200000;
6867         case GC_CLOCK_166_250:
6868                 return 250000;
6869         case GC_CLOCK_100_133:
6870                 return 133333;
6871         case GC_CLOCK_133_266:
6872         case GC_CLOCK_133_266_2:
6873         case GC_CLOCK_166_266:
6874                 return 266667;
6875         }
6876
6877         /* Shouldn't happen */
6878         return 0;
6879 }
6880
6881 static int i830_get_display_clock_speed(struct drm_device *dev)
6882 {
6883         return 133333;
6884 }
6885
6886 static unsigned int intel_hpll_vco(struct drm_device *dev)
6887 {
6888         struct drm_i915_private *dev_priv = dev->dev_private;
6889         static const unsigned int blb_vco[8] = {
6890                 [0] = 3200000,
6891                 [1] = 4000000,
6892                 [2] = 5333333,
6893                 [3] = 4800000,
6894                 [4] = 6400000,
6895         };
6896         static const unsigned int pnv_vco[8] = {
6897                 [0] = 3200000,
6898                 [1] = 4000000,
6899                 [2] = 5333333,
6900                 [3] = 4800000,
6901                 [4] = 2666667,
6902         };
6903         static const unsigned int cl_vco[8] = {
6904                 [0] = 3200000,
6905                 [1] = 4000000,
6906                 [2] = 5333333,
6907                 [3] = 6400000,
6908                 [4] = 3333333,
6909                 [5] = 3566667,
6910                 [6] = 4266667,
6911         };
6912         static const unsigned int elk_vco[8] = {
6913                 [0] = 3200000,
6914                 [1] = 4000000,
6915                 [2] = 5333333,
6916                 [3] = 4800000,
6917         };
6918         static const unsigned int ctg_vco[8] = {
6919                 [0] = 3200000,
6920                 [1] = 4000000,
6921                 [2] = 5333333,
6922                 [3] = 6400000,
6923                 [4] = 2666667,
6924                 [5] = 4266667,
6925         };
6926         const unsigned int *vco_table;
6927         unsigned int vco;
6928         uint8_t tmp = 0;
6929
6930         /* FIXME other chipsets? */
6931         if (IS_GM45(dev))
6932                 vco_table = ctg_vco;
6933         else if (IS_G4X(dev))
6934                 vco_table = elk_vco;
6935         else if (IS_CRESTLINE(dev))
6936                 vco_table = cl_vco;
6937         else if (IS_PINEVIEW(dev))
6938                 vco_table = pnv_vco;
6939         else if (IS_G33(dev))
6940                 vco_table = blb_vco;
6941         else
6942                 return 0;
6943
6944         tmp = I915_READ(IS_MOBILE(dev) ? HPLLVCO_MOBILE : HPLLVCO);
6945
6946         vco = vco_table[tmp & 0x7];
6947         if (vco == 0)
6948                 DRM_ERROR("Bad HPLL VCO (HPLLVCO=0x%02x)\n", tmp);
6949         else
6950                 DRM_DEBUG_KMS("HPLL VCO %u kHz\n", vco);
6951
6952         return vco;
6953 }
6954
6955 static int gm45_get_display_clock_speed(struct drm_device *dev)
6956 {
6957         unsigned int cdclk_sel, vco = intel_hpll_vco(dev);
6958         uint16_t tmp = 0;
6959
6960         pci_read_config_word(dev->pdev, GCFGC, &tmp);
6961
6962         cdclk_sel = (tmp >> 12) & 0x1;
6963
6964         switch (vco) {
6965         case 2666667:
6966         case 4000000:
6967         case 5333333:
6968                 return cdclk_sel ? 333333 : 222222;
6969         case 3200000:
6970                 return cdclk_sel ? 320000 : 228571;
6971         default:
6972                 DRM_ERROR("Unable to determine CDCLK. HPLL VCO=%u, CFGC=0x%04x\n", vco, tmp);
6973                 return 222222;
6974         }
6975 }
6976
6977 static int i965gm_get_display_clock_speed(struct drm_device *dev)
6978 {
6979         static const uint8_t div_3200[] = { 16, 10,  8 };
6980         static const uint8_t div_4000[] = { 20, 12, 10 };
6981         static const uint8_t div_5333[] = { 24, 16, 14 };
6982         const uint8_t *div_table;
6983         unsigned int cdclk_sel, vco = intel_hpll_vco(dev);
6984         uint16_t tmp = 0;
6985
6986         pci_read_config_word(dev->pdev, GCFGC, &tmp);
6987
6988         cdclk_sel = ((tmp >> 8) & 0x1f) - 1;
6989
6990         if (cdclk_sel >= ARRAY_SIZE(div_3200))
6991                 goto fail;
6992
6993         switch (vco) {
6994         case 3200000:
6995                 div_table = div_3200;
6996                 break;
6997         case 4000000:
6998                 div_table = div_4000;
6999                 break;
7000         case 5333333:
7001                 div_table = div_5333;
7002                 break;
7003         default:
7004                 goto fail;
7005         }
7006
7007         return DIV_ROUND_CLOSEST(vco, div_table[cdclk_sel]);
7008
7009 fail:
7010         DRM_ERROR("Unable to determine CDCLK. HPLL VCO=%u kHz, CFGC=0x%04x\n", vco, tmp);
7011         return 200000;
7012 }
7013
7014 static int g33_get_display_clock_speed(struct drm_device *dev)
7015 {
7016         static const uint8_t div_3200[] = { 12, 10,  8,  7, 5, 16 };
7017         static const uint8_t div_4000[] = { 14, 12, 10,  8, 6, 20 };
7018         static const uint8_t div_4800[] = { 20, 14, 12, 10, 8, 24 };
7019         static const uint8_t div_5333[] = { 20, 16, 12, 12, 8, 28 };
7020         const uint8_t *div_table;
7021         unsigned int cdclk_sel, vco = intel_hpll_vco(dev);
7022         uint16_t tmp = 0;
7023
7024         pci_read_config_word(dev->pdev, GCFGC, &tmp);
7025
7026         cdclk_sel = (tmp >> 4) & 0x7;
7027
7028         if (cdclk_sel >= ARRAY_SIZE(div_3200))
7029                 goto fail;
7030
7031         switch (vco) {
7032         case 3200000:
7033                 div_table = div_3200;
7034                 break;
7035         case 4000000:
7036                 div_table = div_4000;
7037                 break;
7038         case 4800000:
7039                 div_table = div_4800;
7040                 break;
7041         case 5333333:
7042                 div_table = div_5333;
7043                 break;
7044         default:
7045                 goto fail;
7046         }
7047
7048         return DIV_ROUND_CLOSEST(vco, div_table[cdclk_sel]);
7049
7050 fail:
7051         DRM_ERROR("Unable to determine CDCLK. HPLL VCO=%u kHz, CFGC=0x%08x\n", vco, tmp);
7052         return 190476;
7053 }
7054
7055 static void
7056 intel_reduce_m_n_ratio(uint32_t *num, uint32_t *den)
7057 {
7058         while (*num > DATA_LINK_M_N_MASK ||
7059                *den > DATA_LINK_M_N_MASK) {
7060                 *num >>= 1;
7061                 *den >>= 1;
7062         }
7063 }
7064
7065 static void compute_m_n(unsigned int m, unsigned int n,
7066                         uint32_t *ret_m, uint32_t *ret_n)
7067 {
7068         *ret_n = min_t(unsigned int, roundup_pow_of_two(n), DATA_LINK_N_MAX);
7069         *ret_m = div_u64((uint64_t) m * *ret_n, n);
7070         intel_reduce_m_n_ratio(ret_m, ret_n);
7071 }
7072
7073 void
7074 intel_link_compute_m_n(int bits_per_pixel, int nlanes,
7075                        int pixel_clock, int link_clock,
7076                        struct intel_link_m_n *m_n)
7077 {
7078         m_n->tu = 64;
7079
7080         compute_m_n(bits_per_pixel * pixel_clock,
7081                     link_clock * nlanes * 8,
7082                     &m_n->gmch_m, &m_n->gmch_n);
7083
7084         compute_m_n(pixel_clock, link_clock,
7085                     &m_n->link_m, &m_n->link_n);
7086 }
7087
7088 static inline bool intel_panel_use_ssc(struct drm_i915_private *dev_priv)
7089 {
7090         if (i915.panel_use_ssc >= 0)
7091                 return i915.panel_use_ssc != 0;
7092         return dev_priv->vbt.lvds_use_ssc
7093                 && !(dev_priv->quirks & QUIRK_LVDS_SSC_DISABLE);
7094 }
7095
7096 static int i9xx_get_refclk(const struct intel_crtc_state *crtc_state,
7097                            int num_connectors)
7098 {
7099         struct drm_device *dev = crtc_state->base.crtc->dev;
7100         struct drm_i915_private *dev_priv = dev->dev_private;
7101         int refclk;
7102
7103         WARN_ON(!crtc_state->base.state);
7104
7105         if (IS_VALLEYVIEW(dev) || IS_CHERRYVIEW(dev) || IS_BROXTON(dev)) {
7106                 refclk = 100000;
7107         } else if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_LVDS) &&
7108             intel_panel_use_ssc(dev_priv) && num_connectors < 2) {
7109                 refclk = dev_priv->vbt.lvds_ssc_freq;
7110                 DRM_DEBUG_KMS("using SSC reference clock of %d kHz\n", refclk);
7111         } else if (!IS_GEN2(dev)) {
7112                 refclk = 96000;
7113         } else {
7114                 refclk = 48000;
7115         }
7116
7117         return refclk;
7118 }
7119
7120 static uint32_t pnv_dpll_compute_fp(struct dpll *dpll)
7121 {
7122         return (1 << dpll->n) << 16 | dpll->m2;
7123 }
7124
7125 static uint32_t i9xx_dpll_compute_fp(struct dpll *dpll)
7126 {
7127         return dpll->n << 16 | dpll->m1 << 8 | dpll->m2;
7128 }
7129
7130 static void i9xx_update_pll_dividers(struct intel_crtc *crtc,
7131                                      struct intel_crtc_state *crtc_state,
7132                                      intel_clock_t *reduced_clock)
7133 {
7134         struct drm_device *dev = crtc->base.dev;
7135         u32 fp, fp2 = 0;
7136
7137         if (IS_PINEVIEW(dev)) {
7138                 fp = pnv_dpll_compute_fp(&crtc_state->dpll);
7139                 if (reduced_clock)
7140                         fp2 = pnv_dpll_compute_fp(reduced_clock);
7141         } else {
7142                 fp = i9xx_dpll_compute_fp(&crtc_state->dpll);
7143                 if (reduced_clock)
7144                         fp2 = i9xx_dpll_compute_fp(reduced_clock);
7145         }
7146
7147         crtc_state->dpll_hw_state.fp0 = fp;
7148
7149         crtc->lowfreq_avail = false;
7150         if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_LVDS) &&
7151             reduced_clock) {
7152                 crtc_state->dpll_hw_state.fp1 = fp2;
7153                 crtc->lowfreq_avail = true;
7154         } else {
7155                 crtc_state->dpll_hw_state.fp1 = fp;
7156         }
7157 }
7158
7159 static void vlv_pllb_recal_opamp(struct drm_i915_private *dev_priv, enum pipe
7160                 pipe)
7161 {
7162         u32 reg_val;
7163
7164         /*
7165          * PLLB opamp always calibrates to max value of 0x3f, force enable it
7166          * and set it to a reasonable value instead.
7167          */
7168         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW9(1));
7169         reg_val &= 0xffffff00;
7170         reg_val |= 0x00000030;
7171         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW9(1), reg_val);
7172
7173         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_REF_DW13);
7174         reg_val &= 0x8cffffff;
7175         reg_val = 0x8c000000;
7176         vlv_dpio_write(dev_priv, pipe, VLV_REF_DW13, reg_val);
7177
7178         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW9(1));
7179         reg_val &= 0xffffff00;
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 &= 0x00ffffff;
7184         reg_val |= 0xb0000000;
7185         vlv_dpio_write(dev_priv, pipe, VLV_REF_DW13, reg_val);
7186 }
7187
7188 static void intel_pch_transcoder_set_m_n(struct intel_crtc *crtc,
7189                                          struct intel_link_m_n *m_n)
7190 {
7191         struct drm_device *dev = crtc->base.dev;
7192         struct drm_i915_private *dev_priv = dev->dev_private;
7193         int pipe = crtc->pipe;
7194
7195         I915_WRITE(PCH_TRANS_DATA_M1(pipe), TU_SIZE(m_n->tu) | m_n->gmch_m);
7196         I915_WRITE(PCH_TRANS_DATA_N1(pipe), m_n->gmch_n);
7197         I915_WRITE(PCH_TRANS_LINK_M1(pipe), m_n->link_m);
7198         I915_WRITE(PCH_TRANS_LINK_N1(pipe), m_n->link_n);
7199 }
7200
7201 static void intel_cpu_transcoder_set_m_n(struct intel_crtc *crtc,
7202                                          struct intel_link_m_n *m_n,
7203                                          struct intel_link_m_n *m2_n2)
7204 {
7205         struct drm_device *dev = crtc->base.dev;
7206         struct drm_i915_private *dev_priv = dev->dev_private;
7207         int pipe = crtc->pipe;
7208         enum transcoder transcoder = crtc->config->cpu_transcoder;
7209
7210         if (INTEL_INFO(dev)->gen >= 5) {
7211                 I915_WRITE(PIPE_DATA_M1(transcoder), TU_SIZE(m_n->tu) | m_n->gmch_m);
7212                 I915_WRITE(PIPE_DATA_N1(transcoder), m_n->gmch_n);
7213                 I915_WRITE(PIPE_LINK_M1(transcoder), m_n->link_m);
7214                 I915_WRITE(PIPE_LINK_N1(transcoder), m_n->link_n);
7215                 /* M2_N2 registers to be set only for gen < 8 (M2_N2 available
7216                  * for gen < 8) and if DRRS is supported (to make sure the
7217                  * registers are not unnecessarily accessed).
7218                  */
7219                 if (m2_n2 && (IS_CHERRYVIEW(dev) || INTEL_INFO(dev)->gen < 8) &&
7220                         crtc->config->has_drrs) {
7221                         I915_WRITE(PIPE_DATA_M2(transcoder),
7222                                         TU_SIZE(m2_n2->tu) | m2_n2->gmch_m);
7223                         I915_WRITE(PIPE_DATA_N2(transcoder), m2_n2->gmch_n);
7224                         I915_WRITE(PIPE_LINK_M2(transcoder), m2_n2->link_m);
7225                         I915_WRITE(PIPE_LINK_N2(transcoder), m2_n2->link_n);
7226                 }
7227         } else {
7228                 I915_WRITE(PIPE_DATA_M_G4X(pipe), TU_SIZE(m_n->tu) | m_n->gmch_m);
7229                 I915_WRITE(PIPE_DATA_N_G4X(pipe), m_n->gmch_n);
7230                 I915_WRITE(PIPE_LINK_M_G4X(pipe), m_n->link_m);
7231                 I915_WRITE(PIPE_LINK_N_G4X(pipe), m_n->link_n);
7232         }
7233 }
7234
7235 void intel_dp_set_m_n(struct intel_crtc *crtc, enum link_m_n_set m_n)
7236 {
7237         struct intel_link_m_n *dp_m_n, *dp_m2_n2 = NULL;
7238
7239         if (m_n == M1_N1) {
7240                 dp_m_n = &crtc->config->dp_m_n;
7241                 dp_m2_n2 = &crtc->config->dp_m2_n2;
7242         } else if (m_n == M2_N2) {
7243
7244                 /*
7245                  * M2_N2 registers are not supported. Hence m2_n2 divider value
7246                  * needs to be programmed into M1_N1.
7247                  */
7248                 dp_m_n = &crtc->config->dp_m2_n2;
7249         } else {
7250                 DRM_ERROR("Unsupported divider value\n");
7251                 return;
7252         }
7253
7254         if (crtc->config->has_pch_encoder)
7255                 intel_pch_transcoder_set_m_n(crtc, &crtc->config->dp_m_n);
7256         else
7257                 intel_cpu_transcoder_set_m_n(crtc, dp_m_n, dp_m2_n2);
7258 }
7259
7260 static void vlv_compute_dpll(struct intel_crtc *crtc,
7261                              struct intel_crtc_state *pipe_config)
7262 {
7263         u32 dpll, dpll_md;
7264
7265         /*
7266          * Enable DPIO clock input. We should never disable the reference
7267          * clock for pipe B, since VGA hotplug / manual detection depends
7268          * on it.
7269          */
7270         dpll = DPLL_EXT_BUFFER_ENABLE_VLV | DPLL_REF_CLK_ENABLE_VLV |
7271                 DPLL_VGA_MODE_DIS | DPLL_INTEGRATED_REF_CLK_VLV;
7272         /* We should never disable this, set it here for state tracking */
7273         if (crtc->pipe == PIPE_B)
7274                 dpll |= DPLL_INTEGRATED_CRI_CLK_VLV;
7275         dpll |= DPLL_VCO_ENABLE;
7276         pipe_config->dpll_hw_state.dpll = dpll;
7277
7278         dpll_md = (pipe_config->pixel_multiplier - 1)
7279                 << DPLL_MD_UDI_MULTIPLIER_SHIFT;
7280         pipe_config->dpll_hw_state.dpll_md = dpll_md;
7281 }
7282
7283 static void vlv_prepare_pll(struct intel_crtc *crtc,
7284                             const struct intel_crtc_state *pipe_config)
7285 {
7286         struct drm_device *dev = crtc->base.dev;
7287         struct drm_i915_private *dev_priv = dev->dev_private;
7288         int pipe = crtc->pipe;
7289         u32 mdiv;
7290         u32 bestn, bestm1, bestm2, bestp1, bestp2;
7291         u32 coreclk, reg_val;
7292
7293         mutex_lock(&dev_priv->sb_lock);
7294
7295         bestn = pipe_config->dpll.n;
7296         bestm1 = pipe_config->dpll.m1;
7297         bestm2 = pipe_config->dpll.m2;
7298         bestp1 = pipe_config->dpll.p1;
7299         bestp2 = pipe_config->dpll.p2;
7300
7301         /* See eDP HDMI DPIO driver vbios notes doc */
7302
7303         /* PLL B needs special handling */
7304         if (pipe == PIPE_B)
7305                 vlv_pllb_recal_opamp(dev_priv, pipe);
7306
7307         /* Set up Tx target for periodic Rcomp update */
7308         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW9_BCAST, 0x0100000f);
7309
7310         /* Disable target IRef on PLL */
7311         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW8(pipe));
7312         reg_val &= 0x00ffffff;
7313         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW8(pipe), reg_val);
7314
7315         /* Disable fast lock */
7316         vlv_dpio_write(dev_priv, pipe, VLV_CMN_DW0, 0x610);
7317
7318         /* Set idtafcrecal before PLL is enabled */
7319         mdiv = ((bestm1 << DPIO_M1DIV_SHIFT) | (bestm2 & DPIO_M2DIV_MASK));
7320         mdiv |= ((bestp1 << DPIO_P1_SHIFT) | (bestp2 << DPIO_P2_SHIFT));
7321         mdiv |= ((bestn << DPIO_N_SHIFT));
7322         mdiv |= (1 << DPIO_K_SHIFT);
7323
7324         /*
7325          * Post divider depends on pixel clock rate, DAC vs digital (and LVDS,
7326          * but we don't support that).
7327          * Note: don't use the DAC post divider as it seems unstable.
7328          */
7329         mdiv |= (DPIO_POST_DIV_HDMIDP << DPIO_POST_DIV_SHIFT);
7330         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW3(pipe), mdiv);
7331
7332         mdiv |= DPIO_ENABLE_CALIBRATION;
7333         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW3(pipe), mdiv);
7334
7335         /* Set HBR and RBR LPF coefficients */
7336         if (pipe_config->port_clock == 162000 ||
7337             intel_pipe_has_type(crtc, INTEL_OUTPUT_ANALOG) ||
7338             intel_pipe_has_type(crtc, INTEL_OUTPUT_HDMI))
7339                 vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW10(pipe),
7340                                  0x009f0003);
7341         else
7342                 vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW10(pipe),
7343                                  0x00d0000f);
7344
7345         if (pipe_config->has_dp_encoder) {
7346                 /* Use SSC source */
7347                 if (pipe == PIPE_A)
7348                         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW5(pipe),
7349                                          0x0df40000);
7350                 else
7351                         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW5(pipe),
7352                                          0x0df70000);
7353         } else { /* HDMI or VGA */
7354                 /* Use bend source */
7355                 if (pipe == PIPE_A)
7356                         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW5(pipe),
7357                                          0x0df70000);
7358                 else
7359                         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW5(pipe),
7360                                          0x0df40000);
7361         }
7362
7363         coreclk = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW7(pipe));
7364         coreclk = (coreclk & 0x0000ff00) | 0x01c00000;
7365         if (intel_pipe_has_type(crtc, INTEL_OUTPUT_DISPLAYPORT) ||
7366             intel_pipe_has_type(crtc, INTEL_OUTPUT_EDP))
7367                 coreclk |= 0x01000000;
7368         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW7(pipe), coreclk);
7369
7370         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW11(pipe), 0x87871000);
7371         mutex_unlock(&dev_priv->sb_lock);
7372 }
7373
7374 static void chv_compute_dpll(struct intel_crtc *crtc,
7375                              struct intel_crtc_state *pipe_config)
7376 {
7377         pipe_config->dpll_hw_state.dpll = DPLL_SSC_REF_CLK_CHV |
7378                 DPLL_REF_CLK_ENABLE_VLV | DPLL_VGA_MODE_DIS |
7379                 DPLL_VCO_ENABLE;
7380         if (crtc->pipe != PIPE_A)
7381                 pipe_config->dpll_hw_state.dpll |= DPLL_INTEGRATED_CRI_CLK_VLV;
7382
7383         pipe_config->dpll_hw_state.dpll_md =
7384                 (pipe_config->pixel_multiplier - 1) << DPLL_MD_UDI_MULTIPLIER_SHIFT;
7385 }
7386
7387 static void chv_prepare_pll(struct intel_crtc *crtc,
7388                             const struct intel_crtc_state *pipe_config)
7389 {
7390         struct drm_device *dev = crtc->base.dev;
7391         struct drm_i915_private *dev_priv = dev->dev_private;
7392         int pipe = crtc->pipe;
7393         i915_reg_t dpll_reg = DPLL(crtc->pipe);
7394         enum dpio_channel port = vlv_pipe_to_channel(pipe);
7395         u32 loopfilter, tribuf_calcntr;
7396         u32 bestn, bestm1, bestm2, bestp1, bestp2, bestm2_frac;
7397         u32 dpio_val;
7398         int vco;
7399
7400         bestn = pipe_config->dpll.n;
7401         bestm2_frac = pipe_config->dpll.m2 & 0x3fffff;
7402         bestm1 = pipe_config->dpll.m1;
7403         bestm2 = pipe_config->dpll.m2 >> 22;
7404         bestp1 = pipe_config->dpll.p1;
7405         bestp2 = pipe_config->dpll.p2;
7406         vco = pipe_config->dpll.vco;
7407         dpio_val = 0;
7408         loopfilter = 0;
7409
7410         /*
7411          * Enable Refclk and SSC
7412          */
7413         I915_WRITE(dpll_reg,
7414                    pipe_config->dpll_hw_state.dpll & ~DPLL_VCO_ENABLE);
7415
7416         mutex_lock(&dev_priv->sb_lock);
7417
7418         /* p1 and p2 divider */
7419         vlv_dpio_write(dev_priv, pipe, CHV_CMN_DW13(port),
7420                         5 << DPIO_CHV_S1_DIV_SHIFT |
7421                         bestp1 << DPIO_CHV_P1_DIV_SHIFT |
7422                         bestp2 << DPIO_CHV_P2_DIV_SHIFT |
7423                         1 << DPIO_CHV_K_DIV_SHIFT);
7424
7425         /* Feedback post-divider - m2 */
7426         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW0(port), bestm2);
7427
7428         /* Feedback refclk divider - n and m1 */
7429         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW1(port),
7430                         DPIO_CHV_M1_DIV_BY_2 |
7431                         1 << DPIO_CHV_N_DIV_SHIFT);
7432
7433         /* M2 fraction division */
7434         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW2(port), bestm2_frac);
7435
7436         /* M2 fraction division enable */
7437         dpio_val = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW3(port));
7438         dpio_val &= ~(DPIO_CHV_FEEDFWD_GAIN_MASK | DPIO_CHV_FRAC_DIV_EN);
7439         dpio_val |= (2 << DPIO_CHV_FEEDFWD_GAIN_SHIFT);
7440         if (bestm2_frac)
7441                 dpio_val |= DPIO_CHV_FRAC_DIV_EN;
7442         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW3(port), dpio_val);
7443
7444         /* Program digital lock detect threshold */
7445         dpio_val = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW9(port));
7446         dpio_val &= ~(DPIO_CHV_INT_LOCK_THRESHOLD_MASK |
7447                                         DPIO_CHV_INT_LOCK_THRESHOLD_SEL_COARSE);
7448         dpio_val |= (0x5 << DPIO_CHV_INT_LOCK_THRESHOLD_SHIFT);
7449         if (!bestm2_frac)
7450                 dpio_val |= DPIO_CHV_INT_LOCK_THRESHOLD_SEL_COARSE;
7451         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW9(port), dpio_val);
7452
7453         /* Loop filter */
7454         if (vco == 5400000) {
7455                 loopfilter |= (0x3 << DPIO_CHV_PROP_COEFF_SHIFT);
7456                 loopfilter |= (0x8 << DPIO_CHV_INT_COEFF_SHIFT);
7457                 loopfilter |= (0x1 << DPIO_CHV_GAIN_CTRL_SHIFT);
7458                 tribuf_calcntr = 0x9;
7459         } else if (vco <= 6200000) {
7460                 loopfilter |= (0x5 << DPIO_CHV_PROP_COEFF_SHIFT);
7461                 loopfilter |= (0xB << DPIO_CHV_INT_COEFF_SHIFT);
7462                 loopfilter |= (0x3 << DPIO_CHV_GAIN_CTRL_SHIFT);
7463                 tribuf_calcntr = 0x9;
7464         } else if (vco <= 6480000) {
7465                 loopfilter |= (0x4 << DPIO_CHV_PROP_COEFF_SHIFT);
7466                 loopfilter |= (0x9 << DPIO_CHV_INT_COEFF_SHIFT);
7467                 loopfilter |= (0x3 << DPIO_CHV_GAIN_CTRL_SHIFT);
7468                 tribuf_calcntr = 0x8;
7469         } else {
7470                 /* Not supported. Apply the same limits as in the max case */
7471                 loopfilter |= (0x4 << DPIO_CHV_PROP_COEFF_SHIFT);
7472                 loopfilter |= (0x9 << DPIO_CHV_INT_COEFF_SHIFT);
7473                 loopfilter |= (0x3 << DPIO_CHV_GAIN_CTRL_SHIFT);
7474                 tribuf_calcntr = 0;
7475         }
7476         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW6(port), loopfilter);
7477
7478         dpio_val = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW8(port));
7479         dpio_val &= ~DPIO_CHV_TDC_TARGET_CNT_MASK;
7480         dpio_val |= (tribuf_calcntr << DPIO_CHV_TDC_TARGET_CNT_SHIFT);
7481         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW8(port), dpio_val);
7482
7483         /* AFC Recal */
7484         vlv_dpio_write(dev_priv, pipe, CHV_CMN_DW14(port),
7485                         vlv_dpio_read(dev_priv, pipe, CHV_CMN_DW14(port)) |
7486                         DPIO_AFC_RECAL);
7487
7488         mutex_unlock(&dev_priv->sb_lock);
7489 }
7490
7491 /**
7492  * vlv_force_pll_on - forcibly enable just the PLL
7493  * @dev_priv: i915 private structure
7494  * @pipe: pipe PLL to enable
7495  * @dpll: PLL configuration
7496  *
7497  * Enable the PLL for @pipe using the supplied @dpll config. To be used
7498  * in cases where we need the PLL enabled even when @pipe is not going to
7499  * be enabled.
7500  */
7501 int vlv_force_pll_on(struct drm_device *dev, enum pipe pipe,
7502                      const struct dpll *dpll)
7503 {
7504         struct intel_crtc *crtc =
7505                 to_intel_crtc(intel_get_crtc_for_pipe(dev, pipe));
7506         struct intel_crtc_state *pipe_config;
7507
7508         pipe_config = kzalloc(sizeof(*pipe_config), GFP_KERNEL);
7509         if (!pipe_config)
7510                 return -ENOMEM;
7511
7512         pipe_config->base.crtc = &crtc->base;
7513         pipe_config->pixel_multiplier = 1;
7514         pipe_config->dpll = *dpll;
7515
7516         if (IS_CHERRYVIEW(dev)) {
7517                 chv_compute_dpll(crtc, pipe_config);
7518                 chv_prepare_pll(crtc, pipe_config);
7519                 chv_enable_pll(crtc, pipe_config);
7520         } else {
7521                 vlv_compute_dpll(crtc, pipe_config);
7522                 vlv_prepare_pll(crtc, pipe_config);
7523                 vlv_enable_pll(crtc, pipe_config);
7524         }
7525
7526         kfree(pipe_config);
7527
7528         return 0;
7529 }
7530
7531 /**
7532  * vlv_force_pll_off - forcibly disable just the PLL
7533  * @dev_priv: i915 private structure
7534  * @pipe: pipe PLL to disable
7535  *
7536  * Disable the PLL for @pipe. To be used in cases where we need
7537  * the PLL enabled even when @pipe is not going to be enabled.
7538  */
7539 void vlv_force_pll_off(struct drm_device *dev, enum pipe pipe)
7540 {
7541         if (IS_CHERRYVIEW(dev))
7542                 chv_disable_pll(to_i915(dev), pipe);
7543         else
7544                 vlv_disable_pll(to_i915(dev), pipe);
7545 }
7546
7547 static void i9xx_compute_dpll(struct intel_crtc *crtc,
7548                               struct intel_crtc_state *crtc_state,
7549                               intel_clock_t *reduced_clock,
7550                               int num_connectors)
7551 {
7552         struct drm_device *dev = crtc->base.dev;
7553         struct drm_i915_private *dev_priv = dev->dev_private;
7554         u32 dpll;
7555         bool is_sdvo;
7556         struct dpll *clock = &crtc_state->dpll;
7557
7558         i9xx_update_pll_dividers(crtc, crtc_state, reduced_clock);
7559
7560         is_sdvo = intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_SDVO) ||
7561                 intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_HDMI);
7562
7563         dpll = DPLL_VGA_MODE_DIS;
7564
7565         if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_LVDS))
7566                 dpll |= DPLLB_MODE_LVDS;
7567         else
7568                 dpll |= DPLLB_MODE_DAC_SERIAL;
7569
7570         if (IS_I945G(dev) || IS_I945GM(dev) || IS_G33(dev)) {
7571                 dpll |= (crtc_state->pixel_multiplier - 1)
7572                         << SDVO_MULTIPLIER_SHIFT_HIRES;
7573         }
7574
7575         if (is_sdvo)
7576                 dpll |= DPLL_SDVO_HIGH_SPEED;
7577
7578         if (crtc_state->has_dp_encoder)
7579                 dpll |= DPLL_SDVO_HIGH_SPEED;
7580
7581         /* compute bitmask from p1 value */
7582         if (IS_PINEVIEW(dev))
7583                 dpll |= (1 << (clock->p1 - 1)) << DPLL_FPA01_P1_POST_DIV_SHIFT_PINEVIEW;
7584         else {
7585                 dpll |= (1 << (clock->p1 - 1)) << DPLL_FPA01_P1_POST_DIV_SHIFT;
7586                 if (IS_G4X(dev) && reduced_clock)
7587                         dpll |= (1 << (reduced_clock->p1 - 1)) << DPLL_FPA1_P1_POST_DIV_SHIFT;
7588         }
7589         switch (clock->p2) {
7590         case 5:
7591                 dpll |= DPLL_DAC_SERIAL_P2_CLOCK_DIV_5;
7592                 break;
7593         case 7:
7594                 dpll |= DPLLB_LVDS_P2_CLOCK_DIV_7;
7595                 break;
7596         case 10:
7597                 dpll |= DPLL_DAC_SERIAL_P2_CLOCK_DIV_10;
7598                 break;
7599         case 14:
7600                 dpll |= DPLLB_LVDS_P2_CLOCK_DIV_14;
7601                 break;
7602         }
7603         if (INTEL_INFO(dev)->gen >= 4)
7604                 dpll |= (6 << PLL_LOAD_PULSE_PHASE_SHIFT);
7605
7606         if (crtc_state->sdvo_tv_clock)
7607                 dpll |= PLL_REF_INPUT_TVCLKINBC;
7608         else if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_LVDS) &&
7609                  intel_panel_use_ssc(dev_priv) && num_connectors < 2)
7610                 dpll |= PLLB_REF_INPUT_SPREADSPECTRUMIN;
7611         else
7612                 dpll |= PLL_REF_INPUT_DREFCLK;
7613
7614         dpll |= DPLL_VCO_ENABLE;
7615         crtc_state->dpll_hw_state.dpll = dpll;
7616
7617         if (INTEL_INFO(dev)->gen >= 4) {
7618                 u32 dpll_md = (crtc_state->pixel_multiplier - 1)
7619                         << DPLL_MD_UDI_MULTIPLIER_SHIFT;
7620                 crtc_state->dpll_hw_state.dpll_md = dpll_md;
7621         }
7622 }
7623
7624 static void i8xx_compute_dpll(struct intel_crtc *crtc,
7625                               struct intel_crtc_state *crtc_state,
7626                               intel_clock_t *reduced_clock,
7627                               int num_connectors)
7628 {
7629         struct drm_device *dev = crtc->base.dev;
7630         struct drm_i915_private *dev_priv = dev->dev_private;
7631         u32 dpll;
7632         struct dpll *clock = &crtc_state->dpll;
7633
7634         i9xx_update_pll_dividers(crtc, crtc_state, reduced_clock);
7635
7636         dpll = DPLL_VGA_MODE_DIS;
7637
7638         if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_LVDS)) {
7639                 dpll |= (1 << (clock->p1 - 1)) << DPLL_FPA01_P1_POST_DIV_SHIFT;
7640         } else {
7641                 if (clock->p1 == 2)
7642                         dpll |= PLL_P1_DIVIDE_BY_TWO;
7643                 else
7644                         dpll |= (clock->p1 - 2) << DPLL_FPA01_P1_POST_DIV_SHIFT;
7645                 if (clock->p2 == 4)
7646                         dpll |= PLL_P2_DIVIDE_BY_4;
7647         }
7648
7649         if (!IS_I830(dev) && intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_DVO))
7650                 dpll |= DPLL_DVO_2X_MODE;
7651
7652         if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_LVDS) &&
7653                  intel_panel_use_ssc(dev_priv) && num_connectors < 2)
7654                 dpll |= PLLB_REF_INPUT_SPREADSPECTRUMIN;
7655         else
7656                 dpll |= PLL_REF_INPUT_DREFCLK;
7657
7658         dpll |= DPLL_VCO_ENABLE;
7659         crtc_state->dpll_hw_state.dpll = dpll;
7660 }
7661
7662 static void intel_set_pipe_timings(struct intel_crtc *intel_crtc)
7663 {
7664         struct drm_device *dev = intel_crtc->base.dev;
7665         struct drm_i915_private *dev_priv = dev->dev_private;
7666         enum pipe pipe = intel_crtc->pipe;
7667         enum transcoder cpu_transcoder = intel_crtc->config->cpu_transcoder;
7668         const struct drm_display_mode *adjusted_mode = &intel_crtc->config->base.adjusted_mode;
7669         uint32_t crtc_vtotal, crtc_vblank_end;
7670         int vsyncshift = 0;
7671
7672         /* We need to be careful not to changed the adjusted mode, for otherwise
7673          * the hw state checker will get angry at the mismatch. */
7674         crtc_vtotal = adjusted_mode->crtc_vtotal;
7675         crtc_vblank_end = adjusted_mode->crtc_vblank_end;
7676
7677         if (adjusted_mode->flags & DRM_MODE_FLAG_INTERLACE) {
7678                 /* the chip adds 2 halflines automatically */
7679                 crtc_vtotal -= 1;
7680                 crtc_vblank_end -= 1;
7681
7682                 if (intel_pipe_has_type(intel_crtc, INTEL_OUTPUT_SDVO))
7683                         vsyncshift = (adjusted_mode->crtc_htotal - 1) / 2;
7684                 else
7685                         vsyncshift = adjusted_mode->crtc_hsync_start -
7686                                 adjusted_mode->crtc_htotal / 2;
7687                 if (vsyncshift < 0)
7688                         vsyncshift += adjusted_mode->crtc_htotal;
7689         }
7690
7691         if (INTEL_INFO(dev)->gen > 3)
7692                 I915_WRITE(VSYNCSHIFT(cpu_transcoder), vsyncshift);
7693
7694         I915_WRITE(HTOTAL(cpu_transcoder),
7695                    (adjusted_mode->crtc_hdisplay - 1) |
7696                    ((adjusted_mode->crtc_htotal - 1) << 16));
7697         I915_WRITE(HBLANK(cpu_transcoder),
7698                    (adjusted_mode->crtc_hblank_start - 1) |
7699                    ((adjusted_mode->crtc_hblank_end - 1) << 16));
7700         I915_WRITE(HSYNC(cpu_transcoder),
7701                    (adjusted_mode->crtc_hsync_start - 1) |
7702                    ((adjusted_mode->crtc_hsync_end - 1) << 16));
7703
7704         I915_WRITE(VTOTAL(cpu_transcoder),
7705                    (adjusted_mode->crtc_vdisplay - 1) |
7706                    ((crtc_vtotal - 1) << 16));
7707         I915_WRITE(VBLANK(cpu_transcoder),
7708                    (adjusted_mode->crtc_vblank_start - 1) |
7709                    ((crtc_vblank_end - 1) << 16));
7710         I915_WRITE(VSYNC(cpu_transcoder),
7711                    (adjusted_mode->crtc_vsync_start - 1) |
7712                    ((adjusted_mode->crtc_vsync_end - 1) << 16));
7713
7714         /* Workaround: when the EDP input selection is B, the VTOTAL_B must be
7715          * programmed with the VTOTAL_EDP value. Same for VTOTAL_C. This is
7716          * documented on the DDI_FUNC_CTL register description, EDP Input Select
7717          * bits. */
7718         if (IS_HASWELL(dev) && cpu_transcoder == TRANSCODER_EDP &&
7719             (pipe == PIPE_B || pipe == PIPE_C))
7720                 I915_WRITE(VTOTAL(pipe), I915_READ(VTOTAL(cpu_transcoder)));
7721
7722         /* pipesrc controls the size that is scaled from, which should
7723          * always be the user's requested size.
7724          */
7725         I915_WRITE(PIPESRC(pipe),
7726                    ((intel_crtc->config->pipe_src_w - 1) << 16) |
7727                    (intel_crtc->config->pipe_src_h - 1));
7728 }
7729
7730 static void intel_get_pipe_timings(struct intel_crtc *crtc,
7731                                    struct intel_crtc_state *pipe_config)
7732 {
7733         struct drm_device *dev = crtc->base.dev;
7734         struct drm_i915_private *dev_priv = dev->dev_private;
7735         enum transcoder cpu_transcoder = pipe_config->cpu_transcoder;
7736         uint32_t tmp;
7737
7738         tmp = I915_READ(HTOTAL(cpu_transcoder));
7739         pipe_config->base.adjusted_mode.crtc_hdisplay = (tmp & 0xffff) + 1;
7740         pipe_config->base.adjusted_mode.crtc_htotal = ((tmp >> 16) & 0xffff) + 1;
7741         tmp = I915_READ(HBLANK(cpu_transcoder));
7742         pipe_config->base.adjusted_mode.crtc_hblank_start = (tmp & 0xffff) + 1;
7743         pipe_config->base.adjusted_mode.crtc_hblank_end = ((tmp >> 16) & 0xffff) + 1;
7744         tmp = I915_READ(HSYNC(cpu_transcoder));
7745         pipe_config->base.adjusted_mode.crtc_hsync_start = (tmp & 0xffff) + 1;
7746         pipe_config->base.adjusted_mode.crtc_hsync_end = ((tmp >> 16) & 0xffff) + 1;
7747
7748         tmp = I915_READ(VTOTAL(cpu_transcoder));
7749         pipe_config->base.adjusted_mode.crtc_vdisplay = (tmp & 0xffff) + 1;
7750         pipe_config->base.adjusted_mode.crtc_vtotal = ((tmp >> 16) & 0xffff) + 1;
7751         tmp = I915_READ(VBLANK(cpu_transcoder));
7752         pipe_config->base.adjusted_mode.crtc_vblank_start = (tmp & 0xffff) + 1;
7753         pipe_config->base.adjusted_mode.crtc_vblank_end = ((tmp >> 16) & 0xffff) + 1;
7754         tmp = I915_READ(VSYNC(cpu_transcoder));
7755         pipe_config->base.adjusted_mode.crtc_vsync_start = (tmp & 0xffff) + 1;
7756         pipe_config->base.adjusted_mode.crtc_vsync_end = ((tmp >> 16) & 0xffff) + 1;
7757
7758         if (I915_READ(PIPECONF(cpu_transcoder)) & PIPECONF_INTERLACE_MASK) {
7759                 pipe_config->base.adjusted_mode.flags |= DRM_MODE_FLAG_INTERLACE;
7760                 pipe_config->base.adjusted_mode.crtc_vtotal += 1;
7761                 pipe_config->base.adjusted_mode.crtc_vblank_end += 1;
7762         }
7763
7764         tmp = I915_READ(PIPESRC(crtc->pipe));
7765         pipe_config->pipe_src_h = (tmp & 0xffff) + 1;
7766         pipe_config->pipe_src_w = ((tmp >> 16) & 0xffff) + 1;
7767
7768         pipe_config->base.mode.vdisplay = pipe_config->pipe_src_h;
7769         pipe_config->base.mode.hdisplay = pipe_config->pipe_src_w;
7770 }
7771
7772 void intel_mode_from_pipe_config(struct drm_display_mode *mode,
7773                                  struct intel_crtc_state *pipe_config)
7774 {
7775         mode->hdisplay = pipe_config->base.adjusted_mode.crtc_hdisplay;
7776         mode->htotal = pipe_config->base.adjusted_mode.crtc_htotal;
7777         mode->hsync_start = pipe_config->base.adjusted_mode.crtc_hsync_start;
7778         mode->hsync_end = pipe_config->base.adjusted_mode.crtc_hsync_end;
7779
7780         mode->vdisplay = pipe_config->base.adjusted_mode.crtc_vdisplay;
7781         mode->vtotal = pipe_config->base.adjusted_mode.crtc_vtotal;
7782         mode->vsync_start = pipe_config->base.adjusted_mode.crtc_vsync_start;
7783         mode->vsync_end = pipe_config->base.adjusted_mode.crtc_vsync_end;
7784
7785         mode->flags = pipe_config->base.adjusted_mode.flags;
7786         mode->type = DRM_MODE_TYPE_DRIVER;
7787
7788         mode->clock = pipe_config->base.adjusted_mode.crtc_clock;
7789         mode->flags |= pipe_config->base.adjusted_mode.flags;
7790
7791         mode->hsync = drm_mode_hsync(mode);
7792         mode->vrefresh = drm_mode_vrefresh(mode);
7793         drm_mode_set_name(mode);
7794 }
7795
7796 static void i9xx_set_pipeconf(struct intel_crtc *intel_crtc)
7797 {
7798         struct drm_device *dev = intel_crtc->base.dev;
7799         struct drm_i915_private *dev_priv = dev->dev_private;
7800         uint32_t pipeconf;
7801
7802         pipeconf = 0;
7803
7804         if ((intel_crtc->pipe == PIPE_A && dev_priv->quirks & QUIRK_PIPEA_FORCE) ||
7805             (intel_crtc->pipe == PIPE_B && dev_priv->quirks & QUIRK_PIPEB_FORCE))
7806                 pipeconf |= I915_READ(PIPECONF(intel_crtc->pipe)) & PIPECONF_ENABLE;
7807
7808         if (intel_crtc->config->double_wide)
7809                 pipeconf |= PIPECONF_DOUBLE_WIDE;
7810
7811         /* only g4x and later have fancy bpc/dither controls */
7812         if (IS_G4X(dev) || IS_VALLEYVIEW(dev) || IS_CHERRYVIEW(dev)) {
7813                 /* Bspec claims that we can't use dithering for 30bpp pipes. */
7814                 if (intel_crtc->config->dither && intel_crtc->config->pipe_bpp != 30)
7815                         pipeconf |= PIPECONF_DITHER_EN |
7816                                     PIPECONF_DITHER_TYPE_SP;
7817
7818                 switch (intel_crtc->config->pipe_bpp) {
7819                 case 18:
7820                         pipeconf |= PIPECONF_6BPC;
7821                         break;
7822                 case 24:
7823                         pipeconf |= PIPECONF_8BPC;
7824                         break;
7825                 case 30:
7826                         pipeconf |= PIPECONF_10BPC;
7827                         break;
7828                 default:
7829                         /* Case prevented by intel_choose_pipe_bpp_dither. */
7830                         BUG();
7831                 }
7832         }
7833
7834         if (HAS_PIPE_CXSR(dev)) {
7835                 if (intel_crtc->lowfreq_avail) {
7836                         DRM_DEBUG_KMS("enabling CxSR downclocking\n");
7837                         pipeconf |= PIPECONF_CXSR_DOWNCLOCK;
7838                 } else {
7839                         DRM_DEBUG_KMS("disabling CxSR downclocking\n");
7840                 }
7841         }
7842
7843         if (intel_crtc->config->base.adjusted_mode.flags & DRM_MODE_FLAG_INTERLACE) {
7844                 if (INTEL_INFO(dev)->gen < 4 ||
7845                     intel_pipe_has_type(intel_crtc, INTEL_OUTPUT_SDVO))
7846                         pipeconf |= PIPECONF_INTERLACE_W_FIELD_INDICATION;
7847                 else
7848                         pipeconf |= PIPECONF_INTERLACE_W_SYNC_SHIFT;
7849         } else
7850                 pipeconf |= PIPECONF_PROGRESSIVE;
7851
7852         if ((IS_VALLEYVIEW(dev) || IS_CHERRYVIEW(dev)) &&
7853              intel_crtc->config->limited_color_range)
7854                 pipeconf |= PIPECONF_COLOR_RANGE_SELECT;
7855
7856         I915_WRITE(PIPECONF(intel_crtc->pipe), pipeconf);
7857         POSTING_READ(PIPECONF(intel_crtc->pipe));
7858 }
7859
7860 static int i9xx_crtc_compute_clock(struct intel_crtc *crtc,
7861                                    struct intel_crtc_state *crtc_state)
7862 {
7863         struct drm_device *dev = crtc->base.dev;
7864         struct drm_i915_private *dev_priv = dev->dev_private;
7865         int refclk, num_connectors = 0;
7866         intel_clock_t clock;
7867         bool ok;
7868         const intel_limit_t *limit;
7869         struct drm_atomic_state *state = crtc_state->base.state;
7870         struct drm_connector *connector;
7871         struct drm_connector_state *connector_state;
7872         int i;
7873
7874         memset(&crtc_state->dpll_hw_state, 0,
7875                sizeof(crtc_state->dpll_hw_state));
7876
7877         if (crtc_state->has_dsi_encoder)
7878                 return 0;
7879
7880         for_each_connector_in_state(state, connector, connector_state, i) {
7881                 if (connector_state->crtc == &crtc->base)
7882                         num_connectors++;
7883         }
7884
7885         if (!crtc_state->clock_set) {
7886                 refclk = i9xx_get_refclk(crtc_state, num_connectors);
7887
7888                 /*
7889                  * Returns a set of divisors for the desired target clock with
7890                  * the given refclk, or FALSE.  The returned values represent
7891                  * the clock equation: reflck * (5 * (m1 + 2) + (m2 + 2)) / (n +
7892                  * 2) / p1 / p2.
7893                  */
7894                 limit = intel_limit(crtc_state, refclk);
7895                 ok = dev_priv->display.find_dpll(limit, crtc_state,
7896                                                  crtc_state->port_clock,
7897                                                  refclk, NULL, &clock);
7898                 if (!ok) {
7899                         DRM_ERROR("Couldn't find PLL settings for mode!\n");
7900                         return -EINVAL;
7901                 }
7902
7903                 /* Compat-code for transition, will disappear. */
7904                 crtc_state->dpll.n = clock.n;
7905                 crtc_state->dpll.m1 = clock.m1;
7906                 crtc_state->dpll.m2 = clock.m2;
7907                 crtc_state->dpll.p1 = clock.p1;
7908                 crtc_state->dpll.p2 = clock.p2;
7909         }
7910
7911         if (IS_GEN2(dev)) {
7912                 i8xx_compute_dpll(crtc, crtc_state, NULL,
7913                                   num_connectors);
7914         } else if (IS_CHERRYVIEW(dev)) {
7915                 chv_compute_dpll(crtc, crtc_state);
7916         } else if (IS_VALLEYVIEW(dev)) {
7917                 vlv_compute_dpll(crtc, crtc_state);
7918         } else {
7919                 i9xx_compute_dpll(crtc, crtc_state, NULL,
7920                                   num_connectors);
7921         }
7922
7923         return 0;
7924 }
7925
7926 static void i9xx_get_pfit_config(struct intel_crtc *crtc,
7927                                  struct intel_crtc_state *pipe_config)
7928 {
7929         struct drm_device *dev = crtc->base.dev;
7930         struct drm_i915_private *dev_priv = dev->dev_private;
7931         uint32_t tmp;
7932
7933         if (INTEL_INFO(dev)->gen <= 3 && (IS_I830(dev) || !IS_MOBILE(dev)))
7934                 return;
7935
7936         tmp = I915_READ(PFIT_CONTROL);
7937         if (!(tmp & PFIT_ENABLE))
7938                 return;
7939
7940         /* Check whether the pfit is attached to our pipe. */
7941         if (INTEL_INFO(dev)->gen < 4) {
7942                 if (crtc->pipe != PIPE_B)
7943                         return;
7944         } else {
7945                 if ((tmp & PFIT_PIPE_MASK) != (crtc->pipe << PFIT_PIPE_SHIFT))
7946                         return;
7947         }
7948
7949         pipe_config->gmch_pfit.control = tmp;
7950         pipe_config->gmch_pfit.pgm_ratios = I915_READ(PFIT_PGM_RATIOS);
7951         if (INTEL_INFO(dev)->gen < 5)
7952                 pipe_config->gmch_pfit.lvds_border_bits =
7953                         I915_READ(LVDS) & LVDS_BORDER_ENABLE;
7954 }
7955
7956 static void vlv_crtc_clock_get(struct intel_crtc *crtc,
7957                                struct intel_crtc_state *pipe_config)
7958 {
7959         struct drm_device *dev = crtc->base.dev;
7960         struct drm_i915_private *dev_priv = dev->dev_private;
7961         int pipe = pipe_config->cpu_transcoder;
7962         intel_clock_t clock;
7963         u32 mdiv;
7964         int refclk = 100000;
7965
7966         /* In case of MIPI DPLL will not even be used */
7967         if (!(pipe_config->dpll_hw_state.dpll & DPLL_VCO_ENABLE))
7968                 return;
7969
7970         mutex_lock(&dev_priv->sb_lock);
7971         mdiv = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW3(pipe));
7972         mutex_unlock(&dev_priv->sb_lock);
7973
7974         clock.m1 = (mdiv >> DPIO_M1DIV_SHIFT) & 7;
7975         clock.m2 = mdiv & DPIO_M2DIV_MASK;
7976         clock.n = (mdiv >> DPIO_N_SHIFT) & 0xf;
7977         clock.p1 = (mdiv >> DPIO_P1_SHIFT) & 7;
7978         clock.p2 = (mdiv >> DPIO_P2_SHIFT) & 0x1f;
7979
7980         pipe_config->port_clock = vlv_calc_dpll_params(refclk, &clock);
7981 }
7982
7983 static void
7984 i9xx_get_initial_plane_config(struct intel_crtc *crtc,
7985                               struct intel_initial_plane_config *plane_config)
7986 {
7987         struct drm_device *dev = crtc->base.dev;
7988         struct drm_i915_private *dev_priv = dev->dev_private;
7989         u32 val, base, offset;
7990         int pipe = crtc->pipe, plane = crtc->plane;
7991         int fourcc, pixel_format;
7992         unsigned int aligned_height;
7993         struct drm_framebuffer *fb;
7994         struct intel_framebuffer *intel_fb;
7995
7996         val = I915_READ(DSPCNTR(plane));
7997         if (!(val & DISPLAY_PLANE_ENABLE))
7998                 return;
7999
8000         intel_fb = kzalloc(sizeof(*intel_fb), GFP_KERNEL);
8001         if (!intel_fb) {
8002                 DRM_DEBUG_KMS("failed to alloc fb\n");
8003                 return;
8004         }
8005
8006         fb = &intel_fb->base;
8007
8008         if (INTEL_INFO(dev)->gen >= 4) {
8009                 if (val & DISPPLANE_TILED) {
8010                         plane_config->tiling = I915_TILING_X;
8011                         fb->modifier[0] = I915_FORMAT_MOD_X_TILED;
8012                 }
8013         }
8014
8015         pixel_format = val & DISPPLANE_PIXFORMAT_MASK;
8016         fourcc = i9xx_format_to_fourcc(pixel_format);
8017         fb->pixel_format = fourcc;
8018         fb->bits_per_pixel = drm_format_plane_cpp(fourcc, 0) * 8;
8019
8020         if (INTEL_INFO(dev)->gen >= 4) {
8021                 if (plane_config->tiling)
8022                         offset = I915_READ(DSPTILEOFF(plane));
8023                 else
8024                         offset = I915_READ(DSPLINOFF(plane));
8025                 base = I915_READ(DSPSURF(plane)) & 0xfffff000;
8026         } else {
8027                 base = I915_READ(DSPADDR(plane));
8028         }
8029         plane_config->base = base;
8030
8031         val = I915_READ(PIPESRC(pipe));
8032         fb->width = ((val >> 16) & 0xfff) + 1;
8033         fb->height = ((val >> 0) & 0xfff) + 1;
8034
8035         val = I915_READ(DSPSTRIDE(pipe));
8036         fb->pitches[0] = val & 0xffffffc0;
8037
8038         aligned_height = intel_fb_align_height(dev, fb->height,
8039                                                fb->pixel_format,
8040                                                fb->modifier[0]);
8041
8042         plane_config->size = fb->pitches[0] * aligned_height;
8043
8044         DRM_DEBUG_KMS("pipe/plane %c/%d with fb: size=%dx%d@%d, offset=%x, pitch %d, size 0x%x\n",
8045                       pipe_name(pipe), plane, fb->width, fb->height,
8046                       fb->bits_per_pixel, base, fb->pitches[0],
8047                       plane_config->size);
8048
8049         plane_config->fb = intel_fb;
8050 }
8051
8052 static void chv_crtc_clock_get(struct intel_crtc *crtc,
8053                                struct intel_crtc_state *pipe_config)
8054 {
8055         struct drm_device *dev = crtc->base.dev;
8056         struct drm_i915_private *dev_priv = dev->dev_private;
8057         int pipe = pipe_config->cpu_transcoder;
8058         enum dpio_channel port = vlv_pipe_to_channel(pipe);
8059         intel_clock_t clock;
8060         u32 cmn_dw13, pll_dw0, pll_dw1, pll_dw2, pll_dw3;
8061         int refclk = 100000;
8062
8063         mutex_lock(&dev_priv->sb_lock);
8064         cmn_dw13 = vlv_dpio_read(dev_priv, pipe, CHV_CMN_DW13(port));
8065         pll_dw0 = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW0(port));
8066         pll_dw1 = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW1(port));
8067         pll_dw2 = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW2(port));
8068         pll_dw3 = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW3(port));
8069         mutex_unlock(&dev_priv->sb_lock);
8070
8071         clock.m1 = (pll_dw1 & 0x7) == DPIO_CHV_M1_DIV_BY_2 ? 2 : 0;
8072         clock.m2 = (pll_dw0 & 0xff) << 22;
8073         if (pll_dw3 & DPIO_CHV_FRAC_DIV_EN)
8074                 clock.m2 |= pll_dw2 & 0x3fffff;
8075         clock.n = (pll_dw1 >> DPIO_CHV_N_DIV_SHIFT) & 0xf;
8076         clock.p1 = (cmn_dw13 >> DPIO_CHV_P1_DIV_SHIFT) & 0x7;
8077         clock.p2 = (cmn_dw13 >> DPIO_CHV_P2_DIV_SHIFT) & 0x1f;
8078
8079         pipe_config->port_clock = chv_calc_dpll_params(refclk, &clock);
8080 }
8081
8082 static bool i9xx_get_pipe_config(struct intel_crtc *crtc,
8083                                  struct intel_crtc_state *pipe_config)
8084 {
8085         struct drm_device *dev = crtc->base.dev;
8086         struct drm_i915_private *dev_priv = dev->dev_private;
8087         enum intel_display_power_domain power_domain;
8088         uint32_t tmp;
8089         bool ret;
8090
8091         power_domain = POWER_DOMAIN_PIPE(crtc->pipe);
8092         if (!intel_display_power_get_if_enabled(dev_priv, power_domain))
8093                 return false;
8094
8095         pipe_config->cpu_transcoder = (enum transcoder) crtc->pipe;
8096         pipe_config->shared_dpll = NULL;
8097
8098         ret = false;
8099
8100         tmp = I915_READ(PIPECONF(crtc->pipe));
8101         if (!(tmp & PIPECONF_ENABLE))
8102                 goto out;
8103
8104         if (IS_G4X(dev) || IS_VALLEYVIEW(dev) || IS_CHERRYVIEW(dev)) {
8105                 switch (tmp & PIPECONF_BPC_MASK) {
8106                 case PIPECONF_6BPC:
8107                         pipe_config->pipe_bpp = 18;
8108                         break;
8109                 case PIPECONF_8BPC:
8110                         pipe_config->pipe_bpp = 24;
8111                         break;
8112                 case PIPECONF_10BPC:
8113                         pipe_config->pipe_bpp = 30;
8114                         break;
8115                 default:
8116                         break;
8117                 }
8118         }
8119
8120         if ((IS_VALLEYVIEW(dev) || IS_CHERRYVIEW(dev)) &&
8121             (tmp & PIPECONF_COLOR_RANGE_SELECT))
8122                 pipe_config->limited_color_range = true;
8123
8124         if (INTEL_INFO(dev)->gen < 4)
8125                 pipe_config->double_wide = tmp & PIPECONF_DOUBLE_WIDE;
8126
8127         intel_get_pipe_timings(crtc, pipe_config);
8128
8129         i9xx_get_pfit_config(crtc, pipe_config);
8130
8131         if (INTEL_INFO(dev)->gen >= 4) {
8132                 tmp = I915_READ(DPLL_MD(crtc->pipe));
8133                 pipe_config->pixel_multiplier =
8134                         ((tmp & DPLL_MD_UDI_MULTIPLIER_MASK)
8135                          >> DPLL_MD_UDI_MULTIPLIER_SHIFT) + 1;
8136                 pipe_config->dpll_hw_state.dpll_md = tmp;
8137         } else if (IS_I945G(dev) || IS_I945GM(dev) || IS_G33(dev)) {
8138                 tmp = I915_READ(DPLL(crtc->pipe));
8139                 pipe_config->pixel_multiplier =
8140                         ((tmp & SDVO_MULTIPLIER_MASK)
8141                          >> SDVO_MULTIPLIER_SHIFT_HIRES) + 1;
8142         } else {
8143                 /* Note that on i915G/GM the pixel multiplier is in the sdvo
8144                  * port and will be fixed up in the encoder->get_config
8145                  * function. */
8146                 pipe_config->pixel_multiplier = 1;
8147         }
8148         pipe_config->dpll_hw_state.dpll = I915_READ(DPLL(crtc->pipe));
8149         if (!IS_VALLEYVIEW(dev) && !IS_CHERRYVIEW(dev)) {
8150                 /*
8151                  * DPLL_DVO_2X_MODE must be enabled for both DPLLs
8152                  * on 830. Filter it out here so that we don't
8153                  * report errors due to that.
8154                  */
8155                 if (IS_I830(dev))
8156                         pipe_config->dpll_hw_state.dpll &= ~DPLL_DVO_2X_MODE;
8157
8158                 pipe_config->dpll_hw_state.fp0 = I915_READ(FP0(crtc->pipe));
8159                 pipe_config->dpll_hw_state.fp1 = I915_READ(FP1(crtc->pipe));
8160         } else {
8161                 /* Mask out read-only status bits. */
8162                 pipe_config->dpll_hw_state.dpll &= ~(DPLL_LOCK_VLV |
8163                                                      DPLL_PORTC_READY_MASK |
8164                                                      DPLL_PORTB_READY_MASK);
8165         }
8166
8167         if (IS_CHERRYVIEW(dev))
8168                 chv_crtc_clock_get(crtc, pipe_config);
8169         else if (IS_VALLEYVIEW(dev))
8170                 vlv_crtc_clock_get(crtc, pipe_config);
8171         else
8172                 i9xx_crtc_clock_get(crtc, pipe_config);
8173
8174         /*
8175          * Normally the dotclock is filled in by the encoder .get_config()
8176          * but in case the pipe is enabled w/o any ports we need a sane
8177          * default.
8178          */
8179         pipe_config->base.adjusted_mode.crtc_clock =
8180                 pipe_config->port_clock / pipe_config->pixel_multiplier;
8181
8182         ret = true;
8183
8184 out:
8185         intel_display_power_put(dev_priv, power_domain);
8186
8187         return ret;
8188 }
8189
8190 static void ironlake_init_pch_refclk(struct drm_device *dev)
8191 {
8192         struct drm_i915_private *dev_priv = dev->dev_private;
8193         struct intel_encoder *encoder;
8194         u32 val, final;
8195         bool has_lvds = false;
8196         bool has_cpu_edp = false;
8197         bool has_panel = false;
8198         bool has_ck505 = false;
8199         bool can_ssc = false;
8200
8201         /* We need to take the global config into account */
8202         for_each_intel_encoder(dev, encoder) {
8203                 switch (encoder->type) {
8204                 case INTEL_OUTPUT_LVDS:
8205                         has_panel = true;
8206                         has_lvds = true;
8207                         break;
8208                 case INTEL_OUTPUT_EDP:
8209                         has_panel = true;
8210                         if (enc_to_dig_port(&encoder->base)->port == PORT_A)
8211                                 has_cpu_edp = true;
8212                         break;
8213                 default:
8214                         break;
8215                 }
8216         }
8217
8218         if (HAS_PCH_IBX(dev)) {
8219                 has_ck505 = dev_priv->vbt.display_clock_mode;
8220                 can_ssc = has_ck505;
8221         } else {
8222                 has_ck505 = false;
8223                 can_ssc = true;
8224         }
8225
8226         DRM_DEBUG_KMS("has_panel %d has_lvds %d has_ck505 %d\n",
8227                       has_panel, has_lvds, has_ck505);
8228
8229         /* Ironlake: try to setup display ref clock before DPLL
8230          * enabling. This is only under driver's control after
8231          * PCH B stepping, previous chipset stepping should be
8232          * ignoring this setting.
8233          */
8234         val = I915_READ(PCH_DREF_CONTROL);
8235
8236         /* As we must carefully and slowly disable/enable each source in turn,
8237          * compute the final state we want first and check if we need to
8238          * make any changes at all.
8239          */
8240         final = val;
8241         final &= ~DREF_NONSPREAD_SOURCE_MASK;
8242         if (has_ck505)
8243                 final |= DREF_NONSPREAD_CK505_ENABLE;
8244         else
8245                 final |= DREF_NONSPREAD_SOURCE_ENABLE;
8246
8247         final &= ~DREF_SSC_SOURCE_MASK;
8248         final &= ~DREF_CPU_SOURCE_OUTPUT_MASK;
8249         final &= ~DREF_SSC1_ENABLE;
8250
8251         if (has_panel) {
8252                 final |= DREF_SSC_SOURCE_ENABLE;
8253
8254                 if (intel_panel_use_ssc(dev_priv) && can_ssc)
8255                         final |= DREF_SSC1_ENABLE;
8256
8257                 if (has_cpu_edp) {
8258                         if (intel_panel_use_ssc(dev_priv) && can_ssc)
8259                                 final |= DREF_CPU_SOURCE_OUTPUT_DOWNSPREAD;
8260                         else
8261                                 final |= DREF_CPU_SOURCE_OUTPUT_NONSPREAD;
8262                 } else
8263                         final |= DREF_CPU_SOURCE_OUTPUT_DISABLE;
8264         } else {
8265                 final |= DREF_SSC_SOURCE_DISABLE;
8266                 final |= DREF_CPU_SOURCE_OUTPUT_DISABLE;
8267         }
8268
8269         if (final == val)
8270                 return;
8271
8272         /* Always enable nonspread source */
8273         val &= ~DREF_NONSPREAD_SOURCE_MASK;
8274
8275         if (has_ck505)
8276                 val |= DREF_NONSPREAD_CK505_ENABLE;
8277         else
8278                 val |= DREF_NONSPREAD_SOURCE_ENABLE;
8279
8280         if (has_panel) {
8281                 val &= ~DREF_SSC_SOURCE_MASK;
8282                 val |= DREF_SSC_SOURCE_ENABLE;
8283
8284                 /* SSC must be turned on before enabling the CPU output  */
8285                 if (intel_panel_use_ssc(dev_priv) && can_ssc) {
8286                         DRM_DEBUG_KMS("Using SSC on panel\n");
8287                         val |= DREF_SSC1_ENABLE;
8288                 } else
8289                         val &= ~DREF_SSC1_ENABLE;
8290
8291                 /* Get SSC going before enabling the outputs */
8292                 I915_WRITE(PCH_DREF_CONTROL, val);
8293                 POSTING_READ(PCH_DREF_CONTROL);
8294                 udelay(200);
8295
8296                 val &= ~DREF_CPU_SOURCE_OUTPUT_MASK;
8297
8298                 /* Enable CPU source on CPU attached eDP */
8299                 if (has_cpu_edp) {
8300                         if (intel_panel_use_ssc(dev_priv) && can_ssc) {
8301                                 DRM_DEBUG_KMS("Using SSC on eDP\n");
8302                                 val |= DREF_CPU_SOURCE_OUTPUT_DOWNSPREAD;
8303                         } else
8304                                 val |= DREF_CPU_SOURCE_OUTPUT_NONSPREAD;
8305                 } else
8306                         val |= DREF_CPU_SOURCE_OUTPUT_DISABLE;
8307
8308                 I915_WRITE(PCH_DREF_CONTROL, val);
8309                 POSTING_READ(PCH_DREF_CONTROL);
8310                 udelay(200);
8311         } else {
8312                 DRM_DEBUG_KMS("Disabling SSC entirely\n");
8313
8314                 val &= ~DREF_CPU_SOURCE_OUTPUT_MASK;
8315
8316                 /* Turn off CPU output */
8317                 val |= DREF_CPU_SOURCE_OUTPUT_DISABLE;
8318
8319                 I915_WRITE(PCH_DREF_CONTROL, val);
8320                 POSTING_READ(PCH_DREF_CONTROL);
8321                 udelay(200);
8322
8323                 /* Turn off the SSC source */
8324                 val &= ~DREF_SSC_SOURCE_MASK;
8325                 val |= DREF_SSC_SOURCE_DISABLE;
8326
8327                 /* Turn off SSC1 */
8328                 val &= ~DREF_SSC1_ENABLE;
8329
8330                 I915_WRITE(PCH_DREF_CONTROL, val);
8331                 POSTING_READ(PCH_DREF_CONTROL);
8332                 udelay(200);
8333         }
8334
8335         BUG_ON(val != final);
8336 }
8337
8338 static void lpt_reset_fdi_mphy(struct drm_i915_private *dev_priv)
8339 {
8340         uint32_t tmp;
8341
8342         tmp = I915_READ(SOUTH_CHICKEN2);
8343         tmp |= FDI_MPHY_IOSFSB_RESET_CTL;
8344         I915_WRITE(SOUTH_CHICKEN2, tmp);
8345
8346         if (wait_for_atomic_us(I915_READ(SOUTH_CHICKEN2) &
8347                                FDI_MPHY_IOSFSB_RESET_STATUS, 100))
8348                 DRM_ERROR("FDI mPHY reset assert timeout\n");
8349
8350         tmp = I915_READ(SOUTH_CHICKEN2);
8351         tmp &= ~FDI_MPHY_IOSFSB_RESET_CTL;
8352         I915_WRITE(SOUTH_CHICKEN2, tmp);
8353
8354         if (wait_for_atomic_us((I915_READ(SOUTH_CHICKEN2) &
8355                                 FDI_MPHY_IOSFSB_RESET_STATUS) == 0, 100))
8356                 DRM_ERROR("FDI mPHY reset de-assert timeout\n");
8357 }
8358
8359 /* WaMPhyProgramming:hsw */
8360 static void lpt_program_fdi_mphy(struct drm_i915_private *dev_priv)
8361 {
8362         uint32_t tmp;
8363
8364         tmp = intel_sbi_read(dev_priv, 0x8008, SBI_MPHY);
8365         tmp &= ~(0xFF << 24);
8366         tmp |= (0x12 << 24);
8367         intel_sbi_write(dev_priv, 0x8008, tmp, SBI_MPHY);
8368
8369         tmp = intel_sbi_read(dev_priv, 0x2008, SBI_MPHY);
8370         tmp |= (1 << 11);
8371         intel_sbi_write(dev_priv, 0x2008, tmp, SBI_MPHY);
8372
8373         tmp = intel_sbi_read(dev_priv, 0x2108, SBI_MPHY);
8374         tmp |= (1 << 11);
8375         intel_sbi_write(dev_priv, 0x2108, tmp, SBI_MPHY);
8376
8377         tmp = intel_sbi_read(dev_priv, 0x206C, SBI_MPHY);
8378         tmp |= (1 << 24) | (1 << 21) | (1 << 18);
8379         intel_sbi_write(dev_priv, 0x206C, tmp, SBI_MPHY);
8380
8381         tmp = intel_sbi_read(dev_priv, 0x216C, SBI_MPHY);
8382         tmp |= (1 << 24) | (1 << 21) | (1 << 18);
8383         intel_sbi_write(dev_priv, 0x216C, tmp, SBI_MPHY);
8384
8385         tmp = intel_sbi_read(dev_priv, 0x2080, SBI_MPHY);
8386         tmp &= ~(7 << 13);
8387         tmp |= (5 << 13);
8388         intel_sbi_write(dev_priv, 0x2080, tmp, SBI_MPHY);
8389
8390         tmp = intel_sbi_read(dev_priv, 0x2180, SBI_MPHY);
8391         tmp &= ~(7 << 13);
8392         tmp |= (5 << 13);
8393         intel_sbi_write(dev_priv, 0x2180, tmp, SBI_MPHY);
8394
8395         tmp = intel_sbi_read(dev_priv, 0x208C, SBI_MPHY);
8396         tmp &= ~0xFF;
8397         tmp |= 0x1C;
8398         intel_sbi_write(dev_priv, 0x208C, tmp, SBI_MPHY);
8399
8400         tmp = intel_sbi_read(dev_priv, 0x218C, SBI_MPHY);
8401         tmp &= ~0xFF;
8402         tmp |= 0x1C;
8403         intel_sbi_write(dev_priv, 0x218C, tmp, SBI_MPHY);
8404
8405         tmp = intel_sbi_read(dev_priv, 0x2098, SBI_MPHY);
8406         tmp &= ~(0xFF << 16);
8407         tmp |= (0x1C << 16);
8408         intel_sbi_write(dev_priv, 0x2098, tmp, SBI_MPHY);
8409
8410         tmp = intel_sbi_read(dev_priv, 0x2198, SBI_MPHY);
8411         tmp &= ~(0xFF << 16);
8412         tmp |= (0x1C << 16);
8413         intel_sbi_write(dev_priv, 0x2198, tmp, SBI_MPHY);
8414
8415         tmp = intel_sbi_read(dev_priv, 0x20C4, SBI_MPHY);
8416         tmp |= (1 << 27);
8417         intel_sbi_write(dev_priv, 0x20C4, tmp, SBI_MPHY);
8418
8419         tmp = intel_sbi_read(dev_priv, 0x21C4, SBI_MPHY);
8420         tmp |= (1 << 27);
8421         intel_sbi_write(dev_priv, 0x21C4, tmp, SBI_MPHY);
8422
8423         tmp = intel_sbi_read(dev_priv, 0x20EC, SBI_MPHY);
8424         tmp &= ~(0xF << 28);
8425         tmp |= (4 << 28);
8426         intel_sbi_write(dev_priv, 0x20EC, tmp, SBI_MPHY);
8427
8428         tmp = intel_sbi_read(dev_priv, 0x21EC, SBI_MPHY);
8429         tmp &= ~(0xF << 28);
8430         tmp |= (4 << 28);
8431         intel_sbi_write(dev_priv, 0x21EC, tmp, SBI_MPHY);
8432 }
8433
8434 /* Implements 3 different sequences from BSpec chapter "Display iCLK
8435  * Programming" based on the parameters passed:
8436  * - Sequence to enable CLKOUT_DP
8437  * - Sequence to enable CLKOUT_DP without spread
8438  * - Sequence to enable CLKOUT_DP for FDI usage and configure PCH FDI I/O
8439  */
8440 static void lpt_enable_clkout_dp(struct drm_device *dev, bool with_spread,
8441                                  bool with_fdi)
8442 {
8443         struct drm_i915_private *dev_priv = dev->dev_private;
8444         uint32_t reg, tmp;
8445
8446         if (WARN(with_fdi && !with_spread, "FDI requires downspread\n"))
8447                 with_spread = true;
8448         if (WARN(HAS_PCH_LPT_LP(dev) && with_fdi, "LP PCH doesn't have FDI\n"))
8449                 with_fdi = false;
8450
8451         mutex_lock(&dev_priv->sb_lock);
8452
8453         tmp = intel_sbi_read(dev_priv, SBI_SSCCTL, SBI_ICLK);
8454         tmp &= ~SBI_SSCCTL_DISABLE;
8455         tmp |= SBI_SSCCTL_PATHALT;
8456         intel_sbi_write(dev_priv, SBI_SSCCTL, tmp, SBI_ICLK);
8457
8458         udelay(24);
8459
8460         if (with_spread) {
8461                 tmp = intel_sbi_read(dev_priv, SBI_SSCCTL, SBI_ICLK);
8462                 tmp &= ~SBI_SSCCTL_PATHALT;
8463                 intel_sbi_write(dev_priv, SBI_SSCCTL, tmp, SBI_ICLK);
8464
8465                 if (with_fdi) {
8466                         lpt_reset_fdi_mphy(dev_priv);
8467                         lpt_program_fdi_mphy(dev_priv);
8468                 }
8469         }
8470
8471         reg = HAS_PCH_LPT_LP(dev) ? SBI_GEN0 : SBI_DBUFF0;
8472         tmp = intel_sbi_read(dev_priv, reg, SBI_ICLK);
8473         tmp |= SBI_GEN0_CFG_BUFFENABLE_DISABLE;
8474         intel_sbi_write(dev_priv, reg, tmp, SBI_ICLK);
8475
8476         mutex_unlock(&dev_priv->sb_lock);
8477 }
8478
8479 /* Sequence to disable CLKOUT_DP */
8480 static void lpt_disable_clkout_dp(struct drm_device *dev)
8481 {
8482         struct drm_i915_private *dev_priv = dev->dev_private;
8483         uint32_t reg, tmp;
8484
8485         mutex_lock(&dev_priv->sb_lock);
8486
8487         reg = HAS_PCH_LPT_LP(dev) ? SBI_GEN0 : SBI_DBUFF0;
8488         tmp = intel_sbi_read(dev_priv, reg, SBI_ICLK);
8489         tmp &= ~SBI_GEN0_CFG_BUFFENABLE_DISABLE;
8490         intel_sbi_write(dev_priv, reg, tmp, SBI_ICLK);
8491
8492         tmp = intel_sbi_read(dev_priv, SBI_SSCCTL, SBI_ICLK);
8493         if (!(tmp & SBI_SSCCTL_DISABLE)) {
8494                 if (!(tmp & SBI_SSCCTL_PATHALT)) {
8495                         tmp |= SBI_SSCCTL_PATHALT;
8496                         intel_sbi_write(dev_priv, SBI_SSCCTL, tmp, SBI_ICLK);
8497                         udelay(32);
8498                 }
8499                 tmp |= SBI_SSCCTL_DISABLE;
8500                 intel_sbi_write(dev_priv, SBI_SSCCTL, tmp, SBI_ICLK);
8501         }
8502
8503         mutex_unlock(&dev_priv->sb_lock);
8504 }
8505
8506 #define BEND_IDX(steps) ((50 + (steps)) / 5)
8507
8508 static const uint16_t sscdivintphase[] = {
8509         [BEND_IDX( 50)] = 0x3B23,
8510         [BEND_IDX( 45)] = 0x3B23,
8511         [BEND_IDX( 40)] = 0x3C23,
8512         [BEND_IDX( 35)] = 0x3C23,
8513         [BEND_IDX( 30)] = 0x3D23,
8514         [BEND_IDX( 25)] = 0x3D23,
8515         [BEND_IDX( 20)] = 0x3E23,
8516         [BEND_IDX( 15)] = 0x3E23,
8517         [BEND_IDX( 10)] = 0x3F23,
8518         [BEND_IDX(  5)] = 0x3F23,
8519         [BEND_IDX(  0)] = 0x0025,
8520         [BEND_IDX( -5)] = 0x0025,
8521         [BEND_IDX(-10)] = 0x0125,
8522         [BEND_IDX(-15)] = 0x0125,
8523         [BEND_IDX(-20)] = 0x0225,
8524         [BEND_IDX(-25)] = 0x0225,
8525         [BEND_IDX(-30)] = 0x0325,
8526         [BEND_IDX(-35)] = 0x0325,
8527         [BEND_IDX(-40)] = 0x0425,
8528         [BEND_IDX(-45)] = 0x0425,
8529         [BEND_IDX(-50)] = 0x0525,
8530 };
8531
8532 /*
8533  * Bend CLKOUT_DP
8534  * steps -50 to 50 inclusive, in steps of 5
8535  * < 0 slow down the clock, > 0 speed up the clock, 0 == no bend (135MHz)
8536  * change in clock period = -(steps / 10) * 5.787 ps
8537  */
8538 static void lpt_bend_clkout_dp(struct drm_i915_private *dev_priv, int steps)
8539 {
8540         uint32_t tmp;
8541         int idx = BEND_IDX(steps);
8542
8543         if (WARN_ON(steps % 5 != 0))
8544                 return;
8545
8546         if (WARN_ON(idx >= ARRAY_SIZE(sscdivintphase)))
8547                 return;
8548
8549         mutex_lock(&dev_priv->sb_lock);
8550
8551         if (steps % 10 != 0)
8552                 tmp = 0xAAAAAAAB;
8553         else
8554                 tmp = 0x00000000;
8555         intel_sbi_write(dev_priv, SBI_SSCDITHPHASE, tmp, SBI_ICLK);
8556
8557         tmp = intel_sbi_read(dev_priv, SBI_SSCDIVINTPHASE, SBI_ICLK);
8558         tmp &= 0xffff0000;
8559         tmp |= sscdivintphase[idx];
8560         intel_sbi_write(dev_priv, SBI_SSCDIVINTPHASE, tmp, SBI_ICLK);
8561
8562         mutex_unlock(&dev_priv->sb_lock);
8563 }
8564
8565 #undef BEND_IDX
8566
8567 static void lpt_init_pch_refclk(struct drm_device *dev)
8568 {
8569         struct intel_encoder *encoder;
8570         bool has_vga = false;
8571
8572         for_each_intel_encoder(dev, encoder) {
8573                 switch (encoder->type) {
8574                 case INTEL_OUTPUT_ANALOG:
8575                         has_vga = true;
8576                         break;
8577                 default:
8578                         break;
8579                 }
8580         }
8581
8582         if (has_vga) {
8583                 lpt_bend_clkout_dp(to_i915(dev), 0);
8584                 lpt_enable_clkout_dp(dev, true, true);
8585         } else {
8586                 lpt_disable_clkout_dp(dev);
8587         }
8588 }
8589
8590 /*
8591  * Initialize reference clocks when the driver loads
8592  */
8593 void intel_init_pch_refclk(struct drm_device *dev)
8594 {
8595         if (HAS_PCH_IBX(dev) || HAS_PCH_CPT(dev))
8596                 ironlake_init_pch_refclk(dev);
8597         else if (HAS_PCH_LPT(dev))
8598                 lpt_init_pch_refclk(dev);
8599 }
8600
8601 static int ironlake_get_refclk(struct intel_crtc_state *crtc_state)
8602 {
8603         struct drm_device *dev = crtc_state->base.crtc->dev;
8604         struct drm_i915_private *dev_priv = dev->dev_private;
8605         struct drm_atomic_state *state = crtc_state->base.state;
8606         struct drm_connector *connector;
8607         struct drm_connector_state *connector_state;
8608         struct intel_encoder *encoder;
8609         int num_connectors = 0, i;
8610         bool is_lvds = false;
8611
8612         for_each_connector_in_state(state, connector, connector_state, i) {
8613                 if (connector_state->crtc != crtc_state->base.crtc)
8614                         continue;
8615
8616                 encoder = to_intel_encoder(connector_state->best_encoder);
8617
8618                 switch (encoder->type) {
8619                 case INTEL_OUTPUT_LVDS:
8620                         is_lvds = true;
8621                         break;
8622                 default:
8623                         break;
8624                 }
8625                 num_connectors++;
8626         }
8627
8628         if (is_lvds && intel_panel_use_ssc(dev_priv) && num_connectors < 2) {
8629                 DRM_DEBUG_KMS("using SSC reference clock of %d kHz\n",
8630                               dev_priv->vbt.lvds_ssc_freq);
8631                 return dev_priv->vbt.lvds_ssc_freq;
8632         }
8633
8634         return 120000;
8635 }
8636
8637 static void ironlake_set_pipeconf(struct drm_crtc *crtc)
8638 {
8639         struct drm_i915_private *dev_priv = crtc->dev->dev_private;
8640         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
8641         int pipe = intel_crtc->pipe;
8642         uint32_t val;
8643
8644         val = 0;
8645
8646         switch (intel_crtc->config->pipe_bpp) {
8647         case 18:
8648                 val |= PIPECONF_6BPC;
8649                 break;
8650         case 24:
8651                 val |= PIPECONF_8BPC;
8652                 break;
8653         case 30:
8654                 val |= PIPECONF_10BPC;
8655                 break;
8656         case 36:
8657                 val |= PIPECONF_12BPC;
8658                 break;
8659         default:
8660                 /* Case prevented by intel_choose_pipe_bpp_dither. */
8661                 BUG();
8662         }
8663
8664         if (intel_crtc->config->dither)
8665                 val |= (PIPECONF_DITHER_EN | PIPECONF_DITHER_TYPE_SP);
8666
8667         if (intel_crtc->config->base.adjusted_mode.flags & DRM_MODE_FLAG_INTERLACE)
8668                 val |= PIPECONF_INTERLACED_ILK;
8669         else
8670                 val |= PIPECONF_PROGRESSIVE;
8671
8672         if (intel_crtc->config->limited_color_range)
8673                 val |= PIPECONF_COLOR_RANGE_SELECT;
8674
8675         I915_WRITE(PIPECONF(pipe), val);
8676         POSTING_READ(PIPECONF(pipe));
8677 }
8678
8679 /*
8680  * Set up the pipe CSC unit.
8681  *
8682  * Currently only full range RGB to limited range RGB conversion
8683  * is supported, but eventually this should handle various
8684  * RGB<->YCbCr scenarios as well.
8685  */
8686 static void intel_set_pipe_csc(struct drm_crtc *crtc)
8687 {
8688         struct drm_device *dev = crtc->dev;
8689         struct drm_i915_private *dev_priv = dev->dev_private;
8690         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
8691         int pipe = intel_crtc->pipe;
8692         uint16_t coeff = 0x7800; /* 1.0 */
8693
8694         /*
8695          * TODO: Check what kind of values actually come out of the pipe
8696          * with these coeff/postoff values and adjust to get the best
8697          * accuracy. Perhaps we even need to take the bpc value into
8698          * consideration.
8699          */
8700
8701         if (intel_crtc->config->limited_color_range)
8702                 coeff = ((235 - 16) * (1 << 12) / 255) & 0xff8; /* 0.xxx... */
8703
8704         /*
8705          * GY/GU and RY/RU should be the other way around according
8706          * to BSpec, but reality doesn't agree. Just set them up in
8707          * a way that results in the correct picture.
8708          */
8709         I915_WRITE(PIPE_CSC_COEFF_RY_GY(pipe), coeff << 16);
8710         I915_WRITE(PIPE_CSC_COEFF_BY(pipe), 0);
8711
8712         I915_WRITE(PIPE_CSC_COEFF_RU_GU(pipe), coeff);
8713         I915_WRITE(PIPE_CSC_COEFF_BU(pipe), 0);
8714
8715         I915_WRITE(PIPE_CSC_COEFF_RV_GV(pipe), 0);
8716         I915_WRITE(PIPE_CSC_COEFF_BV(pipe), coeff << 16);
8717
8718         I915_WRITE(PIPE_CSC_PREOFF_HI(pipe), 0);
8719         I915_WRITE(PIPE_CSC_PREOFF_ME(pipe), 0);
8720         I915_WRITE(PIPE_CSC_PREOFF_LO(pipe), 0);
8721
8722         if (INTEL_INFO(dev)->gen > 6) {
8723                 uint16_t postoff = 0;
8724
8725                 if (intel_crtc->config->limited_color_range)
8726                         postoff = (16 * (1 << 12) / 255) & 0x1fff;
8727
8728                 I915_WRITE(PIPE_CSC_POSTOFF_HI(pipe), postoff);
8729                 I915_WRITE(PIPE_CSC_POSTOFF_ME(pipe), postoff);
8730                 I915_WRITE(PIPE_CSC_POSTOFF_LO(pipe), postoff);
8731
8732                 I915_WRITE(PIPE_CSC_MODE(pipe), 0);
8733         } else {
8734                 uint32_t mode = CSC_MODE_YUV_TO_RGB;
8735
8736                 if (intel_crtc->config->limited_color_range)
8737                         mode |= CSC_BLACK_SCREEN_OFFSET;
8738
8739                 I915_WRITE(PIPE_CSC_MODE(pipe), mode);
8740         }
8741 }
8742
8743 static void haswell_set_pipeconf(struct drm_crtc *crtc)
8744 {
8745         struct drm_device *dev = crtc->dev;
8746         struct drm_i915_private *dev_priv = dev->dev_private;
8747         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
8748         enum pipe pipe = intel_crtc->pipe;
8749         enum transcoder cpu_transcoder = intel_crtc->config->cpu_transcoder;
8750         uint32_t val;
8751
8752         val = 0;
8753
8754         if (IS_HASWELL(dev) && intel_crtc->config->dither)
8755                 val |= (PIPECONF_DITHER_EN | PIPECONF_DITHER_TYPE_SP);
8756
8757         if (intel_crtc->config->base.adjusted_mode.flags & DRM_MODE_FLAG_INTERLACE)
8758                 val |= PIPECONF_INTERLACED_ILK;
8759         else
8760                 val |= PIPECONF_PROGRESSIVE;
8761
8762         I915_WRITE(PIPECONF(cpu_transcoder), val);
8763         POSTING_READ(PIPECONF(cpu_transcoder));
8764
8765         I915_WRITE(GAMMA_MODE(intel_crtc->pipe), GAMMA_MODE_MODE_8BIT);
8766         POSTING_READ(GAMMA_MODE(intel_crtc->pipe));
8767
8768         if (IS_BROADWELL(dev) || INTEL_INFO(dev)->gen >= 9) {
8769                 val = 0;
8770
8771                 switch (intel_crtc->config->pipe_bpp) {
8772                 case 18:
8773                         val |= PIPEMISC_DITHER_6_BPC;
8774                         break;
8775                 case 24:
8776                         val |= PIPEMISC_DITHER_8_BPC;
8777                         break;
8778                 case 30:
8779                         val |= PIPEMISC_DITHER_10_BPC;
8780                         break;
8781                 case 36:
8782                         val |= PIPEMISC_DITHER_12_BPC;
8783                         break;
8784                 default:
8785                         /* Case prevented by pipe_config_set_bpp. */
8786                         BUG();
8787                 }
8788
8789                 if (intel_crtc->config->dither)
8790                         val |= PIPEMISC_DITHER_ENABLE | PIPEMISC_DITHER_TYPE_SP;
8791
8792                 I915_WRITE(PIPEMISC(pipe), val);
8793         }
8794 }
8795
8796 static bool ironlake_compute_clocks(struct drm_crtc *crtc,
8797                                     struct intel_crtc_state *crtc_state,
8798                                     intel_clock_t *clock,
8799                                     bool *has_reduced_clock,
8800                                     intel_clock_t *reduced_clock)
8801 {
8802         struct drm_device *dev = crtc->dev;
8803         struct drm_i915_private *dev_priv = dev->dev_private;
8804         int refclk;
8805         const intel_limit_t *limit;
8806         bool ret;
8807
8808         refclk = ironlake_get_refclk(crtc_state);
8809
8810         /*
8811          * Returns a set of divisors for the desired target clock with the given
8812          * refclk, or FALSE.  The returned values represent the clock equation:
8813          * reflck * (5 * (m1 + 2) + (m2 + 2)) / (n + 2) / p1 / p2.
8814          */
8815         limit = intel_limit(crtc_state, refclk);
8816         ret = dev_priv->display.find_dpll(limit, crtc_state,
8817                                           crtc_state->port_clock,
8818                                           refclk, NULL, clock);
8819         if (!ret)
8820                 return false;
8821
8822         return true;
8823 }
8824
8825 int ironlake_get_lanes_required(int target_clock, int link_bw, int bpp)
8826 {
8827         /*
8828          * Account for spread spectrum to avoid
8829          * oversubscribing the link. Max center spread
8830          * is 2.5%; use 5% for safety's sake.
8831          */
8832         u32 bps = target_clock * bpp * 21 / 20;
8833         return DIV_ROUND_UP(bps, link_bw * 8);
8834 }
8835
8836 static bool ironlake_needs_fb_cb_tune(struct dpll *dpll, int factor)
8837 {
8838         return i9xx_dpll_compute_m(dpll) < factor * dpll->n;
8839 }
8840
8841 static uint32_t ironlake_compute_dpll(struct intel_crtc *intel_crtc,
8842                                       struct intel_crtc_state *crtc_state,
8843                                       u32 *fp,
8844                                       intel_clock_t *reduced_clock, u32 *fp2)
8845 {
8846         struct drm_crtc *crtc = &intel_crtc->base;
8847         struct drm_device *dev = crtc->dev;
8848         struct drm_i915_private *dev_priv = dev->dev_private;
8849         struct drm_atomic_state *state = crtc_state->base.state;
8850         struct drm_connector *connector;
8851         struct drm_connector_state *connector_state;
8852         struct intel_encoder *encoder;
8853         uint32_t dpll;
8854         int factor, num_connectors = 0, i;
8855         bool is_lvds = false, is_sdvo = false;
8856
8857         for_each_connector_in_state(state, connector, connector_state, i) {
8858                 if (connector_state->crtc != crtc_state->base.crtc)
8859                         continue;
8860
8861                 encoder = to_intel_encoder(connector_state->best_encoder);
8862
8863                 switch (encoder->type) {
8864                 case INTEL_OUTPUT_LVDS:
8865                         is_lvds = true;
8866                         break;
8867                 case INTEL_OUTPUT_SDVO:
8868                 case INTEL_OUTPUT_HDMI:
8869                         is_sdvo = true;
8870                         break;
8871                 default:
8872                         break;
8873                 }
8874
8875                 num_connectors++;
8876         }
8877
8878         /* Enable autotuning of the PLL clock (if permissible) */
8879         factor = 21;
8880         if (is_lvds) {
8881                 if ((intel_panel_use_ssc(dev_priv) &&
8882                      dev_priv->vbt.lvds_ssc_freq == 100000) ||
8883                     (HAS_PCH_IBX(dev) && intel_is_dual_link_lvds(dev)))
8884                         factor = 25;
8885         } else if (crtc_state->sdvo_tv_clock)
8886                 factor = 20;
8887
8888         if (ironlake_needs_fb_cb_tune(&crtc_state->dpll, factor))
8889                 *fp |= FP_CB_TUNE;
8890
8891         if (fp2 && (reduced_clock->m < factor * reduced_clock->n))
8892                 *fp2 |= FP_CB_TUNE;
8893
8894         dpll = 0;
8895
8896         if (is_lvds)
8897                 dpll |= DPLLB_MODE_LVDS;
8898         else
8899                 dpll |= DPLLB_MODE_DAC_SERIAL;
8900
8901         dpll |= (crtc_state->pixel_multiplier - 1)
8902                 << PLL_REF_SDVO_HDMI_MULTIPLIER_SHIFT;
8903
8904         if (is_sdvo)
8905                 dpll |= DPLL_SDVO_HIGH_SPEED;
8906         if (crtc_state->has_dp_encoder)
8907                 dpll |= DPLL_SDVO_HIGH_SPEED;
8908
8909         /* compute bitmask from p1 value */
8910         dpll |= (1 << (crtc_state->dpll.p1 - 1)) << DPLL_FPA01_P1_POST_DIV_SHIFT;
8911         /* also FPA1 */
8912         dpll |= (1 << (crtc_state->dpll.p1 - 1)) << DPLL_FPA1_P1_POST_DIV_SHIFT;
8913
8914         switch (crtc_state->dpll.p2) {
8915         case 5:
8916                 dpll |= DPLL_DAC_SERIAL_P2_CLOCK_DIV_5;
8917                 break;
8918         case 7:
8919                 dpll |= DPLLB_LVDS_P2_CLOCK_DIV_7;
8920                 break;
8921         case 10:
8922                 dpll |= DPLL_DAC_SERIAL_P2_CLOCK_DIV_10;
8923                 break;
8924         case 14:
8925                 dpll |= DPLLB_LVDS_P2_CLOCK_DIV_14;
8926                 break;
8927         }
8928
8929         if (is_lvds && intel_panel_use_ssc(dev_priv) && num_connectors < 2)
8930                 dpll |= PLLB_REF_INPUT_SPREADSPECTRUMIN;
8931         else
8932                 dpll |= PLL_REF_INPUT_DREFCLK;
8933
8934         return dpll | DPLL_VCO_ENABLE;
8935 }
8936
8937 static int ironlake_crtc_compute_clock(struct intel_crtc *crtc,
8938                                        struct intel_crtc_state *crtc_state)
8939 {
8940         struct drm_device *dev = crtc->base.dev;
8941         intel_clock_t clock, reduced_clock;
8942         u32 dpll = 0, fp = 0, fp2 = 0;
8943         bool ok, has_reduced_clock = false;
8944         bool is_lvds = false;
8945         struct intel_shared_dpll *pll;
8946
8947         memset(&crtc_state->dpll_hw_state, 0,
8948                sizeof(crtc_state->dpll_hw_state));
8949
8950         is_lvds = intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_LVDS);
8951
8952         WARN(!(HAS_PCH_IBX(dev) || HAS_PCH_CPT(dev)),
8953              "Unexpected PCH type %d\n", INTEL_PCH_TYPE(dev));
8954
8955         ok = ironlake_compute_clocks(&crtc->base, crtc_state, &clock,
8956                                      &has_reduced_clock, &reduced_clock);
8957         if (!ok && !crtc_state->clock_set) {
8958                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
8959                 return -EINVAL;
8960         }
8961         /* Compat-code for transition, will disappear. */
8962         if (!crtc_state->clock_set) {
8963                 crtc_state->dpll.n = clock.n;
8964                 crtc_state->dpll.m1 = clock.m1;
8965                 crtc_state->dpll.m2 = clock.m2;
8966                 crtc_state->dpll.p1 = clock.p1;
8967                 crtc_state->dpll.p2 = clock.p2;
8968         }
8969
8970         /* CPU eDP is the only output that doesn't need a PCH PLL of its own. */
8971         if (crtc_state->has_pch_encoder) {
8972                 fp = i9xx_dpll_compute_fp(&crtc_state->dpll);
8973                 if (has_reduced_clock)
8974                         fp2 = i9xx_dpll_compute_fp(&reduced_clock);
8975
8976                 dpll = ironlake_compute_dpll(crtc, crtc_state,
8977                                              &fp, &reduced_clock,
8978                                              has_reduced_clock ? &fp2 : NULL);
8979
8980                 crtc_state->dpll_hw_state.dpll = dpll;
8981                 crtc_state->dpll_hw_state.fp0 = fp;
8982                 if (has_reduced_clock)
8983                         crtc_state->dpll_hw_state.fp1 = fp2;
8984                 else
8985                         crtc_state->dpll_hw_state.fp1 = fp;
8986
8987                 pll = intel_get_shared_dpll(crtc, crtc_state, NULL);
8988                 if (pll == NULL) {
8989                         DRM_DEBUG_DRIVER("failed to find PLL for pipe %c\n",
8990                                          pipe_name(crtc->pipe));
8991                         return -EINVAL;
8992                 }
8993         }
8994
8995         if (is_lvds && has_reduced_clock)
8996                 crtc->lowfreq_avail = true;
8997         else
8998                 crtc->lowfreq_avail = false;
8999
9000         return 0;
9001 }
9002
9003 static void intel_pch_transcoder_get_m_n(struct intel_crtc *crtc,
9004                                          struct intel_link_m_n *m_n)
9005 {
9006         struct drm_device *dev = crtc->base.dev;
9007         struct drm_i915_private *dev_priv = dev->dev_private;
9008         enum pipe pipe = crtc->pipe;
9009
9010         m_n->link_m = I915_READ(PCH_TRANS_LINK_M1(pipe));
9011         m_n->link_n = I915_READ(PCH_TRANS_LINK_N1(pipe));
9012         m_n->gmch_m = I915_READ(PCH_TRANS_DATA_M1(pipe))
9013                 & ~TU_SIZE_MASK;
9014         m_n->gmch_n = I915_READ(PCH_TRANS_DATA_N1(pipe));
9015         m_n->tu = ((I915_READ(PCH_TRANS_DATA_M1(pipe))
9016                     & TU_SIZE_MASK) >> TU_SIZE_SHIFT) + 1;
9017 }
9018
9019 static void intel_cpu_transcoder_get_m_n(struct intel_crtc *crtc,
9020                                          enum transcoder transcoder,
9021                                          struct intel_link_m_n *m_n,
9022                                          struct intel_link_m_n *m2_n2)
9023 {
9024         struct drm_device *dev = crtc->base.dev;
9025         struct drm_i915_private *dev_priv = dev->dev_private;
9026         enum pipe pipe = crtc->pipe;
9027
9028         if (INTEL_INFO(dev)->gen >= 5) {
9029                 m_n->link_m = I915_READ(PIPE_LINK_M1(transcoder));
9030                 m_n->link_n = I915_READ(PIPE_LINK_N1(transcoder));
9031                 m_n->gmch_m = I915_READ(PIPE_DATA_M1(transcoder))
9032                         & ~TU_SIZE_MASK;
9033                 m_n->gmch_n = I915_READ(PIPE_DATA_N1(transcoder));
9034                 m_n->tu = ((I915_READ(PIPE_DATA_M1(transcoder))
9035                             & TU_SIZE_MASK) >> TU_SIZE_SHIFT) + 1;
9036                 /* Read M2_N2 registers only for gen < 8 (M2_N2 available for
9037                  * gen < 8) and if DRRS is supported (to make sure the
9038                  * registers are not unnecessarily read).
9039                  */
9040                 if (m2_n2 && INTEL_INFO(dev)->gen < 8 &&
9041                         crtc->config->has_drrs) {
9042                         m2_n2->link_m = I915_READ(PIPE_LINK_M2(transcoder));
9043                         m2_n2->link_n = I915_READ(PIPE_LINK_N2(transcoder));
9044                         m2_n2->gmch_m = I915_READ(PIPE_DATA_M2(transcoder))
9045                                         & ~TU_SIZE_MASK;
9046                         m2_n2->gmch_n = I915_READ(PIPE_DATA_N2(transcoder));
9047                         m2_n2->tu = ((I915_READ(PIPE_DATA_M2(transcoder))
9048                                         & TU_SIZE_MASK) >> TU_SIZE_SHIFT) + 1;
9049                 }
9050         } else {
9051                 m_n->link_m = I915_READ(PIPE_LINK_M_G4X(pipe));
9052                 m_n->link_n = I915_READ(PIPE_LINK_N_G4X(pipe));
9053                 m_n->gmch_m = I915_READ(PIPE_DATA_M_G4X(pipe))
9054                         & ~TU_SIZE_MASK;
9055                 m_n->gmch_n = I915_READ(PIPE_DATA_N_G4X(pipe));
9056                 m_n->tu = ((I915_READ(PIPE_DATA_M_G4X(pipe))
9057                             & TU_SIZE_MASK) >> TU_SIZE_SHIFT) + 1;
9058         }
9059 }
9060
9061 void intel_dp_get_m_n(struct intel_crtc *crtc,
9062                       struct intel_crtc_state *pipe_config)
9063 {
9064         if (pipe_config->has_pch_encoder)
9065                 intel_pch_transcoder_get_m_n(crtc, &pipe_config->dp_m_n);
9066         else
9067                 intel_cpu_transcoder_get_m_n(crtc, pipe_config->cpu_transcoder,
9068                                              &pipe_config->dp_m_n,
9069                                              &pipe_config->dp_m2_n2);
9070 }
9071
9072 static void ironlake_get_fdi_m_n_config(struct intel_crtc *crtc,
9073                                         struct intel_crtc_state *pipe_config)
9074 {
9075         intel_cpu_transcoder_get_m_n(crtc, pipe_config->cpu_transcoder,
9076                                      &pipe_config->fdi_m_n, NULL);
9077 }
9078
9079 static void skylake_get_pfit_config(struct intel_crtc *crtc,
9080                                     struct intel_crtc_state *pipe_config)
9081 {
9082         struct drm_device *dev = crtc->base.dev;
9083         struct drm_i915_private *dev_priv = dev->dev_private;
9084         struct intel_crtc_scaler_state *scaler_state = &pipe_config->scaler_state;
9085         uint32_t ps_ctrl = 0;
9086         int id = -1;
9087         int i;
9088
9089         /* find scaler attached to this pipe */
9090         for (i = 0; i < crtc->num_scalers; i++) {
9091                 ps_ctrl = I915_READ(SKL_PS_CTRL(crtc->pipe, i));
9092                 if (ps_ctrl & PS_SCALER_EN && !(ps_ctrl & PS_PLANE_SEL_MASK)) {
9093                         id = i;
9094                         pipe_config->pch_pfit.enabled = true;
9095                         pipe_config->pch_pfit.pos = I915_READ(SKL_PS_WIN_POS(crtc->pipe, i));
9096                         pipe_config->pch_pfit.size = I915_READ(SKL_PS_WIN_SZ(crtc->pipe, i));
9097                         break;
9098                 }
9099         }
9100
9101         scaler_state->scaler_id = id;
9102         if (id >= 0) {
9103                 scaler_state->scaler_users |= (1 << SKL_CRTC_INDEX);
9104         } else {
9105                 scaler_state->scaler_users &= ~(1 << SKL_CRTC_INDEX);
9106         }
9107 }
9108
9109 static void
9110 skylake_get_initial_plane_config(struct intel_crtc *crtc,
9111                                  struct intel_initial_plane_config *plane_config)
9112 {
9113         struct drm_device *dev = crtc->base.dev;
9114         struct drm_i915_private *dev_priv = dev->dev_private;
9115         u32 val, base, offset, stride_mult, tiling;
9116         int pipe = crtc->pipe;
9117         int fourcc, pixel_format;
9118         unsigned int aligned_height;
9119         struct drm_framebuffer *fb;
9120         struct intel_framebuffer *intel_fb;
9121
9122         intel_fb = kzalloc(sizeof(*intel_fb), GFP_KERNEL);
9123         if (!intel_fb) {
9124                 DRM_DEBUG_KMS("failed to alloc fb\n");
9125                 return;
9126         }
9127
9128         fb = &intel_fb->base;
9129
9130         val = I915_READ(PLANE_CTL(pipe, 0));
9131         if (!(val & PLANE_CTL_ENABLE))
9132                 goto error;
9133
9134         pixel_format = val & PLANE_CTL_FORMAT_MASK;
9135         fourcc = skl_format_to_fourcc(pixel_format,
9136                                       val & PLANE_CTL_ORDER_RGBX,
9137                                       val & PLANE_CTL_ALPHA_MASK);
9138         fb->pixel_format = fourcc;
9139         fb->bits_per_pixel = drm_format_plane_cpp(fourcc, 0) * 8;
9140
9141         tiling = val & PLANE_CTL_TILED_MASK;
9142         switch (tiling) {
9143         case PLANE_CTL_TILED_LINEAR:
9144                 fb->modifier[0] = DRM_FORMAT_MOD_NONE;
9145                 break;
9146         case PLANE_CTL_TILED_X:
9147                 plane_config->tiling = I915_TILING_X;
9148                 fb->modifier[0] = I915_FORMAT_MOD_X_TILED;
9149                 break;
9150         case PLANE_CTL_TILED_Y:
9151                 fb->modifier[0] = I915_FORMAT_MOD_Y_TILED;
9152                 break;
9153         case PLANE_CTL_TILED_YF:
9154                 fb->modifier[0] = I915_FORMAT_MOD_Yf_TILED;
9155                 break;
9156         default:
9157                 MISSING_CASE(tiling);
9158                 goto error;
9159         }
9160
9161         base = I915_READ(PLANE_SURF(pipe, 0)) & 0xfffff000;
9162         plane_config->base = base;
9163
9164         offset = I915_READ(PLANE_OFFSET(pipe, 0));
9165
9166         val = I915_READ(PLANE_SIZE(pipe, 0));
9167         fb->height = ((val >> 16) & 0xfff) + 1;
9168         fb->width = ((val >> 0) & 0x1fff) + 1;
9169
9170         val = I915_READ(PLANE_STRIDE(pipe, 0));
9171         stride_mult = intel_fb_stride_alignment(dev_priv, fb->modifier[0],
9172                                                 fb->pixel_format);
9173         fb->pitches[0] = (val & 0x3ff) * stride_mult;
9174
9175         aligned_height = intel_fb_align_height(dev, fb->height,
9176                                                fb->pixel_format,
9177                                                fb->modifier[0]);
9178
9179         plane_config->size = fb->pitches[0] * aligned_height;
9180
9181         DRM_DEBUG_KMS("pipe %c with fb: size=%dx%d@%d, offset=%x, pitch %d, size 0x%x\n",
9182                       pipe_name(pipe), fb->width, fb->height,
9183                       fb->bits_per_pixel, base, fb->pitches[0],
9184                       plane_config->size);
9185
9186         plane_config->fb = intel_fb;
9187         return;
9188
9189 error:
9190         kfree(fb);
9191 }
9192
9193 static void ironlake_get_pfit_config(struct intel_crtc *crtc,
9194                                      struct intel_crtc_state *pipe_config)
9195 {
9196         struct drm_device *dev = crtc->base.dev;
9197         struct drm_i915_private *dev_priv = dev->dev_private;
9198         uint32_t tmp;
9199
9200         tmp = I915_READ(PF_CTL(crtc->pipe));
9201
9202         if (tmp & PF_ENABLE) {
9203                 pipe_config->pch_pfit.enabled = true;
9204                 pipe_config->pch_pfit.pos = I915_READ(PF_WIN_POS(crtc->pipe));
9205                 pipe_config->pch_pfit.size = I915_READ(PF_WIN_SZ(crtc->pipe));
9206
9207                 /* We currently do not free assignements of panel fitters on
9208                  * ivb/hsw (since we don't use the higher upscaling modes which
9209                  * differentiates them) so just WARN about this case for now. */
9210                 if (IS_GEN7(dev)) {
9211                         WARN_ON((tmp & PF_PIPE_SEL_MASK_IVB) !=
9212                                 PF_PIPE_SEL_IVB(crtc->pipe));
9213                 }
9214         }
9215 }
9216
9217 static void
9218 ironlake_get_initial_plane_config(struct intel_crtc *crtc,
9219                                   struct intel_initial_plane_config *plane_config)
9220 {
9221         struct drm_device *dev = crtc->base.dev;
9222         struct drm_i915_private *dev_priv = dev->dev_private;
9223         u32 val, base, offset;
9224         int pipe = crtc->pipe;
9225         int fourcc, pixel_format;
9226         unsigned int aligned_height;
9227         struct drm_framebuffer *fb;
9228         struct intel_framebuffer *intel_fb;
9229
9230         val = I915_READ(DSPCNTR(pipe));
9231         if (!(val & DISPLAY_PLANE_ENABLE))
9232                 return;
9233
9234         intel_fb = kzalloc(sizeof(*intel_fb), GFP_KERNEL);
9235         if (!intel_fb) {
9236                 DRM_DEBUG_KMS("failed to alloc fb\n");
9237                 return;
9238         }
9239
9240         fb = &intel_fb->base;
9241
9242         if (INTEL_INFO(dev)->gen >= 4) {
9243                 if (val & DISPPLANE_TILED) {
9244                         plane_config->tiling = I915_TILING_X;
9245                         fb->modifier[0] = I915_FORMAT_MOD_X_TILED;
9246                 }
9247         }
9248
9249         pixel_format = val & DISPPLANE_PIXFORMAT_MASK;
9250         fourcc = i9xx_format_to_fourcc(pixel_format);
9251         fb->pixel_format = fourcc;
9252         fb->bits_per_pixel = drm_format_plane_cpp(fourcc, 0) * 8;
9253
9254         base = I915_READ(DSPSURF(pipe)) & 0xfffff000;
9255         if (IS_HASWELL(dev) || IS_BROADWELL(dev)) {
9256                 offset = I915_READ(DSPOFFSET(pipe));
9257         } else {
9258                 if (plane_config->tiling)
9259                         offset = I915_READ(DSPTILEOFF(pipe));
9260                 else
9261                         offset = I915_READ(DSPLINOFF(pipe));
9262         }
9263         plane_config->base = base;
9264
9265         val = I915_READ(PIPESRC(pipe));
9266         fb->width = ((val >> 16) & 0xfff) + 1;
9267         fb->height = ((val >> 0) & 0xfff) + 1;
9268
9269         val = I915_READ(DSPSTRIDE(pipe));
9270         fb->pitches[0] = val & 0xffffffc0;
9271
9272         aligned_height = intel_fb_align_height(dev, fb->height,
9273                                                fb->pixel_format,
9274                                                fb->modifier[0]);
9275
9276         plane_config->size = fb->pitches[0] * aligned_height;
9277
9278         DRM_DEBUG_KMS("pipe %c with fb: size=%dx%d@%d, offset=%x, pitch %d, size 0x%x\n",
9279                       pipe_name(pipe), fb->width, fb->height,
9280                       fb->bits_per_pixel, base, fb->pitches[0],
9281                       plane_config->size);
9282
9283         plane_config->fb = intel_fb;
9284 }
9285
9286 static bool ironlake_get_pipe_config(struct intel_crtc *crtc,
9287                                      struct intel_crtc_state *pipe_config)
9288 {
9289         struct drm_device *dev = crtc->base.dev;
9290         struct drm_i915_private *dev_priv = dev->dev_private;
9291         enum intel_display_power_domain power_domain;
9292         uint32_t tmp;
9293         bool ret;
9294
9295         power_domain = POWER_DOMAIN_PIPE(crtc->pipe);
9296         if (!intel_display_power_get_if_enabled(dev_priv, power_domain))
9297                 return false;
9298
9299         pipe_config->cpu_transcoder = (enum transcoder) crtc->pipe;
9300         pipe_config->shared_dpll = NULL;
9301
9302         ret = false;
9303         tmp = I915_READ(PIPECONF(crtc->pipe));
9304         if (!(tmp & PIPECONF_ENABLE))
9305                 goto out;
9306
9307         switch (tmp & PIPECONF_BPC_MASK) {
9308         case PIPECONF_6BPC:
9309                 pipe_config->pipe_bpp = 18;
9310                 break;
9311         case PIPECONF_8BPC:
9312                 pipe_config->pipe_bpp = 24;
9313                 break;
9314         case PIPECONF_10BPC:
9315                 pipe_config->pipe_bpp = 30;
9316                 break;
9317         case PIPECONF_12BPC:
9318                 pipe_config->pipe_bpp = 36;
9319                 break;
9320         default:
9321                 break;
9322         }
9323
9324         if (tmp & PIPECONF_COLOR_RANGE_SELECT)
9325                 pipe_config->limited_color_range = true;
9326
9327         if (I915_READ(PCH_TRANSCONF(crtc->pipe)) & TRANS_ENABLE) {
9328                 struct intel_shared_dpll *pll;
9329                 enum intel_dpll_id pll_id;
9330
9331                 pipe_config->has_pch_encoder = true;
9332
9333                 tmp = I915_READ(FDI_RX_CTL(crtc->pipe));
9334                 pipe_config->fdi_lanes = ((FDI_DP_PORT_WIDTH_MASK & tmp) >>
9335                                           FDI_DP_PORT_WIDTH_SHIFT) + 1;
9336
9337                 ironlake_get_fdi_m_n_config(crtc, pipe_config);
9338
9339                 if (HAS_PCH_IBX(dev_priv->dev)) {
9340                         pll_id = (enum intel_dpll_id) crtc->pipe;
9341                 } else {
9342                         tmp = I915_READ(PCH_DPLL_SEL);
9343                         if (tmp & TRANS_DPLLB_SEL(crtc->pipe))
9344                                 pll_id = DPLL_ID_PCH_PLL_B;
9345                         else
9346                                 pll_id= DPLL_ID_PCH_PLL_A;
9347                 }
9348
9349                 pipe_config->shared_dpll =
9350                         intel_get_shared_dpll_by_id(dev_priv, pll_id);
9351                 pll = pipe_config->shared_dpll;
9352
9353                 WARN_ON(!pll->funcs.get_hw_state(dev_priv, pll,
9354                                                  &pipe_config->dpll_hw_state));
9355
9356                 tmp = pipe_config->dpll_hw_state.dpll;
9357                 pipe_config->pixel_multiplier =
9358                         ((tmp & PLL_REF_SDVO_HDMI_MULTIPLIER_MASK)
9359                          >> PLL_REF_SDVO_HDMI_MULTIPLIER_SHIFT) + 1;
9360
9361                 ironlake_pch_clock_get(crtc, pipe_config);
9362         } else {
9363                 pipe_config->pixel_multiplier = 1;
9364         }
9365
9366         intel_get_pipe_timings(crtc, pipe_config);
9367
9368         ironlake_get_pfit_config(crtc, pipe_config);
9369
9370         ret = true;
9371
9372 out:
9373         intel_display_power_put(dev_priv, power_domain);
9374
9375         return ret;
9376 }
9377
9378 static void assert_can_disable_lcpll(struct drm_i915_private *dev_priv)
9379 {
9380         struct drm_device *dev = dev_priv->dev;
9381         struct intel_crtc *crtc;
9382
9383         for_each_intel_crtc(dev, crtc)
9384                 I915_STATE_WARN(crtc->active, "CRTC for pipe %c enabled\n",
9385                      pipe_name(crtc->pipe));
9386
9387         I915_STATE_WARN(I915_READ(HSW_PWR_WELL_DRIVER), "Power well on\n");
9388         I915_STATE_WARN(I915_READ(SPLL_CTL) & SPLL_PLL_ENABLE, "SPLL enabled\n");
9389         I915_STATE_WARN(I915_READ(WRPLL_CTL(0)) & WRPLL_PLL_ENABLE, "WRPLL1 enabled\n");
9390         I915_STATE_WARN(I915_READ(WRPLL_CTL(1)) & WRPLL_PLL_ENABLE, "WRPLL2 enabled\n");
9391         I915_STATE_WARN(I915_READ(PCH_PP_STATUS) & PP_ON, "Panel power on\n");
9392         I915_STATE_WARN(I915_READ(BLC_PWM_CPU_CTL2) & BLM_PWM_ENABLE,
9393              "CPU PWM1 enabled\n");
9394         if (IS_HASWELL(dev))
9395                 I915_STATE_WARN(I915_READ(HSW_BLC_PWM2_CTL) & BLM_PWM_ENABLE,
9396                      "CPU PWM2 enabled\n");
9397         I915_STATE_WARN(I915_READ(BLC_PWM_PCH_CTL1) & BLM_PCH_PWM_ENABLE,
9398              "PCH PWM1 enabled\n");
9399         I915_STATE_WARN(I915_READ(UTIL_PIN_CTL) & UTIL_PIN_ENABLE,
9400              "Utility pin enabled\n");
9401         I915_STATE_WARN(I915_READ(PCH_GTC_CTL) & PCH_GTC_ENABLE, "PCH GTC enabled\n");
9402
9403         /*
9404          * In theory we can still leave IRQs enabled, as long as only the HPD
9405          * interrupts remain enabled. We used to check for that, but since it's
9406          * gen-specific and since we only disable LCPLL after we fully disable
9407          * the interrupts, the check below should be enough.
9408          */
9409         I915_STATE_WARN(intel_irqs_enabled(dev_priv), "IRQs enabled\n");
9410 }
9411
9412 static uint32_t hsw_read_dcomp(struct drm_i915_private *dev_priv)
9413 {
9414         struct drm_device *dev = dev_priv->dev;
9415
9416         if (IS_HASWELL(dev))
9417                 return I915_READ(D_COMP_HSW);
9418         else
9419                 return I915_READ(D_COMP_BDW);
9420 }
9421
9422 static void hsw_write_dcomp(struct drm_i915_private *dev_priv, uint32_t val)
9423 {
9424         struct drm_device *dev = dev_priv->dev;
9425
9426         if (IS_HASWELL(dev)) {
9427                 mutex_lock(&dev_priv->rps.hw_lock);
9428                 if (sandybridge_pcode_write(dev_priv, GEN6_PCODE_WRITE_D_COMP,
9429                                             val))
9430                         DRM_ERROR("Failed to write to D_COMP\n");
9431                 mutex_unlock(&dev_priv->rps.hw_lock);
9432         } else {
9433                 I915_WRITE(D_COMP_BDW, val);
9434                 POSTING_READ(D_COMP_BDW);
9435         }
9436 }
9437
9438 /*
9439  * This function implements pieces of two sequences from BSpec:
9440  * - Sequence for display software to disable LCPLL
9441  * - Sequence for display software to allow package C8+
9442  * The steps implemented here are just the steps that actually touch the LCPLL
9443  * register. Callers should take care of disabling all the display engine
9444  * functions, doing the mode unset, fixing interrupts, etc.
9445  */
9446 static void hsw_disable_lcpll(struct drm_i915_private *dev_priv,
9447                               bool switch_to_fclk, bool allow_power_down)
9448 {
9449         uint32_t val;
9450
9451         assert_can_disable_lcpll(dev_priv);
9452
9453         val = I915_READ(LCPLL_CTL);
9454
9455         if (switch_to_fclk) {
9456                 val |= LCPLL_CD_SOURCE_FCLK;
9457                 I915_WRITE(LCPLL_CTL, val);
9458
9459                 if (wait_for_atomic_us(I915_READ(LCPLL_CTL) &
9460                                        LCPLL_CD_SOURCE_FCLK_DONE, 1))
9461                         DRM_ERROR("Switching to FCLK failed\n");
9462
9463                 val = I915_READ(LCPLL_CTL);
9464         }
9465
9466         val |= LCPLL_PLL_DISABLE;
9467         I915_WRITE(LCPLL_CTL, val);
9468         POSTING_READ(LCPLL_CTL);
9469
9470         if (wait_for((I915_READ(LCPLL_CTL) & LCPLL_PLL_LOCK) == 0, 1))
9471                 DRM_ERROR("LCPLL still locked\n");
9472
9473         val = hsw_read_dcomp(dev_priv);
9474         val |= D_COMP_COMP_DISABLE;
9475         hsw_write_dcomp(dev_priv, val);
9476         ndelay(100);
9477
9478         if (wait_for((hsw_read_dcomp(dev_priv) & D_COMP_RCOMP_IN_PROGRESS) == 0,
9479                      1))
9480                 DRM_ERROR("D_COMP RCOMP still in progress\n");
9481
9482         if (allow_power_down) {
9483                 val = I915_READ(LCPLL_CTL);
9484                 val |= LCPLL_POWER_DOWN_ALLOW;
9485                 I915_WRITE(LCPLL_CTL, val);
9486                 POSTING_READ(LCPLL_CTL);
9487         }
9488 }
9489
9490 /*
9491  * Fully restores LCPLL, disallowing power down and switching back to LCPLL
9492  * source.
9493  */
9494 static void hsw_restore_lcpll(struct drm_i915_private *dev_priv)
9495 {
9496         uint32_t val;
9497
9498         val = I915_READ(LCPLL_CTL);
9499
9500         if ((val & (LCPLL_PLL_LOCK | LCPLL_PLL_DISABLE | LCPLL_CD_SOURCE_FCLK |
9501                     LCPLL_POWER_DOWN_ALLOW)) == LCPLL_PLL_LOCK)
9502                 return;
9503
9504         /*
9505          * Make sure we're not on PC8 state before disabling PC8, otherwise
9506          * we'll hang the machine. To prevent PC8 state, just enable force_wake.
9507          */
9508         intel_uncore_forcewake_get(dev_priv, FORCEWAKE_ALL);
9509
9510         if (val & LCPLL_POWER_DOWN_ALLOW) {
9511                 val &= ~LCPLL_POWER_DOWN_ALLOW;
9512                 I915_WRITE(LCPLL_CTL, val);
9513                 POSTING_READ(LCPLL_CTL);
9514         }
9515
9516         val = hsw_read_dcomp(dev_priv);
9517         val |= D_COMP_COMP_FORCE;
9518         val &= ~D_COMP_COMP_DISABLE;
9519         hsw_write_dcomp(dev_priv, val);
9520
9521         val = I915_READ(LCPLL_CTL);
9522         val &= ~LCPLL_PLL_DISABLE;
9523         I915_WRITE(LCPLL_CTL, val);
9524
9525         if (wait_for(I915_READ(LCPLL_CTL) & LCPLL_PLL_LOCK, 5))
9526                 DRM_ERROR("LCPLL not locked yet\n");
9527
9528         if (val & LCPLL_CD_SOURCE_FCLK) {
9529                 val = I915_READ(LCPLL_CTL);
9530                 val &= ~LCPLL_CD_SOURCE_FCLK;
9531                 I915_WRITE(LCPLL_CTL, val);
9532
9533                 if (wait_for_atomic_us((I915_READ(LCPLL_CTL) &
9534                                         LCPLL_CD_SOURCE_FCLK_DONE) == 0, 1))
9535                         DRM_ERROR("Switching back to LCPLL failed\n");
9536         }
9537
9538         intel_uncore_forcewake_put(dev_priv, FORCEWAKE_ALL);
9539         intel_update_cdclk(dev_priv->dev);
9540 }
9541
9542 /*
9543  * Package states C8 and deeper are really deep PC states that can only be
9544  * reached when all the devices on the system allow it, so even if the graphics
9545  * device allows PC8+, it doesn't mean the system will actually get to these
9546  * states. Our driver only allows PC8+ when going into runtime PM.
9547  *
9548  * The requirements for PC8+ are that all the outputs are disabled, the power
9549  * well is disabled and most interrupts are disabled, and these are also
9550  * requirements for runtime PM. When these conditions are met, we manually do
9551  * the other conditions: disable the interrupts, clocks and switch LCPLL refclk
9552  * to Fclk. If we're in PC8+ and we get an non-hotplug interrupt, we can hard
9553  * hang the machine.
9554  *
9555  * When we really reach PC8 or deeper states (not just when we allow it) we lose
9556  * the state of some registers, so when we come back from PC8+ we need to
9557  * restore this state. We don't get into PC8+ if we're not in RC6, so we don't
9558  * need to take care of the registers kept by RC6. Notice that this happens even
9559  * if we don't put the device in PCI D3 state (which is what currently happens
9560  * because of the runtime PM support).
9561  *
9562  * For more, read "Display Sequences for Package C8" on the hardware
9563  * documentation.
9564  */
9565 void hsw_enable_pc8(struct drm_i915_private *dev_priv)
9566 {
9567         struct drm_device *dev = dev_priv->dev;
9568         uint32_t val;
9569
9570         DRM_DEBUG_KMS("Enabling package C8+\n");
9571
9572         if (HAS_PCH_LPT_LP(dev)) {
9573                 val = I915_READ(SOUTH_DSPCLK_GATE_D);
9574                 val &= ~PCH_LP_PARTITION_LEVEL_DISABLE;
9575                 I915_WRITE(SOUTH_DSPCLK_GATE_D, val);
9576         }
9577
9578         lpt_disable_clkout_dp(dev);
9579         hsw_disable_lcpll(dev_priv, true, true);
9580 }
9581
9582 void hsw_disable_pc8(struct drm_i915_private *dev_priv)
9583 {
9584         struct drm_device *dev = dev_priv->dev;
9585         uint32_t val;
9586
9587         DRM_DEBUG_KMS("Disabling package C8+\n");
9588
9589         hsw_restore_lcpll(dev_priv);
9590         lpt_init_pch_refclk(dev);
9591
9592         if (HAS_PCH_LPT_LP(dev)) {
9593                 val = I915_READ(SOUTH_DSPCLK_GATE_D);
9594                 val |= PCH_LP_PARTITION_LEVEL_DISABLE;
9595                 I915_WRITE(SOUTH_DSPCLK_GATE_D, val);
9596         }
9597 }
9598
9599 static void broxton_modeset_commit_cdclk(struct drm_atomic_state *old_state)
9600 {
9601         struct drm_device *dev = old_state->dev;
9602         struct intel_atomic_state *old_intel_state =
9603                 to_intel_atomic_state(old_state);
9604         unsigned int req_cdclk = old_intel_state->dev_cdclk;
9605
9606         broxton_set_cdclk(dev, req_cdclk);
9607 }
9608
9609 /* compute the max rate for new configuration */
9610 static int ilk_max_pixel_rate(struct drm_atomic_state *state)
9611 {
9612         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
9613         struct drm_i915_private *dev_priv = state->dev->dev_private;
9614         struct drm_crtc *crtc;
9615         struct drm_crtc_state *cstate;
9616         struct intel_crtc_state *crtc_state;
9617         unsigned max_pixel_rate = 0, i;
9618         enum pipe pipe;
9619
9620         memcpy(intel_state->min_pixclk, dev_priv->min_pixclk,
9621                sizeof(intel_state->min_pixclk));
9622
9623         for_each_crtc_in_state(state, crtc, cstate, i) {
9624                 int pixel_rate;
9625
9626                 crtc_state = to_intel_crtc_state(cstate);
9627                 if (!crtc_state->base.enable) {
9628                         intel_state->min_pixclk[i] = 0;
9629                         continue;
9630                 }
9631
9632                 pixel_rate = ilk_pipe_pixel_rate(crtc_state);
9633
9634                 /* pixel rate mustn't exceed 95% of cdclk with IPS on BDW */
9635                 if (IS_BROADWELL(dev_priv) && crtc_state->ips_enabled)
9636                         pixel_rate = DIV_ROUND_UP(pixel_rate * 100, 95);
9637
9638                 intel_state->min_pixclk[i] = pixel_rate;
9639         }
9640
9641         for_each_pipe(dev_priv, pipe)
9642                 max_pixel_rate = max(intel_state->min_pixclk[pipe], max_pixel_rate);
9643
9644         return max_pixel_rate;
9645 }
9646
9647 static void broadwell_set_cdclk(struct drm_device *dev, int cdclk)
9648 {
9649         struct drm_i915_private *dev_priv = dev->dev_private;
9650         uint32_t val, data;
9651         int ret;
9652
9653         if (WARN((I915_READ(LCPLL_CTL) &
9654                   (LCPLL_PLL_DISABLE | LCPLL_PLL_LOCK |
9655                    LCPLL_CD_CLOCK_DISABLE | LCPLL_ROOT_CD_CLOCK_DISABLE |
9656                    LCPLL_CD2X_CLOCK_DISABLE | LCPLL_POWER_DOWN_ALLOW |
9657                    LCPLL_CD_SOURCE_FCLK)) != LCPLL_PLL_LOCK,
9658                  "trying to change cdclk frequency with cdclk not enabled\n"))
9659                 return;
9660
9661         mutex_lock(&dev_priv->rps.hw_lock);
9662         ret = sandybridge_pcode_write(dev_priv,
9663                                       BDW_PCODE_DISPLAY_FREQ_CHANGE_REQ, 0x0);
9664         mutex_unlock(&dev_priv->rps.hw_lock);
9665         if (ret) {
9666                 DRM_ERROR("failed to inform pcode about cdclk change\n");
9667                 return;
9668         }
9669
9670         val = I915_READ(LCPLL_CTL);
9671         val |= LCPLL_CD_SOURCE_FCLK;
9672         I915_WRITE(LCPLL_CTL, val);
9673
9674         if (wait_for_us(I915_READ(LCPLL_CTL) &
9675                         LCPLL_CD_SOURCE_FCLK_DONE, 1))
9676                 DRM_ERROR("Switching to FCLK failed\n");
9677
9678         val = I915_READ(LCPLL_CTL);
9679         val &= ~LCPLL_CLK_FREQ_MASK;
9680
9681         switch (cdclk) {
9682         case 450000:
9683                 val |= LCPLL_CLK_FREQ_450;
9684                 data = 0;
9685                 break;
9686         case 540000:
9687                 val |= LCPLL_CLK_FREQ_54O_BDW;
9688                 data = 1;
9689                 break;
9690         case 337500:
9691                 val |= LCPLL_CLK_FREQ_337_5_BDW;
9692                 data = 2;
9693                 break;
9694         case 675000:
9695                 val |= LCPLL_CLK_FREQ_675_BDW;
9696                 data = 3;
9697                 break;
9698         default:
9699                 WARN(1, "invalid cdclk frequency\n");
9700                 return;
9701         }
9702
9703         I915_WRITE(LCPLL_CTL, val);
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) == 0, 1))
9711                 DRM_ERROR("Switching back to LCPLL failed\n");
9712
9713         mutex_lock(&dev_priv->rps.hw_lock);
9714         sandybridge_pcode_write(dev_priv, HSW_PCODE_DE_WRITE_FREQ_REQ, data);
9715         mutex_unlock(&dev_priv->rps.hw_lock);
9716
9717         intel_update_cdclk(dev);
9718
9719         WARN(cdclk != dev_priv->cdclk_freq,
9720              "cdclk requested %d kHz but got %d kHz\n",
9721              cdclk, dev_priv->cdclk_freq);
9722 }
9723
9724 static int broadwell_modeset_calc_cdclk(struct drm_atomic_state *state)
9725 {
9726         struct drm_i915_private *dev_priv = to_i915(state->dev);
9727         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
9728         int max_pixclk = ilk_max_pixel_rate(state);
9729         int cdclk;
9730
9731         /*
9732          * FIXME should also account for plane ratio
9733          * once 64bpp pixel formats are supported.
9734          */
9735         if (max_pixclk > 540000)
9736                 cdclk = 675000;
9737         else if (max_pixclk > 450000)
9738                 cdclk = 540000;
9739         else if (max_pixclk > 337500)
9740                 cdclk = 450000;
9741         else
9742                 cdclk = 337500;
9743
9744         if (cdclk > dev_priv->max_cdclk_freq) {
9745                 DRM_DEBUG_KMS("requested cdclk (%d kHz) exceeds max (%d kHz)\n",
9746                               cdclk, dev_priv->max_cdclk_freq);
9747                 return -EINVAL;
9748         }
9749
9750         intel_state->cdclk = intel_state->dev_cdclk = cdclk;
9751         if (!intel_state->active_crtcs)
9752                 intel_state->dev_cdclk = 337500;
9753
9754         return 0;
9755 }
9756
9757 static void broadwell_modeset_commit_cdclk(struct drm_atomic_state *old_state)
9758 {
9759         struct drm_device *dev = old_state->dev;
9760         struct intel_atomic_state *old_intel_state =
9761                 to_intel_atomic_state(old_state);
9762         unsigned req_cdclk = old_intel_state->dev_cdclk;
9763
9764         broadwell_set_cdclk(dev, req_cdclk);
9765 }
9766
9767 static int haswell_crtc_compute_clock(struct intel_crtc *crtc,
9768                                       struct intel_crtc_state *crtc_state)
9769 {
9770         struct intel_encoder *intel_encoder =
9771                 intel_ddi_get_crtc_new_encoder(crtc_state);
9772
9773         if (intel_encoder->type != INTEL_OUTPUT_DSI) {
9774                 if (!intel_ddi_pll_select(crtc, crtc_state))
9775                         return -EINVAL;
9776         }
9777
9778         crtc->lowfreq_avail = false;
9779
9780         return 0;
9781 }
9782
9783 static void bxt_get_ddi_pll(struct drm_i915_private *dev_priv,
9784                                 enum port port,
9785                                 struct intel_crtc_state *pipe_config)
9786 {
9787         enum intel_dpll_id id;
9788
9789         switch (port) {
9790         case PORT_A:
9791                 pipe_config->ddi_pll_sel = SKL_DPLL0;
9792                 id = DPLL_ID_SKL_DPLL0;
9793                 break;
9794         case PORT_B:
9795                 pipe_config->ddi_pll_sel = SKL_DPLL1;
9796                 id = DPLL_ID_SKL_DPLL1;
9797                 break;
9798         case PORT_C:
9799                 pipe_config->ddi_pll_sel = SKL_DPLL2;
9800                 id = DPLL_ID_SKL_DPLL2;
9801                 break;
9802         default:
9803                 DRM_ERROR("Incorrect port type\n");
9804                 return;
9805         }
9806
9807         pipe_config->shared_dpll = intel_get_shared_dpll_by_id(dev_priv, id);
9808 }
9809
9810 static void skylake_get_ddi_pll(struct drm_i915_private *dev_priv,
9811                                 enum port port,
9812                                 struct intel_crtc_state *pipe_config)
9813 {
9814         enum intel_dpll_id id;
9815         u32 temp;
9816
9817         temp = I915_READ(DPLL_CTRL2) & DPLL_CTRL2_DDI_CLK_SEL_MASK(port);
9818         pipe_config->ddi_pll_sel = temp >> (port * 3 + 1);
9819
9820         switch (pipe_config->ddi_pll_sel) {
9821         case SKL_DPLL0:
9822                 id = DPLL_ID_SKL_DPLL0;
9823                 break;
9824         case SKL_DPLL1:
9825                 id = DPLL_ID_SKL_DPLL1;
9826                 break;
9827         case SKL_DPLL2:
9828                 id = DPLL_ID_SKL_DPLL2;
9829                 break;
9830         case SKL_DPLL3:
9831                 id = DPLL_ID_SKL_DPLL3;
9832                 break;
9833         default:
9834                 MISSING_CASE(pipe_config->ddi_pll_sel);
9835                 return;
9836         }
9837
9838         pipe_config->shared_dpll = intel_get_shared_dpll_by_id(dev_priv, id);
9839 }
9840
9841 static void haswell_get_ddi_pll(struct drm_i915_private *dev_priv,
9842                                 enum port port,
9843                                 struct intel_crtc_state *pipe_config)
9844 {
9845         enum intel_dpll_id id;
9846
9847         pipe_config->ddi_pll_sel = I915_READ(PORT_CLK_SEL(port));
9848
9849         switch (pipe_config->ddi_pll_sel) {
9850         case PORT_CLK_SEL_WRPLL1:
9851                 id = DPLL_ID_WRPLL1;
9852                 break;
9853         case PORT_CLK_SEL_WRPLL2:
9854                 id = DPLL_ID_WRPLL2;
9855                 break;
9856         case PORT_CLK_SEL_SPLL:
9857                 id = DPLL_ID_SPLL;
9858                 break;
9859         case PORT_CLK_SEL_LCPLL_810:
9860                 id = DPLL_ID_LCPLL_810;
9861                 break;
9862         case PORT_CLK_SEL_LCPLL_1350:
9863                 id = DPLL_ID_LCPLL_1350;
9864                 break;
9865         case PORT_CLK_SEL_LCPLL_2700:
9866                 id = DPLL_ID_LCPLL_2700;
9867                 break;
9868         default:
9869                 MISSING_CASE(pipe_config->ddi_pll_sel);
9870                 /* fall through */
9871         case PORT_CLK_SEL_NONE:
9872                 return;
9873         }
9874
9875         pipe_config->shared_dpll = intel_get_shared_dpll_by_id(dev_priv, id);
9876 }
9877
9878 static void haswell_get_ddi_port_state(struct intel_crtc *crtc,
9879                                        struct intel_crtc_state *pipe_config)
9880 {
9881         struct drm_device *dev = crtc->base.dev;
9882         struct drm_i915_private *dev_priv = dev->dev_private;
9883         struct intel_shared_dpll *pll;
9884         enum port port;
9885         uint32_t tmp;
9886
9887         tmp = I915_READ(TRANS_DDI_FUNC_CTL(pipe_config->cpu_transcoder));
9888
9889         port = (tmp & TRANS_DDI_PORT_MASK) >> TRANS_DDI_PORT_SHIFT;
9890
9891         if (IS_SKYLAKE(dev) || IS_KABYLAKE(dev))
9892                 skylake_get_ddi_pll(dev_priv, port, pipe_config);
9893         else if (IS_BROXTON(dev))
9894                 bxt_get_ddi_pll(dev_priv, port, pipe_config);
9895         else
9896                 haswell_get_ddi_pll(dev_priv, port, pipe_config);
9897
9898         pll = pipe_config->shared_dpll;
9899         if (pll) {
9900                 WARN_ON(!pll->funcs.get_hw_state(dev_priv, pll,
9901                                                  &pipe_config->dpll_hw_state));
9902         }
9903
9904         /*
9905          * Haswell has only FDI/PCH transcoder A. It is which is connected to
9906          * DDI E. So just check whether this pipe is wired to DDI E and whether
9907          * the PCH transcoder is on.
9908          */
9909         if (INTEL_INFO(dev)->gen < 9 &&
9910             (port == PORT_E) && I915_READ(LPT_TRANSCONF) & TRANS_ENABLE) {
9911                 pipe_config->has_pch_encoder = true;
9912
9913                 tmp = I915_READ(FDI_RX_CTL(PIPE_A));
9914                 pipe_config->fdi_lanes = ((FDI_DP_PORT_WIDTH_MASK & tmp) >>
9915                                           FDI_DP_PORT_WIDTH_SHIFT) + 1;
9916
9917                 ironlake_get_fdi_m_n_config(crtc, pipe_config);
9918         }
9919 }
9920
9921 static bool haswell_get_pipe_config(struct intel_crtc *crtc,
9922                                     struct intel_crtc_state *pipe_config)
9923 {
9924         struct drm_device *dev = crtc->base.dev;
9925         struct drm_i915_private *dev_priv = dev->dev_private;
9926         enum intel_display_power_domain power_domain;
9927         unsigned long power_domain_mask;
9928         uint32_t tmp;
9929         bool ret;
9930
9931         power_domain = POWER_DOMAIN_PIPE(crtc->pipe);
9932         if (!intel_display_power_get_if_enabled(dev_priv, power_domain))
9933                 return false;
9934         power_domain_mask = BIT(power_domain);
9935
9936         ret = false;
9937
9938         pipe_config->cpu_transcoder = (enum transcoder) crtc->pipe;
9939         pipe_config->shared_dpll = NULL;
9940
9941         tmp = I915_READ(TRANS_DDI_FUNC_CTL(TRANSCODER_EDP));
9942         if (tmp & TRANS_DDI_FUNC_ENABLE) {
9943                 enum pipe trans_edp_pipe;
9944                 switch (tmp & TRANS_DDI_EDP_INPUT_MASK) {
9945                 default:
9946                         WARN(1, "unknown pipe linked to edp transcoder\n");
9947                 case TRANS_DDI_EDP_INPUT_A_ONOFF:
9948                 case TRANS_DDI_EDP_INPUT_A_ON:
9949                         trans_edp_pipe = PIPE_A;
9950                         break;
9951                 case TRANS_DDI_EDP_INPUT_B_ONOFF:
9952                         trans_edp_pipe = PIPE_B;
9953                         break;
9954                 case TRANS_DDI_EDP_INPUT_C_ONOFF:
9955                         trans_edp_pipe = PIPE_C;
9956                         break;
9957                 }
9958
9959                 if (trans_edp_pipe == crtc->pipe)
9960                         pipe_config->cpu_transcoder = TRANSCODER_EDP;
9961         }
9962
9963         power_domain = POWER_DOMAIN_TRANSCODER(pipe_config->cpu_transcoder);
9964         if (!intel_display_power_get_if_enabled(dev_priv, power_domain))
9965                 goto out;
9966         power_domain_mask |= BIT(power_domain);
9967
9968         tmp = I915_READ(PIPECONF(pipe_config->cpu_transcoder));
9969         if (!(tmp & PIPECONF_ENABLE))
9970                 goto out;
9971
9972         haswell_get_ddi_port_state(crtc, pipe_config);
9973
9974         intel_get_pipe_timings(crtc, pipe_config);
9975
9976         if (INTEL_INFO(dev)->gen >= 9) {
9977                 skl_init_scalers(dev, crtc, pipe_config);
9978         }
9979
9980         if (INTEL_INFO(dev)->gen >= 9) {
9981                 pipe_config->scaler_state.scaler_id = -1;
9982                 pipe_config->scaler_state.scaler_users &= ~(1 << SKL_CRTC_INDEX);
9983         }
9984
9985         power_domain = POWER_DOMAIN_PIPE_PANEL_FITTER(crtc->pipe);
9986         if (intel_display_power_get_if_enabled(dev_priv, power_domain)) {
9987                 power_domain_mask |= BIT(power_domain);
9988                 if (INTEL_INFO(dev)->gen >= 9)
9989                         skylake_get_pfit_config(crtc, pipe_config);
9990                 else
9991                         ironlake_get_pfit_config(crtc, pipe_config);
9992         }
9993
9994         if (IS_HASWELL(dev))
9995                 pipe_config->ips_enabled = hsw_crtc_supports_ips(crtc) &&
9996                         (I915_READ(IPS_CTL) & IPS_ENABLE);
9997
9998         if (pipe_config->cpu_transcoder != TRANSCODER_EDP) {
9999                 pipe_config->pixel_multiplier =
10000                         I915_READ(PIPE_MULT(pipe_config->cpu_transcoder)) + 1;
10001         } else {
10002                 pipe_config->pixel_multiplier = 1;
10003         }
10004
10005         ret = true;
10006
10007 out:
10008         for_each_power_domain(power_domain, power_domain_mask)
10009                 intel_display_power_put(dev_priv, power_domain);
10010
10011         return ret;
10012 }
10013
10014 static void i845_update_cursor(struct drm_crtc *crtc, u32 base,
10015                                const struct intel_plane_state *plane_state)
10016 {
10017         struct drm_device *dev = crtc->dev;
10018         struct drm_i915_private *dev_priv = dev->dev_private;
10019         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
10020         uint32_t cntl = 0, size = 0;
10021
10022         if (plane_state && plane_state->visible) {
10023                 unsigned int width = plane_state->base.crtc_w;
10024                 unsigned int height = plane_state->base.crtc_h;
10025                 unsigned int stride = roundup_pow_of_two(width) * 4;
10026
10027                 switch (stride) {
10028                 default:
10029                         WARN_ONCE(1, "Invalid cursor width/stride, width=%u, stride=%u\n",
10030                                   width, stride);
10031                         stride = 256;
10032                         /* fallthrough */
10033                 case 256:
10034                 case 512:
10035                 case 1024:
10036                 case 2048:
10037                         break;
10038                 }
10039
10040                 cntl |= CURSOR_ENABLE |
10041                         CURSOR_GAMMA_ENABLE |
10042                         CURSOR_FORMAT_ARGB |
10043                         CURSOR_STRIDE(stride);
10044
10045                 size = (height << 12) | width;
10046         }
10047
10048         if (intel_crtc->cursor_cntl != 0 &&
10049             (intel_crtc->cursor_base != base ||
10050              intel_crtc->cursor_size != size ||
10051              intel_crtc->cursor_cntl != cntl)) {
10052                 /* On these chipsets we can only modify the base/size/stride
10053                  * whilst the cursor is disabled.
10054                  */
10055                 I915_WRITE(CURCNTR(PIPE_A), 0);
10056                 POSTING_READ(CURCNTR(PIPE_A));
10057                 intel_crtc->cursor_cntl = 0;
10058         }
10059
10060         if (intel_crtc->cursor_base != base) {
10061                 I915_WRITE(CURBASE(PIPE_A), base);
10062                 intel_crtc->cursor_base = base;
10063         }
10064
10065         if (intel_crtc->cursor_size != size) {
10066                 I915_WRITE(CURSIZE, size);
10067                 intel_crtc->cursor_size = size;
10068         }
10069
10070         if (intel_crtc->cursor_cntl != cntl) {
10071                 I915_WRITE(CURCNTR(PIPE_A), cntl);
10072                 POSTING_READ(CURCNTR(PIPE_A));
10073                 intel_crtc->cursor_cntl = cntl;
10074         }
10075 }
10076
10077 static void i9xx_update_cursor(struct drm_crtc *crtc, u32 base,
10078                                const struct intel_plane_state *plane_state)
10079 {
10080         struct drm_device *dev = crtc->dev;
10081         struct drm_i915_private *dev_priv = dev->dev_private;
10082         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
10083         int pipe = intel_crtc->pipe;
10084         uint32_t cntl = 0;
10085
10086         if (plane_state && plane_state->visible) {
10087                 cntl = MCURSOR_GAMMA_ENABLE;
10088                 switch (plane_state->base.crtc_w) {
10089                         case 64:
10090                                 cntl |= CURSOR_MODE_64_ARGB_AX;
10091                                 break;
10092                         case 128:
10093                                 cntl |= CURSOR_MODE_128_ARGB_AX;
10094                                 break;
10095                         case 256:
10096                                 cntl |= CURSOR_MODE_256_ARGB_AX;
10097                                 break;
10098                         default:
10099                                 MISSING_CASE(plane_state->base.crtc_w);
10100                                 return;
10101                 }
10102                 cntl |= pipe << 28; /* Connect to correct pipe */
10103
10104                 if (HAS_DDI(dev))
10105                         cntl |= CURSOR_PIPE_CSC_ENABLE;
10106
10107                 if (plane_state->base.rotation == BIT(DRM_ROTATE_180))
10108                         cntl |= CURSOR_ROTATE_180;
10109         }
10110
10111         if (intel_crtc->cursor_cntl != cntl) {
10112                 I915_WRITE(CURCNTR(pipe), cntl);
10113                 POSTING_READ(CURCNTR(pipe));
10114                 intel_crtc->cursor_cntl = cntl;
10115         }
10116
10117         /* and commit changes on next vblank */
10118         I915_WRITE(CURBASE(pipe), base);
10119         POSTING_READ(CURBASE(pipe));
10120
10121         intel_crtc->cursor_base = base;
10122 }
10123
10124 /* If no-part of the cursor is visible on the framebuffer, then the GPU may hang... */
10125 static void intel_crtc_update_cursor(struct drm_crtc *crtc,
10126                                      const struct intel_plane_state *plane_state)
10127 {
10128         struct drm_device *dev = crtc->dev;
10129         struct drm_i915_private *dev_priv = dev->dev_private;
10130         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
10131         int pipe = intel_crtc->pipe;
10132         u32 base = intel_crtc->cursor_addr;
10133         u32 pos = 0;
10134
10135         if (plane_state) {
10136                 int x = plane_state->base.crtc_x;
10137                 int y = plane_state->base.crtc_y;
10138
10139                 if (x < 0) {
10140                         pos |= CURSOR_POS_SIGN << CURSOR_X_SHIFT;
10141                         x = -x;
10142                 }
10143                 pos |= x << CURSOR_X_SHIFT;
10144
10145                 if (y < 0) {
10146                         pos |= CURSOR_POS_SIGN << CURSOR_Y_SHIFT;
10147                         y = -y;
10148                 }
10149                 pos |= y << CURSOR_Y_SHIFT;
10150
10151                 /* ILK+ do this automagically */
10152                 if (HAS_GMCH_DISPLAY(dev) &&
10153                     plane_state->base.rotation == BIT(DRM_ROTATE_180)) {
10154                         base += (plane_state->base.crtc_h *
10155                                  plane_state->base.crtc_w - 1) * 4;
10156                 }
10157         }
10158
10159         I915_WRITE(CURPOS(pipe), pos);
10160
10161         if (IS_845G(dev) || IS_I865G(dev))
10162                 i845_update_cursor(crtc, base, plane_state);
10163         else
10164                 i9xx_update_cursor(crtc, base, plane_state);
10165 }
10166
10167 static bool cursor_size_ok(struct drm_device *dev,
10168                            uint32_t width, uint32_t height)
10169 {
10170         if (width == 0 || height == 0)
10171                 return false;
10172
10173         /*
10174          * 845g/865g are special in that they are only limited by
10175          * the width of their cursors, the height is arbitrary up to
10176          * the precision of the register. Everything else requires
10177          * square cursors, limited to a few power-of-two sizes.
10178          */
10179         if (IS_845G(dev) || IS_I865G(dev)) {
10180                 if ((width & 63) != 0)
10181                         return false;
10182
10183                 if (width > (IS_845G(dev) ? 64 : 512))
10184                         return false;
10185
10186                 if (height > 1023)
10187                         return false;
10188         } else {
10189                 switch (width | height) {
10190                 case 256:
10191                 case 128:
10192                         if (IS_GEN2(dev))
10193                                 return false;
10194                 case 64:
10195                         break;
10196                 default:
10197                         return false;
10198                 }
10199         }
10200
10201         return true;
10202 }
10203
10204 static void intel_crtc_gamma_set(struct drm_crtc *crtc, u16 *red, u16 *green,
10205                                  u16 *blue, uint32_t start, uint32_t size)
10206 {
10207         int end = (start + size > 256) ? 256 : start + size, i;
10208         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
10209
10210         for (i = start; i < end; i++) {
10211                 intel_crtc->lut_r[i] = red[i] >> 8;
10212                 intel_crtc->lut_g[i] = green[i] >> 8;
10213                 intel_crtc->lut_b[i] = blue[i] >> 8;
10214         }
10215
10216         intel_crtc_load_lut(crtc);
10217 }
10218
10219 /* VESA 640x480x72Hz mode to set on the pipe */
10220 static struct drm_display_mode load_detect_mode = {
10221         DRM_MODE("640x480", DRM_MODE_TYPE_DEFAULT, 31500, 640, 664,
10222                  704, 832, 0, 480, 489, 491, 520, 0, DRM_MODE_FLAG_NHSYNC | DRM_MODE_FLAG_NVSYNC),
10223 };
10224
10225 struct drm_framebuffer *
10226 __intel_framebuffer_create(struct drm_device *dev,
10227                            struct drm_mode_fb_cmd2 *mode_cmd,
10228                            struct drm_i915_gem_object *obj)
10229 {
10230         struct intel_framebuffer *intel_fb;
10231         int ret;
10232
10233         intel_fb = kzalloc(sizeof(*intel_fb), GFP_KERNEL);
10234         if (!intel_fb)
10235                 return ERR_PTR(-ENOMEM);
10236
10237         ret = intel_framebuffer_init(dev, intel_fb, mode_cmd, obj);
10238         if (ret)
10239                 goto err;
10240
10241         return &intel_fb->base;
10242
10243 err:
10244         kfree(intel_fb);
10245         return ERR_PTR(ret);
10246 }
10247
10248 static struct drm_framebuffer *
10249 intel_framebuffer_create(struct drm_device *dev,
10250                          struct drm_mode_fb_cmd2 *mode_cmd,
10251                          struct drm_i915_gem_object *obj)
10252 {
10253         struct drm_framebuffer *fb;
10254         int ret;
10255
10256         ret = i915_mutex_lock_interruptible(dev);
10257         if (ret)
10258                 return ERR_PTR(ret);
10259         fb = __intel_framebuffer_create(dev, mode_cmd, obj);
10260         mutex_unlock(&dev->struct_mutex);
10261
10262         return fb;
10263 }
10264
10265 static u32
10266 intel_framebuffer_pitch_for_width(int width, int bpp)
10267 {
10268         u32 pitch = DIV_ROUND_UP(width * bpp, 8);
10269         return ALIGN(pitch, 64);
10270 }
10271
10272 static u32
10273 intel_framebuffer_size_for_mode(struct drm_display_mode *mode, int bpp)
10274 {
10275         u32 pitch = intel_framebuffer_pitch_for_width(mode->hdisplay, bpp);
10276         return PAGE_ALIGN(pitch * mode->vdisplay);
10277 }
10278
10279 static struct drm_framebuffer *
10280 intel_framebuffer_create_for_mode(struct drm_device *dev,
10281                                   struct drm_display_mode *mode,
10282                                   int depth, int bpp)
10283 {
10284         struct drm_framebuffer *fb;
10285         struct drm_i915_gem_object *obj;
10286         struct drm_mode_fb_cmd2 mode_cmd = { 0 };
10287
10288         obj = i915_gem_alloc_object(dev,
10289                                     intel_framebuffer_size_for_mode(mode, bpp));
10290         if (obj == NULL)
10291                 return ERR_PTR(-ENOMEM);
10292
10293         mode_cmd.width = mode->hdisplay;
10294         mode_cmd.height = mode->vdisplay;
10295         mode_cmd.pitches[0] = intel_framebuffer_pitch_for_width(mode_cmd.width,
10296                                                                 bpp);
10297         mode_cmd.pixel_format = drm_mode_legacy_fb_format(bpp, depth);
10298
10299         fb = intel_framebuffer_create(dev, &mode_cmd, obj);
10300         if (IS_ERR(fb))
10301                 drm_gem_object_unreference_unlocked(&obj->base);
10302
10303         return fb;
10304 }
10305
10306 static struct drm_framebuffer *
10307 mode_fits_in_fbdev(struct drm_device *dev,
10308                    struct drm_display_mode *mode)
10309 {
10310 #ifdef CONFIG_DRM_FBDEV_EMULATION
10311         struct drm_i915_private *dev_priv = dev->dev_private;
10312         struct drm_i915_gem_object *obj;
10313         struct drm_framebuffer *fb;
10314
10315         if (!dev_priv->fbdev)
10316                 return NULL;
10317
10318         if (!dev_priv->fbdev->fb)
10319                 return NULL;
10320
10321         obj = dev_priv->fbdev->fb->obj;
10322         BUG_ON(!obj);
10323
10324         fb = &dev_priv->fbdev->fb->base;
10325         if (fb->pitches[0] < intel_framebuffer_pitch_for_width(mode->hdisplay,
10326                                                                fb->bits_per_pixel))
10327                 return NULL;
10328
10329         if (obj->base.size < mode->vdisplay * fb->pitches[0])
10330                 return NULL;
10331
10332         drm_framebuffer_reference(fb);
10333         return fb;
10334 #else
10335         return NULL;
10336 #endif
10337 }
10338
10339 static int intel_modeset_setup_plane_state(struct drm_atomic_state *state,
10340                                            struct drm_crtc *crtc,
10341                                            struct drm_display_mode *mode,
10342                                            struct drm_framebuffer *fb,
10343                                            int x, int y)
10344 {
10345         struct drm_plane_state *plane_state;
10346         int hdisplay, vdisplay;
10347         int ret;
10348
10349         plane_state = drm_atomic_get_plane_state(state, crtc->primary);
10350         if (IS_ERR(plane_state))
10351                 return PTR_ERR(plane_state);
10352
10353         if (mode)
10354                 drm_crtc_get_hv_timing(mode, &hdisplay, &vdisplay);
10355         else
10356                 hdisplay = vdisplay = 0;
10357
10358         ret = drm_atomic_set_crtc_for_plane(plane_state, fb ? crtc : NULL);
10359         if (ret)
10360                 return ret;
10361         drm_atomic_set_fb_for_plane(plane_state, fb);
10362         plane_state->crtc_x = 0;
10363         plane_state->crtc_y = 0;
10364         plane_state->crtc_w = hdisplay;
10365         plane_state->crtc_h = vdisplay;
10366         plane_state->src_x = x << 16;
10367         plane_state->src_y = y << 16;
10368         plane_state->src_w = hdisplay << 16;
10369         plane_state->src_h = vdisplay << 16;
10370
10371         return 0;
10372 }
10373
10374 bool intel_get_load_detect_pipe(struct drm_connector *connector,
10375                                 struct drm_display_mode *mode,
10376                                 struct intel_load_detect_pipe *old,
10377                                 struct drm_modeset_acquire_ctx *ctx)
10378 {
10379         struct intel_crtc *intel_crtc;
10380         struct intel_encoder *intel_encoder =
10381                 intel_attached_encoder(connector);
10382         struct drm_crtc *possible_crtc;
10383         struct drm_encoder *encoder = &intel_encoder->base;
10384         struct drm_crtc *crtc = NULL;
10385         struct drm_device *dev = encoder->dev;
10386         struct drm_framebuffer *fb;
10387         struct drm_mode_config *config = &dev->mode_config;
10388         struct drm_atomic_state *state = NULL, *restore_state = NULL;
10389         struct drm_connector_state *connector_state;
10390         struct intel_crtc_state *crtc_state;
10391         int ret, i = -1;
10392
10393         DRM_DEBUG_KMS("[CONNECTOR:%d:%s], [ENCODER:%d:%s]\n",
10394                       connector->base.id, connector->name,
10395                       encoder->base.id, encoder->name);
10396
10397         old->restore_state = NULL;
10398
10399 retry:
10400         ret = drm_modeset_lock(&config->connection_mutex, ctx);
10401         if (ret)
10402                 goto fail;
10403
10404         /*
10405          * Algorithm gets a little messy:
10406          *
10407          *   - if the connector already has an assigned crtc, use it (but make
10408          *     sure it's on first)
10409          *
10410          *   - try to find the first unused crtc that can drive this connector,
10411          *     and use that if we find one
10412          */
10413
10414         /* See if we already have a CRTC for this connector */
10415         if (connector->state->crtc) {
10416                 crtc = connector->state->crtc;
10417
10418                 ret = drm_modeset_lock(&crtc->mutex, ctx);
10419                 if (ret)
10420                         goto fail;
10421
10422                 /* Make sure the crtc and connector are running */
10423                 goto found;
10424         }
10425
10426         /* Find an unused one (if possible) */
10427         for_each_crtc(dev, possible_crtc) {
10428                 i++;
10429                 if (!(encoder->possible_crtcs & (1 << i)))
10430                         continue;
10431
10432                 ret = drm_modeset_lock(&possible_crtc->mutex, ctx);
10433                 if (ret)
10434                         goto fail;
10435
10436                 if (possible_crtc->state->enable) {
10437                         drm_modeset_unlock(&possible_crtc->mutex);
10438                         continue;
10439                 }
10440
10441                 crtc = possible_crtc;
10442                 break;
10443         }
10444
10445         /*
10446          * If we didn't find an unused CRTC, don't use any.
10447          */
10448         if (!crtc) {
10449                 DRM_DEBUG_KMS("no pipe available for load-detect\n");
10450                 goto fail;
10451         }
10452
10453 found:
10454         intel_crtc = to_intel_crtc(crtc);
10455
10456         ret = drm_modeset_lock(&crtc->primary->mutex, ctx);
10457         if (ret)
10458                 goto fail;
10459
10460         state = drm_atomic_state_alloc(dev);
10461         restore_state = drm_atomic_state_alloc(dev);
10462         if (!state || !restore_state) {
10463                 ret = -ENOMEM;
10464                 goto fail;
10465         }
10466
10467         state->acquire_ctx = ctx;
10468         restore_state->acquire_ctx = ctx;
10469
10470         connector_state = drm_atomic_get_connector_state(state, connector);
10471         if (IS_ERR(connector_state)) {
10472                 ret = PTR_ERR(connector_state);
10473                 goto fail;
10474         }
10475
10476         ret = drm_atomic_set_crtc_for_connector(connector_state, crtc);
10477         if (ret)
10478                 goto fail;
10479
10480         crtc_state = intel_atomic_get_crtc_state(state, intel_crtc);
10481         if (IS_ERR(crtc_state)) {
10482                 ret = PTR_ERR(crtc_state);
10483                 goto fail;
10484         }
10485
10486         crtc_state->base.active = crtc_state->base.enable = true;
10487
10488         if (!mode)
10489                 mode = &load_detect_mode;
10490
10491         /* We need a framebuffer large enough to accommodate all accesses
10492          * that the plane may generate whilst we perform load detection.
10493          * We can not rely on the fbcon either being present (we get called
10494          * during its initialisation to detect all boot displays, or it may
10495          * not even exist) or that it is large enough to satisfy the
10496          * requested mode.
10497          */
10498         fb = mode_fits_in_fbdev(dev, mode);
10499         if (fb == NULL) {
10500                 DRM_DEBUG_KMS("creating tmp fb for load-detection\n");
10501                 fb = intel_framebuffer_create_for_mode(dev, mode, 24, 32);
10502         } else
10503                 DRM_DEBUG_KMS("reusing fbdev for load-detection framebuffer\n");
10504         if (IS_ERR(fb)) {
10505                 DRM_DEBUG_KMS("failed to allocate framebuffer for load-detection\n");
10506                 goto fail;
10507         }
10508
10509         ret = intel_modeset_setup_plane_state(state, crtc, mode, fb, 0, 0);
10510         if (ret)
10511                 goto fail;
10512
10513         drm_framebuffer_unreference(fb);
10514
10515         ret = drm_atomic_set_mode_for_crtc(&crtc_state->base, mode);
10516         if (ret)
10517                 goto fail;
10518
10519         ret = PTR_ERR_OR_ZERO(drm_atomic_get_connector_state(restore_state, connector));
10520         if (!ret)
10521                 ret = PTR_ERR_OR_ZERO(drm_atomic_get_crtc_state(restore_state, crtc));
10522         if (!ret)
10523                 ret = PTR_ERR_OR_ZERO(drm_atomic_get_plane_state(restore_state, crtc->primary));
10524         if (ret) {
10525                 DRM_DEBUG_KMS("Failed to create a copy of old state to restore: %i\n", ret);
10526                 goto fail;
10527         }
10528
10529         ret = drm_atomic_commit(state);
10530         if (ret) {
10531                 DRM_DEBUG_KMS("failed to set mode on load-detect pipe\n");
10532                 goto fail;
10533         }
10534
10535         old->restore_state = restore_state;
10536
10537         /* let the connector get through one full cycle before testing */
10538         intel_wait_for_vblank(dev, intel_crtc->pipe);
10539         return true;
10540
10541 fail:
10542         drm_atomic_state_free(state);
10543         drm_atomic_state_free(restore_state);
10544         restore_state = state = NULL;
10545
10546         if (ret == -EDEADLK) {
10547                 drm_modeset_backoff(ctx);
10548                 goto retry;
10549         }
10550
10551         return false;
10552 }
10553
10554 void intel_release_load_detect_pipe(struct drm_connector *connector,
10555                                     struct intel_load_detect_pipe *old,
10556                                     struct drm_modeset_acquire_ctx *ctx)
10557 {
10558         struct intel_encoder *intel_encoder =
10559                 intel_attached_encoder(connector);
10560         struct drm_encoder *encoder = &intel_encoder->base;
10561         struct drm_atomic_state *state = old->restore_state;
10562         int ret;
10563
10564         DRM_DEBUG_KMS("[CONNECTOR:%d:%s], [ENCODER:%d:%s]\n",
10565                       connector->base.id, connector->name,
10566                       encoder->base.id, encoder->name);
10567
10568         if (!state)
10569                 return;
10570
10571         ret = drm_atomic_commit(state);
10572         if (ret) {
10573                 DRM_DEBUG_KMS("Couldn't release load detect pipe: %i\n", ret);
10574                 drm_atomic_state_free(state);
10575         }
10576 }
10577
10578 static int i9xx_pll_refclk(struct drm_device *dev,
10579                            const struct intel_crtc_state *pipe_config)
10580 {
10581         struct drm_i915_private *dev_priv = dev->dev_private;
10582         u32 dpll = pipe_config->dpll_hw_state.dpll;
10583
10584         if ((dpll & PLL_REF_INPUT_MASK) == PLLB_REF_INPUT_SPREADSPECTRUMIN)
10585                 return dev_priv->vbt.lvds_ssc_freq;
10586         else if (HAS_PCH_SPLIT(dev))
10587                 return 120000;
10588         else if (!IS_GEN2(dev))
10589                 return 96000;
10590         else
10591                 return 48000;
10592 }
10593
10594 /* Returns the clock of the currently programmed mode of the given pipe. */
10595 static void i9xx_crtc_clock_get(struct intel_crtc *crtc,
10596                                 struct intel_crtc_state *pipe_config)
10597 {
10598         struct drm_device *dev = crtc->base.dev;
10599         struct drm_i915_private *dev_priv = dev->dev_private;
10600         int pipe = pipe_config->cpu_transcoder;
10601         u32 dpll = pipe_config->dpll_hw_state.dpll;
10602         u32 fp;
10603         intel_clock_t clock;
10604         int port_clock;
10605         int refclk = i9xx_pll_refclk(dev, pipe_config);
10606
10607         if ((dpll & DISPLAY_RATE_SELECT_FPA1) == 0)
10608                 fp = pipe_config->dpll_hw_state.fp0;
10609         else
10610                 fp = pipe_config->dpll_hw_state.fp1;
10611
10612         clock.m1 = (fp & FP_M1_DIV_MASK) >> FP_M1_DIV_SHIFT;
10613         if (IS_PINEVIEW(dev)) {
10614                 clock.n = ffs((fp & FP_N_PINEVIEW_DIV_MASK) >> FP_N_DIV_SHIFT) - 1;
10615                 clock.m2 = (fp & FP_M2_PINEVIEW_DIV_MASK) >> FP_M2_DIV_SHIFT;
10616         } else {
10617                 clock.n = (fp & FP_N_DIV_MASK) >> FP_N_DIV_SHIFT;
10618                 clock.m2 = (fp & FP_M2_DIV_MASK) >> FP_M2_DIV_SHIFT;
10619         }
10620
10621         if (!IS_GEN2(dev)) {
10622                 if (IS_PINEVIEW(dev))
10623                         clock.p1 = ffs((dpll & DPLL_FPA01_P1_POST_DIV_MASK_PINEVIEW) >>
10624                                 DPLL_FPA01_P1_POST_DIV_SHIFT_PINEVIEW);
10625                 else
10626                         clock.p1 = ffs((dpll & DPLL_FPA01_P1_POST_DIV_MASK) >>
10627                                DPLL_FPA01_P1_POST_DIV_SHIFT);
10628
10629                 switch (dpll & DPLL_MODE_MASK) {
10630                 case DPLLB_MODE_DAC_SERIAL:
10631                         clock.p2 = dpll & DPLL_DAC_SERIAL_P2_CLOCK_DIV_5 ?
10632                                 5 : 10;
10633                         break;
10634                 case DPLLB_MODE_LVDS:
10635                         clock.p2 = dpll & DPLLB_LVDS_P2_CLOCK_DIV_7 ?
10636                                 7 : 14;
10637                         break;
10638                 default:
10639                         DRM_DEBUG_KMS("Unknown DPLL mode %08x in programmed "
10640                                   "mode\n", (int)(dpll & DPLL_MODE_MASK));
10641                         return;
10642                 }
10643
10644                 if (IS_PINEVIEW(dev))
10645                         port_clock = pnv_calc_dpll_params(refclk, &clock);
10646                 else
10647                         port_clock = i9xx_calc_dpll_params(refclk, &clock);
10648         } else {
10649                 u32 lvds = IS_I830(dev) ? 0 : I915_READ(LVDS);
10650                 bool is_lvds = (pipe == 1) && (lvds & LVDS_PORT_EN);
10651
10652                 if (is_lvds) {
10653                         clock.p1 = ffs((dpll & DPLL_FPA01_P1_POST_DIV_MASK_I830_LVDS) >>
10654                                        DPLL_FPA01_P1_POST_DIV_SHIFT);
10655
10656                         if (lvds & LVDS_CLKB_POWER_UP)
10657                                 clock.p2 = 7;
10658                         else
10659                                 clock.p2 = 14;
10660                 } else {
10661                         if (dpll & PLL_P1_DIVIDE_BY_TWO)
10662                                 clock.p1 = 2;
10663                         else {
10664                                 clock.p1 = ((dpll & DPLL_FPA01_P1_POST_DIV_MASK_I830) >>
10665                                             DPLL_FPA01_P1_POST_DIV_SHIFT) + 2;
10666                         }
10667                         if (dpll & PLL_P2_DIVIDE_BY_4)
10668                                 clock.p2 = 4;
10669                         else
10670                                 clock.p2 = 2;
10671                 }
10672
10673                 port_clock = i9xx_calc_dpll_params(refclk, &clock);
10674         }
10675
10676         /*
10677          * This value includes pixel_multiplier. We will use
10678          * port_clock to compute adjusted_mode.crtc_clock in the
10679          * encoder's get_config() function.
10680          */
10681         pipe_config->port_clock = port_clock;
10682 }
10683
10684 int intel_dotclock_calculate(int link_freq,
10685                              const struct intel_link_m_n *m_n)
10686 {
10687         /*
10688          * The calculation for the data clock is:
10689          * pixel_clock = ((m/n)*(link_clock * nr_lanes))/bpp
10690          * But we want to avoid losing precison if possible, so:
10691          * pixel_clock = ((m * link_clock * nr_lanes)/(n*bpp))
10692          *
10693          * and the link clock is simpler:
10694          * link_clock = (m * link_clock) / n
10695          */
10696
10697         if (!m_n->link_n)
10698                 return 0;
10699
10700         return div_u64((u64)m_n->link_m * link_freq, m_n->link_n);
10701 }
10702
10703 static void ironlake_pch_clock_get(struct intel_crtc *crtc,
10704                                    struct intel_crtc_state *pipe_config)
10705 {
10706         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
10707
10708         /* read out port_clock from the DPLL */
10709         i9xx_crtc_clock_get(crtc, pipe_config);
10710
10711         /*
10712          * In case there is an active pipe without active ports,
10713          * we may need some idea for the dotclock anyway.
10714          * Calculate one based on the FDI configuration.
10715          */
10716         pipe_config->base.adjusted_mode.crtc_clock =
10717                 intel_dotclock_calculate(intel_fdi_link_freq(dev_priv, pipe_config),
10718                                          &pipe_config->fdi_m_n);
10719 }
10720
10721 /** Returns the currently programmed mode of the given pipe. */
10722 struct drm_display_mode *intel_crtc_mode_get(struct drm_device *dev,
10723                                              struct drm_crtc *crtc)
10724 {
10725         struct drm_i915_private *dev_priv = dev->dev_private;
10726         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
10727         enum transcoder cpu_transcoder = intel_crtc->config->cpu_transcoder;
10728         struct drm_display_mode *mode;
10729         struct intel_crtc_state *pipe_config;
10730         int htot = I915_READ(HTOTAL(cpu_transcoder));
10731         int hsync = I915_READ(HSYNC(cpu_transcoder));
10732         int vtot = I915_READ(VTOTAL(cpu_transcoder));
10733         int vsync = I915_READ(VSYNC(cpu_transcoder));
10734         enum pipe pipe = intel_crtc->pipe;
10735
10736         mode = kzalloc(sizeof(*mode), GFP_KERNEL);
10737         if (!mode)
10738                 return NULL;
10739
10740         pipe_config = kzalloc(sizeof(*pipe_config), GFP_KERNEL);
10741         if (!pipe_config) {
10742                 kfree(mode);
10743                 return NULL;
10744         }
10745
10746         /*
10747          * Construct a pipe_config sufficient for getting the clock info
10748          * back out of crtc_clock_get.
10749          *
10750          * Note, if LVDS ever uses a non-1 pixel multiplier, we'll need
10751          * to use a real value here instead.
10752          */
10753         pipe_config->cpu_transcoder = (enum transcoder) pipe;
10754         pipe_config->pixel_multiplier = 1;
10755         pipe_config->dpll_hw_state.dpll = I915_READ(DPLL(pipe));
10756         pipe_config->dpll_hw_state.fp0 = I915_READ(FP0(pipe));
10757         pipe_config->dpll_hw_state.fp1 = I915_READ(FP1(pipe));
10758         i9xx_crtc_clock_get(intel_crtc, pipe_config);
10759
10760         mode->clock = pipe_config->port_clock / pipe_config->pixel_multiplier;
10761         mode->hdisplay = (htot & 0xffff) + 1;
10762         mode->htotal = ((htot & 0xffff0000) >> 16) + 1;
10763         mode->hsync_start = (hsync & 0xffff) + 1;
10764         mode->hsync_end = ((hsync & 0xffff0000) >> 16) + 1;
10765         mode->vdisplay = (vtot & 0xffff) + 1;
10766         mode->vtotal = ((vtot & 0xffff0000) >> 16) + 1;
10767         mode->vsync_start = (vsync & 0xffff) + 1;
10768         mode->vsync_end = ((vsync & 0xffff0000) >> 16) + 1;
10769
10770         drm_mode_set_name(mode);
10771
10772         kfree(pipe_config);
10773
10774         return mode;
10775 }
10776
10777 void intel_mark_busy(struct drm_device *dev)
10778 {
10779         struct drm_i915_private *dev_priv = dev->dev_private;
10780
10781         if (dev_priv->mm.busy)
10782                 return;
10783
10784         intel_runtime_pm_get(dev_priv);
10785         i915_update_gfx_val(dev_priv);
10786         if (INTEL_INFO(dev)->gen >= 6)
10787                 gen6_rps_busy(dev_priv);
10788         dev_priv->mm.busy = true;
10789 }
10790
10791 void intel_mark_idle(struct drm_device *dev)
10792 {
10793         struct drm_i915_private *dev_priv = dev->dev_private;
10794
10795         if (!dev_priv->mm.busy)
10796                 return;
10797
10798         dev_priv->mm.busy = false;
10799
10800         if (INTEL_INFO(dev)->gen >= 6)
10801                 gen6_rps_idle(dev->dev_private);
10802
10803         intel_runtime_pm_put(dev_priv);
10804 }
10805
10806 static void intel_crtc_destroy(struct drm_crtc *crtc)
10807 {
10808         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
10809         struct drm_device *dev = crtc->dev;
10810         struct intel_unpin_work *work;
10811
10812         spin_lock_irq(&dev->event_lock);
10813         work = intel_crtc->unpin_work;
10814         intel_crtc->unpin_work = NULL;
10815         spin_unlock_irq(&dev->event_lock);
10816
10817         if (work) {
10818                 cancel_work_sync(&work->work);
10819                 kfree(work);
10820         }
10821
10822         drm_crtc_cleanup(crtc);
10823
10824         kfree(intel_crtc);
10825 }
10826
10827 static void intel_unpin_work_fn(struct work_struct *__work)
10828 {
10829         struct intel_unpin_work *work =
10830                 container_of(__work, struct intel_unpin_work, work);
10831         struct intel_crtc *crtc = to_intel_crtc(work->crtc);
10832         struct drm_device *dev = crtc->base.dev;
10833         struct drm_plane *primary = crtc->base.primary;
10834
10835         mutex_lock(&dev->struct_mutex);
10836         intel_unpin_fb_obj(work->old_fb, primary->state->rotation);
10837         drm_gem_object_unreference(&work->pending_flip_obj->base);
10838
10839         if (work->flip_queued_req)
10840                 i915_gem_request_assign(&work->flip_queued_req, NULL);
10841         mutex_unlock(&dev->struct_mutex);
10842
10843         intel_frontbuffer_flip_complete(dev, to_intel_plane(primary)->frontbuffer_bit);
10844         intel_fbc_post_update(crtc);
10845         drm_framebuffer_unreference(work->old_fb);
10846
10847         BUG_ON(atomic_read(&crtc->unpin_work_count) == 0);
10848         atomic_dec(&crtc->unpin_work_count);
10849
10850         kfree(work);
10851 }
10852
10853 static void do_intel_finish_page_flip(struct drm_device *dev,
10854                                       struct drm_crtc *crtc)
10855 {
10856         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
10857         struct intel_unpin_work *work;
10858         unsigned long flags;
10859
10860         /* Ignore early vblank irqs */
10861         if (intel_crtc == NULL)
10862                 return;
10863
10864         /*
10865          * This is called both by irq handlers and the reset code (to complete
10866          * lost pageflips) so needs the full irqsave spinlocks.
10867          */
10868         spin_lock_irqsave(&dev->event_lock, flags);
10869         work = intel_crtc->unpin_work;
10870
10871         /* Ensure we don't miss a work->pending update ... */
10872         smp_rmb();
10873
10874         if (work == NULL || atomic_read(&work->pending) < INTEL_FLIP_COMPLETE) {
10875                 spin_unlock_irqrestore(&dev->event_lock, flags);
10876                 return;
10877         }
10878
10879         page_flip_completed(intel_crtc);
10880
10881         spin_unlock_irqrestore(&dev->event_lock, flags);
10882 }
10883
10884 void intel_finish_page_flip(struct drm_device *dev, int pipe)
10885 {
10886         struct drm_i915_private *dev_priv = dev->dev_private;
10887         struct drm_crtc *crtc = dev_priv->pipe_to_crtc_mapping[pipe];
10888
10889         do_intel_finish_page_flip(dev, crtc);
10890 }
10891
10892 void intel_finish_page_flip_plane(struct drm_device *dev, int plane)
10893 {
10894         struct drm_i915_private *dev_priv = dev->dev_private;
10895         struct drm_crtc *crtc = dev_priv->plane_to_crtc_mapping[plane];
10896
10897         do_intel_finish_page_flip(dev, crtc);
10898 }
10899
10900 /* Is 'a' after or equal to 'b'? */
10901 static bool g4x_flip_count_after_eq(u32 a, u32 b)
10902 {
10903         return !((a - b) & 0x80000000);
10904 }
10905
10906 static bool page_flip_finished(struct intel_crtc *crtc)
10907 {
10908         struct drm_device *dev = crtc->base.dev;
10909         struct drm_i915_private *dev_priv = dev->dev_private;
10910
10911         if (i915_reset_in_progress(&dev_priv->gpu_error) ||
10912             crtc->reset_counter != atomic_read(&dev_priv->gpu_error.reset_counter))
10913                 return true;
10914
10915         /*
10916          * The relevant registers doen't exist on pre-ctg.
10917          * As the flip done interrupt doesn't trigger for mmio
10918          * flips on gmch platforms, a flip count check isn't
10919          * really needed there. But since ctg has the registers,
10920          * include it in the check anyway.
10921          */
10922         if (INTEL_INFO(dev)->gen < 5 && !IS_G4X(dev))
10923                 return true;
10924
10925         /*
10926          * BDW signals flip done immediately if the plane
10927          * is disabled, even if the plane enable is already
10928          * armed to occur at the next vblank :(
10929          */
10930
10931         /*
10932          * A DSPSURFLIVE check isn't enough in case the mmio and CS flips
10933          * used the same base address. In that case the mmio flip might
10934          * have completed, but the CS hasn't even executed the flip yet.
10935          *
10936          * A flip count check isn't enough as the CS might have updated
10937          * the base address just after start of vblank, but before we
10938          * managed to process the interrupt. This means we'd complete the
10939          * CS flip too soon.
10940          *
10941          * Combining both checks should get us a good enough result. It may
10942          * still happen that the CS flip has been executed, but has not
10943          * yet actually completed. But in case the base address is the same
10944          * anyway, we don't really care.
10945          */
10946         return (I915_READ(DSPSURFLIVE(crtc->plane)) & ~0xfff) ==
10947                 crtc->unpin_work->gtt_offset &&
10948                 g4x_flip_count_after_eq(I915_READ(PIPE_FLIPCOUNT_G4X(crtc->pipe)),
10949                                     crtc->unpin_work->flip_count);
10950 }
10951
10952 void intel_prepare_page_flip(struct drm_device *dev, int plane)
10953 {
10954         struct drm_i915_private *dev_priv = dev->dev_private;
10955         struct intel_crtc *intel_crtc =
10956                 to_intel_crtc(dev_priv->plane_to_crtc_mapping[plane]);
10957         unsigned long flags;
10958
10959
10960         /*
10961          * This is called both by irq handlers and the reset code (to complete
10962          * lost pageflips) so needs the full irqsave spinlocks.
10963          *
10964          * NB: An MMIO update of the plane base pointer will also
10965          * generate a page-flip completion irq, i.e. every modeset
10966          * is also accompanied by a spurious intel_prepare_page_flip().
10967          */
10968         spin_lock_irqsave(&dev->event_lock, flags);
10969         if (intel_crtc->unpin_work && page_flip_finished(intel_crtc))
10970                 atomic_inc_not_zero(&intel_crtc->unpin_work->pending);
10971         spin_unlock_irqrestore(&dev->event_lock, flags);
10972 }
10973
10974 static inline void intel_mark_page_flip_active(struct intel_unpin_work *work)
10975 {
10976         /* Ensure that the work item is consistent when activating it ... */
10977         smp_wmb();
10978         atomic_set(&work->pending, INTEL_FLIP_PENDING);
10979         /* and that it is marked active as soon as the irq could fire. */
10980         smp_wmb();
10981 }
10982
10983 static int intel_gen2_queue_flip(struct drm_device *dev,
10984                                  struct drm_crtc *crtc,
10985                                  struct drm_framebuffer *fb,
10986                                  struct drm_i915_gem_object *obj,
10987                                  struct drm_i915_gem_request *req,
10988                                  uint32_t flags)
10989 {
10990         struct intel_engine_cs *engine = req->engine;
10991         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
10992         u32 flip_mask;
10993         int ret;
10994
10995         ret = intel_ring_begin(req, 6);
10996         if (ret)
10997                 return ret;
10998
10999         /* Can't queue multiple flips, so wait for the previous
11000          * one to finish before executing the next.
11001          */
11002         if (intel_crtc->plane)
11003                 flip_mask = MI_WAIT_FOR_PLANE_B_FLIP;
11004         else
11005                 flip_mask = MI_WAIT_FOR_PLANE_A_FLIP;
11006         intel_ring_emit(engine, MI_WAIT_FOR_EVENT | flip_mask);
11007         intel_ring_emit(engine, MI_NOOP);
11008         intel_ring_emit(engine, MI_DISPLAY_FLIP |
11009                         MI_DISPLAY_FLIP_PLANE(intel_crtc->plane));
11010         intel_ring_emit(engine, fb->pitches[0]);
11011         intel_ring_emit(engine, intel_crtc->unpin_work->gtt_offset);
11012         intel_ring_emit(engine, 0); /* aux display base address, unused */
11013
11014         intel_mark_page_flip_active(intel_crtc->unpin_work);
11015         return 0;
11016 }
11017
11018 static int intel_gen3_queue_flip(struct drm_device *dev,
11019                                  struct drm_crtc *crtc,
11020                                  struct drm_framebuffer *fb,
11021                                  struct drm_i915_gem_object *obj,
11022                                  struct drm_i915_gem_request *req,
11023                                  uint32_t flags)
11024 {
11025         struct intel_engine_cs *engine = req->engine;
11026         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
11027         u32 flip_mask;
11028         int ret;
11029
11030         ret = intel_ring_begin(req, 6);
11031         if (ret)
11032                 return ret;
11033
11034         if (intel_crtc->plane)
11035                 flip_mask = MI_WAIT_FOR_PLANE_B_FLIP;
11036         else
11037                 flip_mask = MI_WAIT_FOR_PLANE_A_FLIP;
11038         intel_ring_emit(engine, MI_WAIT_FOR_EVENT | flip_mask);
11039         intel_ring_emit(engine, MI_NOOP);
11040         intel_ring_emit(engine, MI_DISPLAY_FLIP_I915 |
11041                         MI_DISPLAY_FLIP_PLANE(intel_crtc->plane));
11042         intel_ring_emit(engine, fb->pitches[0]);
11043         intel_ring_emit(engine, intel_crtc->unpin_work->gtt_offset);
11044         intel_ring_emit(engine, MI_NOOP);
11045
11046         intel_mark_page_flip_active(intel_crtc->unpin_work);
11047         return 0;
11048 }
11049
11050 static int intel_gen4_queue_flip(struct drm_device *dev,
11051                                  struct drm_crtc *crtc,
11052                                  struct drm_framebuffer *fb,
11053                                  struct drm_i915_gem_object *obj,
11054                                  struct drm_i915_gem_request *req,
11055                                  uint32_t flags)
11056 {
11057         struct intel_engine_cs *engine = req->engine;
11058         struct drm_i915_private *dev_priv = dev->dev_private;
11059         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
11060         uint32_t pf, pipesrc;
11061         int ret;
11062
11063         ret = intel_ring_begin(req, 4);
11064         if (ret)
11065                 return ret;
11066
11067         /* i965+ uses the linear or tiled offsets from the
11068          * Display Registers (which do not change across a page-flip)
11069          * so we need only reprogram the base address.
11070          */
11071         intel_ring_emit(engine, MI_DISPLAY_FLIP |
11072                         MI_DISPLAY_FLIP_PLANE(intel_crtc->plane));
11073         intel_ring_emit(engine, fb->pitches[0]);
11074         intel_ring_emit(engine, intel_crtc->unpin_work->gtt_offset |
11075                         obj->tiling_mode);
11076
11077         /* XXX Enabling the panel-fitter across page-flip is so far
11078          * untested on non-native modes, so ignore it for now.
11079          * pf = I915_READ(pipe == 0 ? PFA_CTL_1 : PFB_CTL_1) & PF_ENABLE;
11080          */
11081         pf = 0;
11082         pipesrc = I915_READ(PIPESRC(intel_crtc->pipe)) & 0x0fff0fff;
11083         intel_ring_emit(engine, pf | pipesrc);
11084
11085         intel_mark_page_flip_active(intel_crtc->unpin_work);
11086         return 0;
11087 }
11088
11089 static int intel_gen6_queue_flip(struct drm_device *dev,
11090                                  struct drm_crtc *crtc,
11091                                  struct drm_framebuffer *fb,
11092                                  struct drm_i915_gem_object *obj,
11093                                  struct drm_i915_gem_request *req,
11094                                  uint32_t flags)
11095 {
11096         struct intel_engine_cs *engine = req->engine;
11097         struct drm_i915_private *dev_priv = dev->dev_private;
11098         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
11099         uint32_t pf, pipesrc;
11100         int ret;
11101
11102         ret = intel_ring_begin(req, 4);
11103         if (ret)
11104                 return ret;
11105
11106         intel_ring_emit(engine, MI_DISPLAY_FLIP |
11107                         MI_DISPLAY_FLIP_PLANE(intel_crtc->plane));
11108         intel_ring_emit(engine, fb->pitches[0] | obj->tiling_mode);
11109         intel_ring_emit(engine, intel_crtc->unpin_work->gtt_offset);
11110
11111         /* Contrary to the suggestions in the documentation,
11112          * "Enable Panel Fitter" does not seem to be required when page
11113          * flipping with a non-native mode, and worse causes a normal
11114          * modeset to fail.
11115          * pf = I915_READ(PF_CTL(intel_crtc->pipe)) & 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_gen7_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 intel_crtc *intel_crtc = to_intel_crtc(crtc);
11134         uint32_t plane_bit = 0;
11135         int len, ret;
11136
11137         switch (intel_crtc->plane) {
11138         case PLANE_A:
11139                 plane_bit = MI_DISPLAY_FLIP_IVB_PLANE_A;
11140                 break;
11141         case PLANE_B:
11142                 plane_bit = MI_DISPLAY_FLIP_IVB_PLANE_B;
11143                 break;
11144         case PLANE_C:
11145                 plane_bit = MI_DISPLAY_FLIP_IVB_PLANE_C;
11146                 break;
11147         default:
11148                 WARN_ONCE(1, "unknown plane in flip command\n");
11149                 return -ENODEV;
11150         }
11151
11152         len = 4;
11153         if (engine->id == RCS) {
11154                 len += 6;
11155                 /*
11156                  * On Gen 8, SRM is now taking an extra dword to accommodate
11157                  * 48bits addresses, and we need a NOOP for the batch size to
11158                  * stay even.
11159                  */
11160                 if (IS_GEN8(dev))
11161                         len += 2;
11162         }
11163
11164         /*
11165          * BSpec MI_DISPLAY_FLIP for IVB:
11166          * "The full packet must be contained within the same cache line."
11167          *
11168          * Currently the LRI+SRM+MI_DISPLAY_FLIP all fit within the same
11169          * cacheline, if we ever start emitting more commands before
11170          * the MI_DISPLAY_FLIP we may need to first emit everything else,
11171          * then do the cacheline alignment, and finally emit the
11172          * MI_DISPLAY_FLIP.
11173          */
11174         ret = intel_ring_cacheline_align(req);
11175         if (ret)
11176                 return ret;
11177
11178         ret = intel_ring_begin(req, len);
11179         if (ret)
11180                 return ret;
11181
11182         /* Unmask the flip-done completion message. Note that the bspec says that
11183          * we should do this for both the BCS and RCS, and that we must not unmask
11184          * more than one flip event at any time (or ensure that one flip message
11185          * can be sent by waiting for flip-done prior to queueing new flips).
11186          * Experimentation says that BCS works despite DERRMR masking all
11187          * flip-done completion events and that unmasking all planes at once
11188          * for the RCS also doesn't appear to drop events. Setting the DERRMR
11189          * to zero does lead to lockups within MI_DISPLAY_FLIP.
11190          */
11191         if (engine->id == RCS) {
11192                 intel_ring_emit(engine, MI_LOAD_REGISTER_IMM(1));
11193                 intel_ring_emit_reg(engine, DERRMR);
11194                 intel_ring_emit(engine, ~(DERRMR_PIPEA_PRI_FLIP_DONE |
11195                                           DERRMR_PIPEB_PRI_FLIP_DONE |
11196                                           DERRMR_PIPEC_PRI_FLIP_DONE));
11197                 if (IS_GEN8(dev))
11198                         intel_ring_emit(engine, MI_STORE_REGISTER_MEM_GEN8 |
11199                                               MI_SRM_LRM_GLOBAL_GTT);
11200                 else
11201                         intel_ring_emit(engine, MI_STORE_REGISTER_MEM |
11202                                               MI_SRM_LRM_GLOBAL_GTT);
11203                 intel_ring_emit_reg(engine, DERRMR);
11204                 intel_ring_emit(engine, engine->scratch.gtt_offset + 256);
11205                 if (IS_GEN8(dev)) {
11206                         intel_ring_emit(engine, 0);
11207                         intel_ring_emit(engine, MI_NOOP);
11208                 }
11209         }
11210
11211         intel_ring_emit(engine, MI_DISPLAY_FLIP_I915 | plane_bit);
11212         intel_ring_emit(engine, (fb->pitches[0] | obj->tiling_mode));
11213         intel_ring_emit(engine, intel_crtc->unpin_work->gtt_offset);
11214         intel_ring_emit(engine, (MI_NOOP));
11215
11216         intel_mark_page_flip_active(intel_crtc->unpin_work);
11217         return 0;
11218 }
11219
11220 static bool use_mmio_flip(struct intel_engine_cs *engine,
11221                           struct drm_i915_gem_object *obj)
11222 {
11223         /*
11224          * This is not being used for older platforms, because
11225          * non-availability of flip done interrupt forces us to use
11226          * CS flips. Older platforms derive flip done using some clever
11227          * tricks involving the flip_pending status bits and vblank irqs.
11228          * So using MMIO flips there would disrupt this mechanism.
11229          */
11230
11231         if (engine == NULL)
11232                 return true;
11233
11234         if (INTEL_INFO(engine->dev)->gen < 5)
11235                 return false;
11236
11237         if (i915.use_mmio_flip < 0)
11238                 return false;
11239         else if (i915.use_mmio_flip > 0)
11240                 return true;
11241         else if (i915.enable_execlists)
11242                 return true;
11243         else if (obj->base.dma_buf &&
11244                  !reservation_object_test_signaled_rcu(obj->base.dma_buf->resv,
11245                                                        false))
11246                 return true;
11247         else
11248                 return engine != i915_gem_request_get_engine(obj->last_write_req);
11249 }
11250
11251 static void skl_do_mmio_flip(struct intel_crtc *intel_crtc,
11252                              unsigned int rotation,
11253                              struct intel_unpin_work *work)
11254 {
11255         struct drm_device *dev = intel_crtc->base.dev;
11256         struct drm_i915_private *dev_priv = dev->dev_private;
11257         struct drm_framebuffer *fb = intel_crtc->base.primary->fb;
11258         const enum pipe pipe = intel_crtc->pipe;
11259         u32 ctl, stride, tile_height;
11260
11261         ctl = I915_READ(PLANE_CTL(pipe, 0));
11262         ctl &= ~PLANE_CTL_TILED_MASK;
11263         switch (fb->modifier[0]) {
11264         case DRM_FORMAT_MOD_NONE:
11265                 break;
11266         case I915_FORMAT_MOD_X_TILED:
11267                 ctl |= PLANE_CTL_TILED_X;
11268                 break;
11269         case I915_FORMAT_MOD_Y_TILED:
11270                 ctl |= PLANE_CTL_TILED_Y;
11271                 break;
11272         case I915_FORMAT_MOD_Yf_TILED:
11273                 ctl |= PLANE_CTL_TILED_YF;
11274                 break;
11275         default:
11276                 MISSING_CASE(fb->modifier[0]);
11277         }
11278
11279         /*
11280          * The stride is either expressed as a multiple of 64 bytes chunks for
11281          * linear buffers or in number of tiles for tiled buffers.
11282          */
11283         if (intel_rotation_90_or_270(rotation)) {
11284                 /* stride = Surface height in tiles */
11285                 tile_height = intel_tile_height(dev_priv, fb->modifier[0], 0);
11286                 stride = DIV_ROUND_UP(fb->height, tile_height);
11287         } else {
11288                 stride = fb->pitches[0] /
11289                         intel_fb_stride_alignment(dev_priv, fb->modifier[0],
11290                                                   fb->pixel_format);
11291         }
11292
11293         /*
11294          * Both PLANE_CTL and PLANE_STRIDE are not updated on vblank but on
11295          * PLANE_SURF updates, the update is then guaranteed to be atomic.
11296          */
11297         I915_WRITE(PLANE_CTL(pipe, 0), ctl);
11298         I915_WRITE(PLANE_STRIDE(pipe, 0), stride);
11299
11300         I915_WRITE(PLANE_SURF(pipe, 0), work->gtt_offset);
11301         POSTING_READ(PLANE_SURF(pipe, 0));
11302 }
11303
11304 static void ilk_do_mmio_flip(struct intel_crtc *intel_crtc,
11305                              struct intel_unpin_work *work)
11306 {
11307         struct drm_device *dev = intel_crtc->base.dev;
11308         struct drm_i915_private *dev_priv = dev->dev_private;
11309         struct intel_framebuffer *intel_fb =
11310                 to_intel_framebuffer(intel_crtc->base.primary->fb);
11311         struct drm_i915_gem_object *obj = intel_fb->obj;
11312         i915_reg_t reg = DSPCNTR(intel_crtc->plane);
11313         u32 dspcntr;
11314
11315         dspcntr = I915_READ(reg);
11316
11317         if (obj->tiling_mode != I915_TILING_NONE)
11318                 dspcntr |= DISPPLANE_TILED;
11319         else
11320                 dspcntr &= ~DISPPLANE_TILED;
11321
11322         I915_WRITE(reg, dspcntr);
11323
11324         I915_WRITE(DSPSURF(intel_crtc->plane), work->gtt_offset);
11325         POSTING_READ(DSPSURF(intel_crtc->plane));
11326 }
11327
11328 /*
11329  * XXX: This is the temporary way to update the plane registers until we get
11330  * around to using the usual plane update functions for MMIO flips
11331  */
11332 static void intel_do_mmio_flip(struct intel_mmio_flip *mmio_flip)
11333 {
11334         struct intel_crtc *crtc = mmio_flip->crtc;
11335         struct intel_unpin_work *work;
11336
11337         spin_lock_irq(&crtc->base.dev->event_lock);
11338         work = crtc->unpin_work;
11339         spin_unlock_irq(&crtc->base.dev->event_lock);
11340         if (work == NULL)
11341                 return;
11342
11343         intel_mark_page_flip_active(work);
11344
11345         intel_pipe_update_start(crtc);
11346
11347         if (INTEL_INFO(mmio_flip->i915)->gen >= 9)
11348                 skl_do_mmio_flip(crtc, mmio_flip->rotation, work);
11349         else
11350                 /* use_mmio_flip() retricts MMIO flips to ilk+ */
11351                 ilk_do_mmio_flip(crtc, work);
11352
11353         intel_pipe_update_end(crtc);
11354 }
11355
11356 static void intel_mmio_flip_work_func(struct work_struct *work)
11357 {
11358         struct intel_mmio_flip *mmio_flip =
11359                 container_of(work, struct intel_mmio_flip, work);
11360         struct intel_framebuffer *intel_fb =
11361                 to_intel_framebuffer(mmio_flip->crtc->base.primary->fb);
11362         struct drm_i915_gem_object *obj = intel_fb->obj;
11363
11364         if (mmio_flip->req) {
11365                 WARN_ON(__i915_wait_request(mmio_flip->req,
11366                                             mmio_flip->crtc->reset_counter,
11367                                             false, NULL,
11368                                             &mmio_flip->i915->rps.mmioflips));
11369                 i915_gem_request_unreference__unlocked(mmio_flip->req);
11370         }
11371
11372         /* For framebuffer backed by dmabuf, wait for fence */
11373         if (obj->base.dma_buf)
11374                 WARN_ON(reservation_object_wait_timeout_rcu(obj->base.dma_buf->resv,
11375                                                             false, false,
11376                                                             MAX_SCHEDULE_TIMEOUT) < 0);
11377
11378         intel_do_mmio_flip(mmio_flip);
11379         kfree(mmio_flip);
11380 }
11381
11382 static int intel_queue_mmio_flip(struct drm_device *dev,
11383                                  struct drm_crtc *crtc,
11384                                  struct drm_i915_gem_object *obj)
11385 {
11386         struct intel_mmio_flip *mmio_flip;
11387
11388         mmio_flip = kmalloc(sizeof(*mmio_flip), GFP_KERNEL);
11389         if (mmio_flip == NULL)
11390                 return -ENOMEM;
11391
11392         mmio_flip->i915 = to_i915(dev);
11393         mmio_flip->req = i915_gem_request_reference(obj->last_write_req);
11394         mmio_flip->crtc = to_intel_crtc(crtc);
11395         mmio_flip->rotation = crtc->primary->state->rotation;
11396
11397         INIT_WORK(&mmio_flip->work, intel_mmio_flip_work_func);
11398         schedule_work(&mmio_flip->work);
11399
11400         return 0;
11401 }
11402
11403 static int intel_default_queue_flip(struct drm_device *dev,
11404                                     struct drm_crtc *crtc,
11405                                     struct drm_framebuffer *fb,
11406                                     struct drm_i915_gem_object *obj,
11407                                     struct drm_i915_gem_request *req,
11408                                     uint32_t flags)
11409 {
11410         return -ENODEV;
11411 }
11412
11413 static bool __intel_pageflip_stall_check(struct drm_device *dev,
11414                                          struct drm_crtc *crtc)
11415 {
11416         struct drm_i915_private *dev_priv = dev->dev_private;
11417         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
11418         struct intel_unpin_work *work = intel_crtc->unpin_work;
11419         u32 addr;
11420
11421         if (atomic_read(&work->pending) >= INTEL_FLIP_COMPLETE)
11422                 return true;
11423
11424         if (atomic_read(&work->pending) < INTEL_FLIP_PENDING)
11425                 return false;
11426
11427         if (!work->enable_stall_check)
11428                 return false;
11429
11430         if (work->flip_ready_vblank == 0) {
11431                 if (work->flip_queued_req &&
11432                     !i915_gem_request_completed(work->flip_queued_req, true))
11433                         return false;
11434
11435                 work->flip_ready_vblank = drm_crtc_vblank_count(crtc);
11436         }
11437
11438         if (drm_crtc_vblank_count(crtc) - work->flip_ready_vblank < 3)
11439                 return false;
11440
11441         /* Potential stall - if we see that the flip has happened,
11442          * assume a missed interrupt. */
11443         if (INTEL_INFO(dev)->gen >= 4)
11444                 addr = I915_HI_DISPBASE(I915_READ(DSPSURF(intel_crtc->plane)));
11445         else
11446                 addr = I915_READ(DSPADDR(intel_crtc->plane));
11447
11448         /* There is a potential issue here with a false positive after a flip
11449          * to the same address. We could address this by checking for a
11450          * non-incrementing frame counter.
11451          */
11452         return addr == work->gtt_offset;
11453 }
11454
11455 void intel_check_page_flip(struct drm_device *dev, int pipe)
11456 {
11457         struct drm_i915_private *dev_priv = dev->dev_private;
11458         struct drm_crtc *crtc = dev_priv->pipe_to_crtc_mapping[pipe];
11459         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
11460         struct intel_unpin_work *work;
11461
11462         WARN_ON(!in_interrupt());
11463
11464         if (crtc == NULL)
11465                 return;
11466
11467         spin_lock(&dev->event_lock);
11468         work = intel_crtc->unpin_work;
11469         if (work != NULL && __intel_pageflip_stall_check(dev, crtc)) {
11470                 WARN_ONCE(1, "Kicking stuck page flip: queued at %d, now %d\n",
11471                          work->flip_queued_vblank, drm_vblank_count(dev, pipe));
11472                 page_flip_completed(intel_crtc);
11473                 work = NULL;
11474         }
11475         if (work != NULL &&
11476             drm_vblank_count(dev, pipe) - work->flip_queued_vblank > 1)
11477                 intel_queue_rps_boost_for_request(dev, work->flip_queued_req);
11478         spin_unlock(&dev->event_lock);
11479 }
11480
11481 static int intel_crtc_page_flip(struct drm_crtc *crtc,
11482                                 struct drm_framebuffer *fb,
11483                                 struct drm_pending_vblank_event *event,
11484                                 uint32_t page_flip_flags)
11485 {
11486         struct drm_device *dev = crtc->dev;
11487         struct drm_i915_private *dev_priv = dev->dev_private;
11488         struct drm_framebuffer *old_fb = crtc->primary->fb;
11489         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
11490         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
11491         struct drm_plane *primary = crtc->primary;
11492         enum pipe pipe = intel_crtc->pipe;
11493         struct intel_unpin_work *work;
11494         struct intel_engine_cs *engine;
11495         bool mmio_flip;
11496         struct drm_i915_gem_request *request = NULL;
11497         int ret;
11498
11499         /*
11500          * drm_mode_page_flip_ioctl() should already catch this, but double
11501          * check to be safe.  In the future we may enable pageflipping from
11502          * a disabled primary plane.
11503          */
11504         if (WARN_ON(intel_fb_obj(old_fb) == NULL))
11505                 return -EBUSY;
11506
11507         /* Can't change pixel format via MI display flips. */
11508         if (fb->pixel_format != crtc->primary->fb->pixel_format)
11509                 return -EINVAL;
11510
11511         /*
11512          * TILEOFF/LINOFF registers can't be changed via MI display flips.
11513          * Note that pitch changes could also affect these register.
11514          */
11515         if (INTEL_INFO(dev)->gen > 3 &&
11516             (fb->offsets[0] != crtc->primary->fb->offsets[0] ||
11517              fb->pitches[0] != crtc->primary->fb->pitches[0]))
11518                 return -EINVAL;
11519
11520         if (i915_terminally_wedged(&dev_priv->gpu_error))
11521                 goto out_hang;
11522
11523         work = kzalloc(sizeof(*work), GFP_KERNEL);
11524         if (work == NULL)
11525                 return -ENOMEM;
11526
11527         work->event = event;
11528         work->crtc = crtc;
11529         work->old_fb = old_fb;
11530         INIT_WORK(&work->work, intel_unpin_work_fn);
11531
11532         ret = drm_crtc_vblank_get(crtc);
11533         if (ret)
11534                 goto free_work;
11535
11536         /* We borrow the event spin lock for protecting unpin_work */
11537         spin_lock_irq(&dev->event_lock);
11538         if (intel_crtc->unpin_work) {
11539                 /* Before declaring the flip queue wedged, check if
11540                  * the hardware completed the operation behind our backs.
11541                  */
11542                 if (__intel_pageflip_stall_check(dev, crtc)) {
11543                         DRM_DEBUG_DRIVER("flip queue: previous flip completed, continuing\n");
11544                         page_flip_completed(intel_crtc);
11545                 } else {
11546                         DRM_DEBUG_DRIVER("flip queue: crtc already busy\n");
11547                         spin_unlock_irq(&dev->event_lock);
11548
11549                         drm_crtc_vblank_put(crtc);
11550                         kfree(work);
11551                         return -EBUSY;
11552                 }
11553         }
11554         intel_crtc->unpin_work = work;
11555         spin_unlock_irq(&dev->event_lock);
11556
11557         if (atomic_read(&intel_crtc->unpin_work_count) >= 2)
11558                 flush_workqueue(dev_priv->wq);
11559
11560         /* Reference the objects for the scheduled work. */
11561         drm_framebuffer_reference(work->old_fb);
11562         drm_gem_object_reference(&obj->base);
11563
11564         crtc->primary->fb = fb;
11565         update_state_fb(crtc->primary);
11566         intel_fbc_pre_update(intel_crtc);
11567
11568         work->pending_flip_obj = obj;
11569
11570         ret = i915_mutex_lock_interruptible(dev);
11571         if (ret)
11572                 goto cleanup;
11573
11574         atomic_inc(&intel_crtc->unpin_work_count);
11575         intel_crtc->reset_counter = atomic_read(&dev_priv->gpu_error.reset_counter);
11576
11577         if (INTEL_INFO(dev)->gen >= 5 || IS_G4X(dev))
11578                 work->flip_count = I915_READ(PIPE_FLIPCOUNT_G4X(pipe)) + 1;
11579
11580         if (IS_VALLEYVIEW(dev) || IS_CHERRYVIEW(dev)) {
11581                 engine = &dev_priv->engine[BCS];
11582                 if (obj->tiling_mode != intel_fb_obj(work->old_fb)->tiling_mode)
11583                         /* vlv: DISPLAY_FLIP fails to change tiling */
11584                         engine = NULL;
11585         } else if (IS_IVYBRIDGE(dev) || IS_HASWELL(dev)) {
11586                 engine = &dev_priv->engine[BCS];
11587         } else if (INTEL_INFO(dev)->gen >= 7) {
11588                 engine = i915_gem_request_get_engine(obj->last_write_req);
11589                 if (engine == NULL || engine->id != RCS)
11590                         engine = &dev_priv->engine[BCS];
11591         } else {
11592                 engine = &dev_priv->engine[RCS];
11593         }
11594
11595         mmio_flip = use_mmio_flip(engine, obj);
11596
11597         /* When using CS flips, we want to emit semaphores between rings.
11598          * However, when using mmio flips we will create a task to do the
11599          * synchronisation, so all we want here is to pin the framebuffer
11600          * into the display plane and skip any waits.
11601          */
11602         if (!mmio_flip) {
11603                 ret = i915_gem_object_sync(obj, engine, &request);
11604                 if (ret)
11605                         goto cleanup_pending;
11606         }
11607
11608         ret = intel_pin_and_fence_fb_obj(fb, primary->state->rotation);
11609         if (ret)
11610                 goto cleanup_pending;
11611
11612         work->gtt_offset = intel_plane_obj_offset(to_intel_plane(primary),
11613                                                   obj, 0);
11614         work->gtt_offset += intel_crtc->dspaddr_offset;
11615
11616         if (mmio_flip) {
11617                 ret = intel_queue_mmio_flip(dev, crtc, obj);
11618                 if (ret)
11619                         goto cleanup_unpin;
11620
11621                 i915_gem_request_assign(&work->flip_queued_req,
11622                                         obj->last_write_req);
11623         } else {
11624                 if (!request) {
11625                         request = i915_gem_request_alloc(engine, NULL);
11626                         if (IS_ERR(request)) {
11627                                 ret = PTR_ERR(request);
11628                                 goto cleanup_unpin;
11629                         }
11630                 }
11631
11632                 ret = dev_priv->display.queue_flip(dev, crtc, fb, obj, request,
11633                                                    page_flip_flags);
11634                 if (ret)
11635                         goto cleanup_unpin;
11636
11637                 i915_gem_request_assign(&work->flip_queued_req, request);
11638         }
11639
11640         if (request)
11641                 i915_add_request_no_flush(request);
11642
11643         work->flip_queued_vblank = drm_crtc_vblank_count(crtc);
11644         work->enable_stall_check = true;
11645
11646         i915_gem_track_fb(intel_fb_obj(work->old_fb), obj,
11647                           to_intel_plane(primary)->frontbuffer_bit);
11648         mutex_unlock(&dev->struct_mutex);
11649
11650         intel_frontbuffer_flip_prepare(dev,
11651                                        to_intel_plane(primary)->frontbuffer_bit);
11652
11653         trace_i915_flip_request(intel_crtc->plane, obj);
11654
11655         return 0;
11656
11657 cleanup_unpin:
11658         intel_unpin_fb_obj(fb, crtc->primary->state->rotation);
11659 cleanup_pending:
11660         if (!IS_ERR_OR_NULL(request))
11661                 i915_gem_request_cancel(request);
11662         atomic_dec(&intel_crtc->unpin_work_count);
11663         mutex_unlock(&dev->struct_mutex);
11664 cleanup:
11665         crtc->primary->fb = old_fb;
11666         update_state_fb(crtc->primary);
11667
11668         drm_gem_object_unreference_unlocked(&obj->base);
11669         drm_framebuffer_unreference(work->old_fb);
11670
11671         spin_lock_irq(&dev->event_lock);
11672         intel_crtc->unpin_work = NULL;
11673         spin_unlock_irq(&dev->event_lock);
11674
11675         drm_crtc_vblank_put(crtc);
11676 free_work:
11677         kfree(work);
11678
11679         if (ret == -EIO) {
11680                 struct drm_atomic_state *state;
11681                 struct drm_plane_state *plane_state;
11682
11683 out_hang:
11684                 state = drm_atomic_state_alloc(dev);
11685                 if (!state)
11686                         return -ENOMEM;
11687                 state->acquire_ctx = drm_modeset_legacy_acquire_ctx(crtc);
11688
11689 retry:
11690                 plane_state = drm_atomic_get_plane_state(state, primary);
11691                 ret = PTR_ERR_OR_ZERO(plane_state);
11692                 if (!ret) {
11693                         drm_atomic_set_fb_for_plane(plane_state, fb);
11694
11695                         ret = drm_atomic_set_crtc_for_plane(plane_state, crtc);
11696                         if (!ret)
11697                                 ret = drm_atomic_commit(state);
11698                 }
11699
11700                 if (ret == -EDEADLK) {
11701                         drm_modeset_backoff(state->acquire_ctx);
11702                         drm_atomic_state_clear(state);
11703                         goto retry;
11704                 }
11705
11706                 if (ret)
11707                         drm_atomic_state_free(state);
11708
11709                 if (ret == 0 && event) {
11710                         spin_lock_irq(&dev->event_lock);
11711                         drm_send_vblank_event(dev, pipe, event);
11712                         spin_unlock_irq(&dev->event_lock);
11713                 }
11714         }
11715         return ret;
11716 }
11717
11718
11719 /**
11720  * intel_wm_need_update - Check whether watermarks need updating
11721  * @plane: drm plane
11722  * @state: new plane state
11723  *
11724  * Check current plane state versus the new one to determine whether
11725  * watermarks need to be recalculated.
11726  *
11727  * Returns true or false.
11728  */
11729 static bool intel_wm_need_update(struct drm_plane *plane,
11730                                  struct drm_plane_state *state)
11731 {
11732         struct intel_plane_state *new = to_intel_plane_state(state);
11733         struct intel_plane_state *cur = to_intel_plane_state(plane->state);
11734
11735         /* Update watermarks on tiling or size changes. */
11736         if (new->visible != cur->visible)
11737                 return true;
11738
11739         if (!cur->base.fb || !new->base.fb)
11740                 return false;
11741
11742         if (cur->base.fb->modifier[0] != new->base.fb->modifier[0] ||
11743             cur->base.rotation != new->base.rotation ||
11744             drm_rect_width(&new->src) != drm_rect_width(&cur->src) ||
11745             drm_rect_height(&new->src) != drm_rect_height(&cur->src) ||
11746             drm_rect_width(&new->dst) != drm_rect_width(&cur->dst) ||
11747             drm_rect_height(&new->dst) != drm_rect_height(&cur->dst))
11748                 return true;
11749
11750         return false;
11751 }
11752
11753 static bool needs_scaling(struct intel_plane_state *state)
11754 {
11755         int src_w = drm_rect_width(&state->src) >> 16;
11756         int src_h = drm_rect_height(&state->src) >> 16;
11757         int dst_w = drm_rect_width(&state->dst);
11758         int dst_h = drm_rect_height(&state->dst);
11759
11760         return (src_w != dst_w || src_h != dst_h);
11761 }
11762
11763 int intel_plane_atomic_calc_changes(struct drm_crtc_state *crtc_state,
11764                                     struct drm_plane_state *plane_state)
11765 {
11766         struct intel_crtc_state *pipe_config = to_intel_crtc_state(crtc_state);
11767         struct drm_crtc *crtc = crtc_state->crtc;
11768         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
11769         struct drm_plane *plane = plane_state->plane;
11770         struct drm_device *dev = crtc->dev;
11771         struct drm_i915_private *dev_priv = to_i915(dev);
11772         struct intel_plane_state *old_plane_state =
11773                 to_intel_plane_state(plane->state);
11774         int idx = intel_crtc->base.base.id, ret;
11775         bool mode_changed = needs_modeset(crtc_state);
11776         bool was_crtc_enabled = crtc->state->active;
11777         bool is_crtc_enabled = crtc_state->active;
11778         bool turn_off, turn_on, visible, was_visible;
11779         struct drm_framebuffer *fb = plane_state->fb;
11780
11781         if (crtc_state && INTEL_INFO(dev)->gen >= 9 &&
11782             plane->type != DRM_PLANE_TYPE_CURSOR) {
11783                 ret = skl_update_scaler_plane(
11784                         to_intel_crtc_state(crtc_state),
11785                         to_intel_plane_state(plane_state));
11786                 if (ret)
11787                         return ret;
11788         }
11789
11790         was_visible = old_plane_state->visible;
11791         visible = to_intel_plane_state(plane_state)->visible;
11792
11793         if (!was_crtc_enabled && WARN_ON(was_visible))
11794                 was_visible = false;
11795
11796         /*
11797          * Visibility is calculated as if the crtc was on, but
11798          * after scaler setup everything depends on it being off
11799          * when the crtc isn't active.
11800          */
11801         if (!is_crtc_enabled)
11802                 to_intel_plane_state(plane_state)->visible = visible = false;
11803
11804         if (!was_visible && !visible)
11805                 return 0;
11806
11807         if (fb != old_plane_state->base.fb)
11808                 pipe_config->fb_changed = true;
11809
11810         turn_off = was_visible && (!visible || mode_changed);
11811         turn_on = visible && (!was_visible || mode_changed);
11812
11813         DRM_DEBUG_ATOMIC("[CRTC:%i] has [PLANE:%i] with fb %i\n", idx,
11814                          plane->base.id, fb ? fb->base.id : -1);
11815
11816         DRM_DEBUG_ATOMIC("[PLANE:%i] visible %i -> %i, off %i, on %i, ms %i\n",
11817                          plane->base.id, was_visible, visible,
11818                          turn_off, turn_on, mode_changed);
11819
11820         if (turn_on) {
11821                 pipe_config->update_wm_pre = true;
11822
11823                 /* must disable cxsr around plane enable/disable */
11824                 if (plane->type != DRM_PLANE_TYPE_CURSOR)
11825                         pipe_config->disable_cxsr = true;
11826         } else if (turn_off) {
11827                 pipe_config->update_wm_post = true;
11828
11829                 /* must disable cxsr around plane enable/disable */
11830                 if (plane->type != DRM_PLANE_TYPE_CURSOR)
11831                         pipe_config->disable_cxsr = true;
11832         } else if (intel_wm_need_update(plane, plane_state)) {
11833                 /* FIXME bollocks */
11834                 pipe_config->update_wm_pre = true;
11835                 pipe_config->update_wm_post = true;
11836         }
11837
11838         /* Pre-gen9 platforms need two-step watermark updates */
11839         if ((pipe_config->update_wm_pre || pipe_config->update_wm_post) &&
11840             INTEL_INFO(dev)->gen < 9 && dev_priv->display.optimize_watermarks)
11841                 to_intel_crtc_state(crtc_state)->wm.need_postvbl_update = true;
11842
11843         if (visible || was_visible)
11844                 pipe_config->fb_bits |= to_intel_plane(plane)->frontbuffer_bit;
11845
11846         /*
11847          * WaCxSRDisabledForSpriteScaling:ivb
11848          *
11849          * cstate->update_wm was already set above, so this flag will
11850          * take effect when we commit and program watermarks.
11851          */
11852         if (plane->type == DRM_PLANE_TYPE_OVERLAY && IS_IVYBRIDGE(dev) &&
11853             needs_scaling(to_intel_plane_state(plane_state)) &&
11854             !needs_scaling(old_plane_state))
11855                 pipe_config->disable_lp_wm = true;
11856
11857         return 0;
11858 }
11859
11860 static bool encoders_cloneable(const struct intel_encoder *a,
11861                                const struct intel_encoder *b)
11862 {
11863         /* masks could be asymmetric, so check both ways */
11864         return a == b || (a->cloneable & (1 << b->type) &&
11865                           b->cloneable & (1 << a->type));
11866 }
11867
11868 static bool check_single_encoder_cloning(struct drm_atomic_state *state,
11869                                          struct intel_crtc *crtc,
11870                                          struct intel_encoder *encoder)
11871 {
11872         struct intel_encoder *source_encoder;
11873         struct drm_connector *connector;
11874         struct drm_connector_state *connector_state;
11875         int i;
11876
11877         for_each_connector_in_state(state, connector, connector_state, i) {
11878                 if (connector_state->crtc != &crtc->base)
11879                         continue;
11880
11881                 source_encoder =
11882                         to_intel_encoder(connector_state->best_encoder);
11883                 if (!encoders_cloneable(encoder, source_encoder))
11884                         return false;
11885         }
11886
11887         return true;
11888 }
11889
11890 static bool check_encoder_cloning(struct drm_atomic_state *state,
11891                                   struct intel_crtc *crtc)
11892 {
11893         struct intel_encoder *encoder;
11894         struct drm_connector *connector;
11895         struct drm_connector_state *connector_state;
11896         int i;
11897
11898         for_each_connector_in_state(state, connector, connector_state, i) {
11899                 if (connector_state->crtc != &crtc->base)
11900                         continue;
11901
11902                 encoder = to_intel_encoder(connector_state->best_encoder);
11903                 if (!check_single_encoder_cloning(state, crtc, encoder))
11904                         return false;
11905         }
11906
11907         return true;
11908 }
11909
11910 static int intel_crtc_atomic_check(struct drm_crtc *crtc,
11911                                    struct drm_crtc_state *crtc_state)
11912 {
11913         struct drm_device *dev = crtc->dev;
11914         struct drm_i915_private *dev_priv = dev->dev_private;
11915         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
11916         struct intel_crtc_state *pipe_config =
11917                 to_intel_crtc_state(crtc_state);
11918         struct drm_atomic_state *state = crtc_state->state;
11919         int ret;
11920         bool mode_changed = needs_modeset(crtc_state);
11921
11922         if (mode_changed && !check_encoder_cloning(state, intel_crtc)) {
11923                 DRM_DEBUG_KMS("rejecting invalid cloning configuration\n");
11924                 return -EINVAL;
11925         }
11926
11927         if (mode_changed && !crtc_state->active)
11928                 pipe_config->update_wm_post = true;
11929
11930         if (mode_changed && crtc_state->enable &&
11931             dev_priv->display.crtc_compute_clock &&
11932             !WARN_ON(pipe_config->shared_dpll)) {
11933                 ret = dev_priv->display.crtc_compute_clock(intel_crtc,
11934                                                            pipe_config);
11935                 if (ret)
11936                         return ret;
11937         }
11938
11939         ret = 0;
11940         if (dev_priv->display.compute_pipe_wm) {
11941                 ret = dev_priv->display.compute_pipe_wm(pipe_config);
11942                 if (ret) {
11943                         DRM_DEBUG_KMS("Target pipe watermarks are invalid\n");
11944                         return ret;
11945                 }
11946         }
11947
11948         if (dev_priv->display.compute_intermediate_wm &&
11949             !to_intel_atomic_state(state)->skip_intermediate_wm) {
11950                 if (WARN_ON(!dev_priv->display.compute_pipe_wm))
11951                         return 0;
11952
11953                 /*
11954                  * Calculate 'intermediate' watermarks that satisfy both the
11955                  * old state and the new state.  We can program these
11956                  * immediately.
11957                  */
11958                 ret = dev_priv->display.compute_intermediate_wm(crtc->dev,
11959                                                                 intel_crtc,
11960                                                                 pipe_config);
11961                 if (ret) {
11962                         DRM_DEBUG_KMS("No valid intermediate pipe watermarks are possible\n");
11963                         return ret;
11964                 }
11965         }
11966
11967         if (INTEL_INFO(dev)->gen >= 9) {
11968                 if (mode_changed)
11969                         ret = skl_update_scaler_crtc(pipe_config);
11970
11971                 if (!ret)
11972                         ret = intel_atomic_setup_scalers(dev, intel_crtc,
11973                                                          pipe_config);
11974         }
11975
11976         return ret;
11977 }
11978
11979 static const struct drm_crtc_helper_funcs intel_helper_funcs = {
11980         .mode_set_base_atomic = intel_pipe_set_base_atomic,
11981         .load_lut = intel_crtc_load_lut,
11982         .atomic_begin = intel_begin_crtc_commit,
11983         .atomic_flush = intel_finish_crtc_commit,
11984         .atomic_check = intel_crtc_atomic_check,
11985 };
11986
11987 static void intel_modeset_update_connector_atomic_state(struct drm_device *dev)
11988 {
11989         struct intel_connector *connector;
11990
11991         for_each_intel_connector(dev, connector) {
11992                 if (connector->base.encoder) {
11993                         connector->base.state->best_encoder =
11994                                 connector->base.encoder;
11995                         connector->base.state->crtc =
11996                                 connector->base.encoder->crtc;
11997                 } else {
11998                         connector->base.state->best_encoder = NULL;
11999                         connector->base.state->crtc = NULL;
12000                 }
12001         }
12002 }
12003
12004 static void
12005 connected_sink_compute_bpp(struct intel_connector *connector,
12006                            struct intel_crtc_state *pipe_config)
12007 {
12008         int bpp = pipe_config->pipe_bpp;
12009
12010         DRM_DEBUG_KMS("[CONNECTOR:%d:%s] checking for sink bpp constrains\n",
12011                 connector->base.base.id,
12012                 connector->base.name);
12013
12014         /* Don't use an invalid EDID bpc value */
12015         if (connector->base.display_info.bpc &&
12016             connector->base.display_info.bpc * 3 < bpp) {
12017                 DRM_DEBUG_KMS("clamping display bpp (was %d) to EDID reported max of %d\n",
12018                               bpp, connector->base.display_info.bpc*3);
12019                 pipe_config->pipe_bpp = connector->base.display_info.bpc*3;
12020         }
12021
12022         /* Clamp bpp to default limit on screens without EDID 1.4 */
12023         if (connector->base.display_info.bpc == 0) {
12024                 int type = connector->base.connector_type;
12025                 int clamp_bpp = 24;
12026
12027                 /* Fall back to 18 bpp when DP sink capability is unknown. */
12028                 if (type == DRM_MODE_CONNECTOR_DisplayPort ||
12029                     type == DRM_MODE_CONNECTOR_eDP)
12030                         clamp_bpp = 18;
12031
12032                 if (bpp > clamp_bpp) {
12033                         DRM_DEBUG_KMS("clamping display bpp (was %d) to default limit of %d\n",
12034                                       bpp, clamp_bpp);
12035                         pipe_config->pipe_bpp = clamp_bpp;
12036                 }
12037         }
12038 }
12039
12040 static int
12041 compute_baseline_pipe_bpp(struct intel_crtc *crtc,
12042                           struct intel_crtc_state *pipe_config)
12043 {
12044         struct drm_device *dev = crtc->base.dev;
12045         struct drm_atomic_state *state;
12046         struct drm_connector *connector;
12047         struct drm_connector_state *connector_state;
12048         int bpp, i;
12049
12050         if ((IS_G4X(dev) || IS_VALLEYVIEW(dev) || IS_CHERRYVIEW(dev)))
12051                 bpp = 10*3;
12052         else if (INTEL_INFO(dev)->gen >= 5)
12053                 bpp = 12*3;
12054         else
12055                 bpp = 8*3;
12056
12057
12058         pipe_config->pipe_bpp = bpp;
12059
12060         state = pipe_config->base.state;
12061
12062         /* Clamp display bpp to EDID value */
12063         for_each_connector_in_state(state, connector, connector_state, i) {
12064                 if (connector_state->crtc != &crtc->base)
12065                         continue;
12066
12067                 connected_sink_compute_bpp(to_intel_connector(connector),
12068                                            pipe_config);
12069         }
12070
12071         return bpp;
12072 }
12073
12074 static void intel_dump_crtc_timings(const struct drm_display_mode *mode)
12075 {
12076         DRM_DEBUG_KMS("crtc timings: %d %d %d %d %d %d %d %d %d, "
12077                         "type: 0x%x flags: 0x%x\n",
12078                 mode->crtc_clock,
12079                 mode->crtc_hdisplay, mode->crtc_hsync_start,
12080                 mode->crtc_hsync_end, mode->crtc_htotal,
12081                 mode->crtc_vdisplay, mode->crtc_vsync_start,
12082                 mode->crtc_vsync_end, mode->crtc_vtotal, mode->type, mode->flags);
12083 }
12084
12085 static void intel_dump_pipe_config(struct intel_crtc *crtc,
12086                                    struct intel_crtc_state *pipe_config,
12087                                    const char *context)
12088 {
12089         struct drm_device *dev = crtc->base.dev;
12090         struct drm_plane *plane;
12091         struct intel_plane *intel_plane;
12092         struct intel_plane_state *state;
12093         struct drm_framebuffer *fb;
12094
12095         DRM_DEBUG_KMS("[CRTC:%d]%s config %p for pipe %c\n", crtc->base.base.id,
12096                       context, pipe_config, pipe_name(crtc->pipe));
12097
12098         DRM_DEBUG_KMS("cpu_transcoder: %s\n", transcoder_name(pipe_config->cpu_transcoder));
12099         DRM_DEBUG_KMS("pipe bpp: %i, dithering: %i\n",
12100                       pipe_config->pipe_bpp, pipe_config->dither);
12101         DRM_DEBUG_KMS("fdi/pch: %i, lanes: %i, gmch_m: %u, gmch_n: %u, link_m: %u, link_n: %u, tu: %u\n",
12102                       pipe_config->has_pch_encoder,
12103                       pipe_config->fdi_lanes,
12104                       pipe_config->fdi_m_n.gmch_m, pipe_config->fdi_m_n.gmch_n,
12105                       pipe_config->fdi_m_n.link_m, pipe_config->fdi_m_n.link_n,
12106                       pipe_config->fdi_m_n.tu);
12107         DRM_DEBUG_KMS("dp: %i, lanes: %i, gmch_m: %u, gmch_n: %u, link_m: %u, link_n: %u, tu: %u\n",
12108                       pipe_config->has_dp_encoder,
12109                       pipe_config->lane_count,
12110                       pipe_config->dp_m_n.gmch_m, pipe_config->dp_m_n.gmch_n,
12111                       pipe_config->dp_m_n.link_m, pipe_config->dp_m_n.link_n,
12112                       pipe_config->dp_m_n.tu);
12113
12114         DRM_DEBUG_KMS("dp: %i, lanes: %i, gmch_m2: %u, gmch_n2: %u, link_m2: %u, link_n2: %u, tu2: %u\n",
12115                       pipe_config->has_dp_encoder,
12116                       pipe_config->lane_count,
12117                       pipe_config->dp_m2_n2.gmch_m,
12118                       pipe_config->dp_m2_n2.gmch_n,
12119                       pipe_config->dp_m2_n2.link_m,
12120                       pipe_config->dp_m2_n2.link_n,
12121                       pipe_config->dp_m2_n2.tu);
12122
12123         DRM_DEBUG_KMS("audio: %i, infoframes: %i\n",
12124                       pipe_config->has_audio,
12125                       pipe_config->has_infoframe);
12126
12127         DRM_DEBUG_KMS("requested mode:\n");
12128         drm_mode_debug_printmodeline(&pipe_config->base.mode);
12129         DRM_DEBUG_KMS("adjusted mode:\n");
12130         drm_mode_debug_printmodeline(&pipe_config->base.adjusted_mode);
12131         intel_dump_crtc_timings(&pipe_config->base.adjusted_mode);
12132         DRM_DEBUG_KMS("port clock: %d\n", pipe_config->port_clock);
12133         DRM_DEBUG_KMS("pipe src size: %dx%d\n",
12134                       pipe_config->pipe_src_w, pipe_config->pipe_src_h);
12135         DRM_DEBUG_KMS("num_scalers: %d, scaler_users: 0x%x, scaler_id: %d\n",
12136                       crtc->num_scalers,
12137                       pipe_config->scaler_state.scaler_users,
12138                       pipe_config->scaler_state.scaler_id);
12139         DRM_DEBUG_KMS("gmch pfit: control: 0x%08x, ratios: 0x%08x, lvds border: 0x%08x\n",
12140                       pipe_config->gmch_pfit.control,
12141                       pipe_config->gmch_pfit.pgm_ratios,
12142                       pipe_config->gmch_pfit.lvds_border_bits);
12143         DRM_DEBUG_KMS("pch pfit: pos: 0x%08x, size: 0x%08x, %s\n",
12144                       pipe_config->pch_pfit.pos,
12145                       pipe_config->pch_pfit.size,
12146                       pipe_config->pch_pfit.enabled ? "enabled" : "disabled");
12147         DRM_DEBUG_KMS("ips: %i\n", pipe_config->ips_enabled);
12148         DRM_DEBUG_KMS("double wide: %i\n", pipe_config->double_wide);
12149
12150         if (IS_BROXTON(dev)) {
12151                 DRM_DEBUG_KMS("ddi_pll_sel: %u; dpll_hw_state: ebb0: 0x%x, ebb4: 0x%x,"
12152                               "pll0: 0x%x, pll1: 0x%x, pll2: 0x%x, pll3: 0x%x, "
12153                               "pll6: 0x%x, pll8: 0x%x, pll9: 0x%x, pll10: 0x%x, pcsdw12: 0x%x\n",
12154                               pipe_config->ddi_pll_sel,
12155                               pipe_config->dpll_hw_state.ebb0,
12156                               pipe_config->dpll_hw_state.ebb4,
12157                               pipe_config->dpll_hw_state.pll0,
12158                               pipe_config->dpll_hw_state.pll1,
12159                               pipe_config->dpll_hw_state.pll2,
12160                               pipe_config->dpll_hw_state.pll3,
12161                               pipe_config->dpll_hw_state.pll6,
12162                               pipe_config->dpll_hw_state.pll8,
12163                               pipe_config->dpll_hw_state.pll9,
12164                               pipe_config->dpll_hw_state.pll10,
12165                               pipe_config->dpll_hw_state.pcsdw12);
12166         } else if (IS_SKYLAKE(dev) || IS_KABYLAKE(dev)) {
12167                 DRM_DEBUG_KMS("ddi_pll_sel: %u; dpll_hw_state: "
12168                               "ctrl1: 0x%x, cfgcr1: 0x%x, cfgcr2: 0x%x\n",
12169                               pipe_config->ddi_pll_sel,
12170                               pipe_config->dpll_hw_state.ctrl1,
12171                               pipe_config->dpll_hw_state.cfgcr1,
12172                               pipe_config->dpll_hw_state.cfgcr2);
12173         } else if (HAS_DDI(dev)) {
12174                 DRM_DEBUG_KMS("ddi_pll_sel: 0x%x; dpll_hw_state: wrpll: 0x%x spll: 0x%x\n",
12175                               pipe_config->ddi_pll_sel,
12176                               pipe_config->dpll_hw_state.wrpll,
12177                               pipe_config->dpll_hw_state.spll);
12178         } else {
12179                 DRM_DEBUG_KMS("dpll_hw_state: dpll: 0x%x, dpll_md: 0x%x, "
12180                               "fp0: 0x%x, fp1: 0x%x\n",
12181                               pipe_config->dpll_hw_state.dpll,
12182                               pipe_config->dpll_hw_state.dpll_md,
12183                               pipe_config->dpll_hw_state.fp0,
12184                               pipe_config->dpll_hw_state.fp1);
12185         }
12186
12187         DRM_DEBUG_KMS("planes on this crtc\n");
12188         list_for_each_entry(plane, &dev->mode_config.plane_list, head) {
12189                 intel_plane = to_intel_plane(plane);
12190                 if (intel_plane->pipe != crtc->pipe)
12191                         continue;
12192
12193                 state = to_intel_plane_state(plane->state);
12194                 fb = state->base.fb;
12195                 if (!fb) {
12196                         DRM_DEBUG_KMS("%s PLANE:%d plane: %u.%u idx: %d "
12197                                 "disabled, scaler_id = %d\n",
12198                                 plane->type == DRM_PLANE_TYPE_CURSOR ? "CURSOR" : "STANDARD",
12199                                 plane->base.id, intel_plane->pipe,
12200                                 (crtc->base.primary == plane) ? 0 : intel_plane->plane + 1,
12201                                 drm_plane_index(plane), state->scaler_id);
12202                         continue;
12203                 }
12204
12205                 DRM_DEBUG_KMS("%s PLANE:%d plane: %u.%u idx: %d enabled",
12206                         plane->type == DRM_PLANE_TYPE_CURSOR ? "CURSOR" : "STANDARD",
12207                         plane->base.id, intel_plane->pipe,
12208                         crtc->base.primary == plane ? 0 : intel_plane->plane + 1,
12209                         drm_plane_index(plane));
12210                 DRM_DEBUG_KMS("\tFB:%d, fb = %ux%u format = 0x%x",
12211                         fb->base.id, fb->width, fb->height, fb->pixel_format);
12212                 DRM_DEBUG_KMS("\tscaler:%d src (%u, %u) %ux%u dst (%u, %u) %ux%u\n",
12213                         state->scaler_id,
12214                         state->src.x1 >> 16, state->src.y1 >> 16,
12215                         drm_rect_width(&state->src) >> 16,
12216                         drm_rect_height(&state->src) >> 16,
12217                         state->dst.x1, state->dst.y1,
12218                         drm_rect_width(&state->dst), drm_rect_height(&state->dst));
12219         }
12220 }
12221
12222 static bool check_digital_port_conflicts(struct drm_atomic_state *state)
12223 {
12224         struct drm_device *dev = state->dev;
12225         struct drm_connector *connector;
12226         unsigned int used_ports = 0;
12227
12228         /*
12229          * Walk the connector list instead of the encoder
12230          * list to detect the problem on ddi platforms
12231          * where there's just one encoder per digital port.
12232          */
12233         drm_for_each_connector(connector, dev) {
12234                 struct drm_connector_state *connector_state;
12235                 struct intel_encoder *encoder;
12236
12237                 connector_state = drm_atomic_get_existing_connector_state(state, connector);
12238                 if (!connector_state)
12239                         connector_state = connector->state;
12240
12241                 if (!connector_state->best_encoder)
12242                         continue;
12243
12244                 encoder = to_intel_encoder(connector_state->best_encoder);
12245
12246                 WARN_ON(!connector_state->crtc);
12247
12248                 switch (encoder->type) {
12249                         unsigned int port_mask;
12250                 case INTEL_OUTPUT_UNKNOWN:
12251                         if (WARN_ON(!HAS_DDI(dev)))
12252                                 break;
12253                 case INTEL_OUTPUT_DISPLAYPORT:
12254                 case INTEL_OUTPUT_HDMI:
12255                 case INTEL_OUTPUT_EDP:
12256                         port_mask = 1 << enc_to_dig_port(&encoder->base)->port;
12257
12258                         /* the same port mustn't appear more than once */
12259                         if (used_ports & port_mask)
12260                                 return false;
12261
12262                         used_ports |= port_mask;
12263                 default:
12264                         break;
12265                 }
12266         }
12267
12268         return true;
12269 }
12270
12271 static void
12272 clear_intel_crtc_state(struct intel_crtc_state *crtc_state)
12273 {
12274         struct drm_crtc_state tmp_state;
12275         struct intel_crtc_scaler_state scaler_state;
12276         struct intel_dpll_hw_state dpll_hw_state;
12277         struct intel_shared_dpll *shared_dpll;
12278         uint32_t ddi_pll_sel;
12279         bool force_thru;
12280
12281         /* FIXME: before the switch to atomic started, a new pipe_config was
12282          * kzalloc'd. Code that depends on any field being zero should be
12283          * fixed, so that the crtc_state can be safely duplicated. For now,
12284          * only fields that are know to not cause problems are preserved. */
12285
12286         tmp_state = crtc_state->base;
12287         scaler_state = crtc_state->scaler_state;
12288         shared_dpll = crtc_state->shared_dpll;
12289         dpll_hw_state = crtc_state->dpll_hw_state;
12290         ddi_pll_sel = crtc_state->ddi_pll_sel;
12291         force_thru = crtc_state->pch_pfit.force_thru;
12292
12293         memset(crtc_state, 0, sizeof *crtc_state);
12294
12295         crtc_state->base = tmp_state;
12296         crtc_state->scaler_state = scaler_state;
12297         crtc_state->shared_dpll = shared_dpll;
12298         crtc_state->dpll_hw_state = dpll_hw_state;
12299         crtc_state->ddi_pll_sel = ddi_pll_sel;
12300         crtc_state->pch_pfit.force_thru = force_thru;
12301 }
12302
12303 static int
12304 intel_modeset_pipe_config(struct drm_crtc *crtc,
12305                           struct intel_crtc_state *pipe_config)
12306 {
12307         struct drm_atomic_state *state = pipe_config->base.state;
12308         struct intel_encoder *encoder;
12309         struct drm_connector *connector;
12310         struct drm_connector_state *connector_state;
12311         int base_bpp, ret = -EINVAL;
12312         int i;
12313         bool retry = true;
12314
12315         clear_intel_crtc_state(pipe_config);
12316
12317         pipe_config->cpu_transcoder =
12318                 (enum transcoder) to_intel_crtc(crtc)->pipe;
12319
12320         /*
12321          * Sanitize sync polarity flags based on requested ones. If neither
12322          * positive or negative polarity is requested, treat this as meaning
12323          * negative polarity.
12324          */
12325         if (!(pipe_config->base.adjusted_mode.flags &
12326               (DRM_MODE_FLAG_PHSYNC | DRM_MODE_FLAG_NHSYNC)))
12327                 pipe_config->base.adjusted_mode.flags |= DRM_MODE_FLAG_NHSYNC;
12328
12329         if (!(pipe_config->base.adjusted_mode.flags &
12330               (DRM_MODE_FLAG_PVSYNC | DRM_MODE_FLAG_NVSYNC)))
12331                 pipe_config->base.adjusted_mode.flags |= DRM_MODE_FLAG_NVSYNC;
12332
12333         base_bpp = compute_baseline_pipe_bpp(to_intel_crtc(crtc),
12334                                              pipe_config);
12335         if (base_bpp < 0)
12336                 goto fail;
12337
12338         /*
12339          * Determine the real pipe dimensions. Note that stereo modes can
12340          * increase the actual pipe size due to the frame doubling and
12341          * insertion of additional space for blanks between the frame. This
12342          * is stored in the crtc timings. We use the requested mode to do this
12343          * computation to clearly distinguish it from the adjusted mode, which
12344          * can be changed by the connectors in the below retry loop.
12345          */
12346         drm_crtc_get_hv_timing(&pipe_config->base.mode,
12347                                &pipe_config->pipe_src_w,
12348                                &pipe_config->pipe_src_h);
12349
12350 encoder_retry:
12351         /* Ensure the port clock defaults are reset when retrying. */
12352         pipe_config->port_clock = 0;
12353         pipe_config->pixel_multiplier = 1;
12354
12355         /* Fill in default crtc timings, allow encoders to overwrite them. */
12356         drm_mode_set_crtcinfo(&pipe_config->base.adjusted_mode,
12357                               CRTC_STEREO_DOUBLE);
12358
12359         /* Pass our mode to the connectors and the CRTC to give them a chance to
12360          * adjust it according to limitations or connector properties, and also
12361          * a chance to reject the mode entirely.
12362          */
12363         for_each_connector_in_state(state, connector, connector_state, i) {
12364                 if (connector_state->crtc != crtc)
12365                         continue;
12366
12367                 encoder = to_intel_encoder(connector_state->best_encoder);
12368
12369                 if (!(encoder->compute_config(encoder, pipe_config))) {
12370                         DRM_DEBUG_KMS("Encoder config failure\n");
12371                         goto fail;
12372                 }
12373         }
12374
12375         /* Set default port clock if not overwritten by the encoder. Needs to be
12376          * done afterwards in case the encoder adjusts the mode. */
12377         if (!pipe_config->port_clock)
12378                 pipe_config->port_clock = pipe_config->base.adjusted_mode.crtc_clock
12379                         * pipe_config->pixel_multiplier;
12380
12381         ret = intel_crtc_compute_config(to_intel_crtc(crtc), pipe_config);
12382         if (ret < 0) {
12383                 DRM_DEBUG_KMS("CRTC fixup failed\n");
12384                 goto fail;
12385         }
12386
12387         if (ret == RETRY) {
12388                 if (WARN(!retry, "loop in pipe configuration computation\n")) {
12389                         ret = -EINVAL;
12390                         goto fail;
12391                 }
12392
12393                 DRM_DEBUG_KMS("CRTC bw constrained, retrying\n");
12394                 retry = false;
12395                 goto encoder_retry;
12396         }
12397
12398         /* Dithering seems to not pass-through bits correctly when it should, so
12399          * only enable it on 6bpc panels. */
12400         pipe_config->dither = pipe_config->pipe_bpp == 6*3;
12401         DRM_DEBUG_KMS("hw max bpp: %i, pipe bpp: %i, dithering: %i\n",
12402                       base_bpp, pipe_config->pipe_bpp, pipe_config->dither);
12403
12404 fail:
12405         return ret;
12406 }
12407
12408 static void
12409 intel_modeset_update_crtc_state(struct drm_atomic_state *state)
12410 {
12411         struct drm_crtc *crtc;
12412         struct drm_crtc_state *crtc_state;
12413         int i;
12414
12415         /* Double check state. */
12416         for_each_crtc_in_state(state, crtc, crtc_state, i) {
12417                 to_intel_crtc(crtc)->config = to_intel_crtc_state(crtc->state);
12418
12419                 /* Update hwmode for vblank functions */
12420                 if (crtc->state->active)
12421                         crtc->hwmode = crtc->state->adjusted_mode;
12422                 else
12423                         crtc->hwmode.crtc_clock = 0;
12424
12425                 /*
12426                  * Update legacy state to satisfy fbc code. This can
12427                  * be removed when fbc uses the atomic state.
12428                  */
12429                 if (drm_atomic_get_existing_plane_state(state, crtc->primary)) {
12430                         struct drm_plane_state *plane_state = crtc->primary->state;
12431
12432                         crtc->primary->fb = plane_state->fb;
12433                         crtc->x = plane_state->src_x >> 16;
12434                         crtc->y = plane_state->src_y >> 16;
12435                 }
12436         }
12437 }
12438
12439 static bool intel_fuzzy_clock_check(int clock1, int clock2)
12440 {
12441         int diff;
12442
12443         if (clock1 == clock2)
12444                 return true;
12445
12446         if (!clock1 || !clock2)
12447                 return false;
12448
12449         diff = abs(clock1 - clock2);
12450
12451         if (((((diff + clock1 + clock2) * 100)) / (clock1 + clock2)) < 105)
12452                 return true;
12453
12454         return false;
12455 }
12456
12457 #define for_each_intel_crtc_masked(dev, mask, intel_crtc) \
12458         list_for_each_entry((intel_crtc), \
12459                             &(dev)->mode_config.crtc_list, \
12460                             base.head) \
12461                 for_each_if (mask & (1 <<(intel_crtc)->pipe))
12462
12463 static bool
12464 intel_compare_m_n(unsigned int m, unsigned int n,
12465                   unsigned int m2, unsigned int n2,
12466                   bool exact)
12467 {
12468         if (m == m2 && n == n2)
12469                 return true;
12470
12471         if (exact || !m || !n || !m2 || !n2)
12472                 return false;
12473
12474         BUILD_BUG_ON(DATA_LINK_M_N_MASK > INT_MAX);
12475
12476         if (n > n2) {
12477                 while (n > n2) {
12478                         m2 <<= 1;
12479                         n2 <<= 1;
12480                 }
12481         } else if (n < n2) {
12482                 while (n < n2) {
12483                         m <<= 1;
12484                         n <<= 1;
12485                 }
12486         }
12487
12488         if (n != n2)
12489                 return false;
12490
12491         return intel_fuzzy_clock_check(m, m2);
12492 }
12493
12494 static bool
12495 intel_compare_link_m_n(const struct intel_link_m_n *m_n,
12496                        struct intel_link_m_n *m2_n2,
12497                        bool adjust)
12498 {
12499         if (m_n->tu == m2_n2->tu &&
12500             intel_compare_m_n(m_n->gmch_m, m_n->gmch_n,
12501                               m2_n2->gmch_m, m2_n2->gmch_n, !adjust) &&
12502             intel_compare_m_n(m_n->link_m, m_n->link_n,
12503                               m2_n2->link_m, m2_n2->link_n, !adjust)) {
12504                 if (adjust)
12505                         *m2_n2 = *m_n;
12506
12507                 return true;
12508         }
12509
12510         return false;
12511 }
12512
12513 static bool
12514 intel_pipe_config_compare(struct drm_device *dev,
12515                           struct intel_crtc_state *current_config,
12516                           struct intel_crtc_state *pipe_config,
12517                           bool adjust)
12518 {
12519         bool ret = true;
12520
12521 #define INTEL_ERR_OR_DBG_KMS(fmt, ...) \
12522         do { \
12523                 if (!adjust) \
12524                         DRM_ERROR(fmt, ##__VA_ARGS__); \
12525                 else \
12526                         DRM_DEBUG_KMS(fmt, ##__VA_ARGS__); \
12527         } while (0)
12528
12529 #define PIPE_CONF_CHECK_X(name) \
12530         if (current_config->name != pipe_config->name) { \
12531                 INTEL_ERR_OR_DBG_KMS("mismatch in " #name " " \
12532                           "(expected 0x%08x, found 0x%08x)\n", \
12533                           current_config->name, \
12534                           pipe_config->name); \
12535                 ret = false; \
12536         }
12537
12538 #define PIPE_CONF_CHECK_I(name) \
12539         if (current_config->name != pipe_config->name) { \
12540                 INTEL_ERR_OR_DBG_KMS("mismatch in " #name " " \
12541                           "(expected %i, found %i)\n", \
12542                           current_config->name, \
12543                           pipe_config->name); \
12544                 ret = false; \
12545         }
12546
12547 #define PIPE_CONF_CHECK_P(name) \
12548         if (current_config->name != pipe_config->name) { \
12549                 INTEL_ERR_OR_DBG_KMS("mismatch in " #name " " \
12550                           "(expected %p, found %p)\n", \
12551                           current_config->name, \
12552                           pipe_config->name); \
12553                 ret = false; \
12554         }
12555
12556 #define PIPE_CONF_CHECK_M_N(name) \
12557         if (!intel_compare_link_m_n(&current_config->name, \
12558                                     &pipe_config->name,\
12559                                     adjust)) { \
12560                 INTEL_ERR_OR_DBG_KMS("mismatch in " #name " " \
12561                           "(expected tu %i gmch %i/%i link %i/%i, " \
12562                           "found tu %i, gmch %i/%i link %i/%i)\n", \
12563                           current_config->name.tu, \
12564                           current_config->name.gmch_m, \
12565                           current_config->name.gmch_n, \
12566                           current_config->name.link_m, \
12567                           current_config->name.link_n, \
12568                           pipe_config->name.tu, \
12569                           pipe_config->name.gmch_m, \
12570                           pipe_config->name.gmch_n, \
12571                           pipe_config->name.link_m, \
12572                           pipe_config->name.link_n); \
12573                 ret = false; \
12574         }
12575
12576 #define PIPE_CONF_CHECK_M_N_ALT(name, alt_name) \
12577         if (!intel_compare_link_m_n(&current_config->name, \
12578                                     &pipe_config->name, adjust) && \
12579             !intel_compare_link_m_n(&current_config->alt_name, \
12580                                     &pipe_config->name, adjust)) { \
12581                 INTEL_ERR_OR_DBG_KMS("mismatch in " #name " " \
12582                           "(expected tu %i gmch %i/%i link %i/%i, " \
12583                           "or tu %i gmch %i/%i link %i/%i, " \
12584                           "found tu %i, gmch %i/%i link %i/%i)\n", \
12585                           current_config->name.tu, \
12586                           current_config->name.gmch_m, \
12587                           current_config->name.gmch_n, \
12588                           current_config->name.link_m, \
12589                           current_config->name.link_n, \
12590                           current_config->alt_name.tu, \
12591                           current_config->alt_name.gmch_m, \
12592                           current_config->alt_name.gmch_n, \
12593                           current_config->alt_name.link_m, \
12594                           current_config->alt_name.link_n, \
12595                           pipe_config->name.tu, \
12596                           pipe_config->name.gmch_m, \
12597                           pipe_config->name.gmch_n, \
12598                           pipe_config->name.link_m, \
12599                           pipe_config->name.link_n); \
12600                 ret = false; \
12601         }
12602
12603 /* This is required for BDW+ where there is only one set of registers for
12604  * switching between high and low RR.
12605  * This macro can be used whenever a comparison has to be made between one
12606  * hw state and multiple sw state variables.
12607  */
12608 #define PIPE_CONF_CHECK_I_ALT(name, alt_name) \
12609         if ((current_config->name != pipe_config->name) && \
12610                 (current_config->alt_name != pipe_config->name)) { \
12611                         INTEL_ERR_OR_DBG_KMS("mismatch in " #name " " \
12612                                   "(expected %i or %i, found %i)\n", \
12613                                   current_config->name, \
12614                                   current_config->alt_name, \
12615                                   pipe_config->name); \
12616                         ret = false; \
12617         }
12618
12619 #define PIPE_CONF_CHECK_FLAGS(name, mask)       \
12620         if ((current_config->name ^ pipe_config->name) & (mask)) { \
12621                 INTEL_ERR_OR_DBG_KMS("mismatch in " #name "(" #mask ") " \
12622                           "(expected %i, found %i)\n", \
12623                           current_config->name & (mask), \
12624                           pipe_config->name & (mask)); \
12625                 ret = false; \
12626         }
12627
12628 #define PIPE_CONF_CHECK_CLOCK_FUZZY(name) \
12629         if (!intel_fuzzy_clock_check(current_config->name, pipe_config->name)) { \
12630                 INTEL_ERR_OR_DBG_KMS("mismatch in " #name " " \
12631                           "(expected %i, found %i)\n", \
12632                           current_config->name, \
12633                           pipe_config->name); \
12634                 ret = false; \
12635         }
12636
12637 #define PIPE_CONF_QUIRK(quirk)  \
12638         ((current_config->quirks | pipe_config->quirks) & (quirk))
12639
12640         PIPE_CONF_CHECK_I(cpu_transcoder);
12641
12642         PIPE_CONF_CHECK_I(has_pch_encoder);
12643         PIPE_CONF_CHECK_I(fdi_lanes);
12644         PIPE_CONF_CHECK_M_N(fdi_m_n);
12645
12646         PIPE_CONF_CHECK_I(has_dp_encoder);
12647         PIPE_CONF_CHECK_I(lane_count);
12648
12649         if (INTEL_INFO(dev)->gen < 8) {
12650                 PIPE_CONF_CHECK_M_N(dp_m_n);
12651
12652                 if (current_config->has_drrs)
12653                         PIPE_CONF_CHECK_M_N(dp_m2_n2);
12654         } else
12655                 PIPE_CONF_CHECK_M_N_ALT(dp_m_n, dp_m2_n2);
12656
12657         PIPE_CONF_CHECK_I(has_dsi_encoder);
12658
12659         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hdisplay);
12660         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_htotal);
12661         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hblank_start);
12662         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hblank_end);
12663         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hsync_start);
12664         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hsync_end);
12665
12666         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vdisplay);
12667         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vtotal);
12668         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vblank_start);
12669         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vblank_end);
12670         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vsync_start);
12671         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vsync_end);
12672
12673         PIPE_CONF_CHECK_I(pixel_multiplier);
12674         PIPE_CONF_CHECK_I(has_hdmi_sink);
12675         if ((INTEL_INFO(dev)->gen < 8 && !IS_HASWELL(dev)) ||
12676             IS_VALLEYVIEW(dev) || IS_CHERRYVIEW(dev))
12677                 PIPE_CONF_CHECK_I(limited_color_range);
12678         PIPE_CONF_CHECK_I(has_infoframe);
12679
12680         PIPE_CONF_CHECK_I(has_audio);
12681
12682         PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
12683                               DRM_MODE_FLAG_INTERLACE);
12684
12685         if (!PIPE_CONF_QUIRK(PIPE_CONFIG_QUIRK_MODE_SYNC_FLAGS)) {
12686                 PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
12687                                       DRM_MODE_FLAG_PHSYNC);
12688                 PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
12689                                       DRM_MODE_FLAG_NHSYNC);
12690                 PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
12691                                       DRM_MODE_FLAG_PVSYNC);
12692                 PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
12693                                       DRM_MODE_FLAG_NVSYNC);
12694         }
12695
12696         PIPE_CONF_CHECK_X(gmch_pfit.control);
12697         /* pfit ratios are autocomputed by the hw on gen4+ */
12698         if (INTEL_INFO(dev)->gen < 4)
12699                 PIPE_CONF_CHECK_I(gmch_pfit.pgm_ratios);
12700         PIPE_CONF_CHECK_X(gmch_pfit.lvds_border_bits);
12701
12702         if (!adjust) {
12703                 PIPE_CONF_CHECK_I(pipe_src_w);
12704                 PIPE_CONF_CHECK_I(pipe_src_h);
12705
12706                 PIPE_CONF_CHECK_I(pch_pfit.enabled);
12707                 if (current_config->pch_pfit.enabled) {
12708                         PIPE_CONF_CHECK_X(pch_pfit.pos);
12709                         PIPE_CONF_CHECK_X(pch_pfit.size);
12710                 }
12711
12712                 PIPE_CONF_CHECK_I(scaler_state.scaler_id);
12713         }
12714
12715         /* BDW+ don't expose a synchronous way to read the state */
12716         if (IS_HASWELL(dev))
12717                 PIPE_CONF_CHECK_I(ips_enabled);
12718
12719         PIPE_CONF_CHECK_I(double_wide);
12720
12721         PIPE_CONF_CHECK_X(ddi_pll_sel);
12722
12723         PIPE_CONF_CHECK_P(shared_dpll);
12724         PIPE_CONF_CHECK_X(dpll_hw_state.dpll);
12725         PIPE_CONF_CHECK_X(dpll_hw_state.dpll_md);
12726         PIPE_CONF_CHECK_X(dpll_hw_state.fp0);
12727         PIPE_CONF_CHECK_X(dpll_hw_state.fp1);
12728         PIPE_CONF_CHECK_X(dpll_hw_state.wrpll);
12729         PIPE_CONF_CHECK_X(dpll_hw_state.spll);
12730         PIPE_CONF_CHECK_X(dpll_hw_state.ctrl1);
12731         PIPE_CONF_CHECK_X(dpll_hw_state.cfgcr1);
12732         PIPE_CONF_CHECK_X(dpll_hw_state.cfgcr2);
12733
12734         if (IS_G4X(dev) || INTEL_INFO(dev)->gen >= 5)
12735                 PIPE_CONF_CHECK_I(pipe_bpp);
12736
12737         PIPE_CONF_CHECK_CLOCK_FUZZY(base.adjusted_mode.crtc_clock);
12738         PIPE_CONF_CHECK_CLOCK_FUZZY(port_clock);
12739
12740 #undef PIPE_CONF_CHECK_X
12741 #undef PIPE_CONF_CHECK_I
12742 #undef PIPE_CONF_CHECK_P
12743 #undef PIPE_CONF_CHECK_I_ALT
12744 #undef PIPE_CONF_CHECK_FLAGS
12745 #undef PIPE_CONF_CHECK_CLOCK_FUZZY
12746 #undef PIPE_CONF_QUIRK
12747 #undef INTEL_ERR_OR_DBG_KMS
12748
12749         return ret;
12750 }
12751
12752 static void intel_pipe_config_sanity_check(struct drm_i915_private *dev_priv,
12753                                            const struct intel_crtc_state *pipe_config)
12754 {
12755         if (pipe_config->has_pch_encoder) {
12756                 int fdi_dotclock = intel_dotclock_calculate(intel_fdi_link_freq(dev_priv, pipe_config),
12757                                                             &pipe_config->fdi_m_n);
12758                 int dotclock = pipe_config->base.adjusted_mode.crtc_clock;
12759
12760                 /*
12761                  * FDI already provided one idea for the dotclock.
12762                  * Yell if the encoder disagrees.
12763                  */
12764                 WARN(!intel_fuzzy_clock_check(fdi_dotclock, dotclock),
12765                      "FDI dotclock and encoder dotclock mismatch, fdi: %i, encoder: %i\n",
12766                      fdi_dotclock, dotclock);
12767         }
12768 }
12769
12770 static void check_wm_state(struct drm_device *dev)
12771 {
12772         struct drm_i915_private *dev_priv = dev->dev_private;
12773         struct skl_ddb_allocation hw_ddb, *sw_ddb;
12774         struct intel_crtc *intel_crtc;
12775         int plane;
12776
12777         if (INTEL_INFO(dev)->gen < 9)
12778                 return;
12779
12780         skl_ddb_get_hw_state(dev_priv, &hw_ddb);
12781         sw_ddb = &dev_priv->wm.skl_hw.ddb;
12782
12783         for_each_intel_crtc(dev, intel_crtc) {
12784                 struct skl_ddb_entry *hw_entry, *sw_entry;
12785                 const enum pipe pipe = intel_crtc->pipe;
12786
12787                 if (!intel_crtc->active)
12788                         continue;
12789
12790                 /* planes */
12791                 for_each_plane(dev_priv, pipe, plane) {
12792                         hw_entry = &hw_ddb.plane[pipe][plane];
12793                         sw_entry = &sw_ddb->plane[pipe][plane];
12794
12795                         if (skl_ddb_entry_equal(hw_entry, sw_entry))
12796                                 continue;
12797
12798                         DRM_ERROR("mismatch in DDB state pipe %c plane %d "
12799                                   "(expected (%u,%u), found (%u,%u))\n",
12800                                   pipe_name(pipe), plane + 1,
12801                                   sw_entry->start, sw_entry->end,
12802                                   hw_entry->start, hw_entry->end);
12803                 }
12804
12805                 /* cursor */
12806                 hw_entry = &hw_ddb.plane[pipe][PLANE_CURSOR];
12807                 sw_entry = &sw_ddb->plane[pipe][PLANE_CURSOR];
12808
12809                 if (skl_ddb_entry_equal(hw_entry, sw_entry))
12810                         continue;
12811
12812                 DRM_ERROR("mismatch in DDB state pipe %c cursor "
12813                           "(expected (%u,%u), found (%u,%u))\n",
12814                           pipe_name(pipe),
12815                           sw_entry->start, sw_entry->end,
12816                           hw_entry->start, hw_entry->end);
12817         }
12818 }
12819
12820 static void
12821 check_connector_state(struct drm_device *dev,
12822                       struct drm_atomic_state *old_state)
12823 {
12824         struct drm_connector_state *old_conn_state;
12825         struct drm_connector *connector;
12826         int i;
12827
12828         for_each_connector_in_state(old_state, connector, old_conn_state, i) {
12829                 struct drm_encoder *encoder = connector->encoder;
12830                 struct drm_connector_state *state = connector->state;
12831
12832                 /* This also checks the encoder/connector hw state with the
12833                  * ->get_hw_state callbacks. */
12834                 intel_connector_check_state(to_intel_connector(connector));
12835
12836                 I915_STATE_WARN(state->best_encoder != encoder,
12837                      "connector's atomic encoder doesn't match legacy encoder\n");
12838         }
12839 }
12840
12841 static void
12842 check_encoder_state(struct drm_device *dev)
12843 {
12844         struct intel_encoder *encoder;
12845         struct intel_connector *connector;
12846
12847         for_each_intel_encoder(dev, encoder) {
12848                 bool enabled = false;
12849                 enum pipe pipe;
12850
12851                 DRM_DEBUG_KMS("[ENCODER:%d:%s]\n",
12852                               encoder->base.base.id,
12853                               encoder->base.name);
12854
12855                 for_each_intel_connector(dev, connector) {
12856                         if (connector->base.state->best_encoder != &encoder->base)
12857                                 continue;
12858                         enabled = true;
12859
12860                         I915_STATE_WARN(connector->base.state->crtc !=
12861                                         encoder->base.crtc,
12862                              "connector's crtc doesn't match encoder crtc\n");
12863                 }
12864
12865                 I915_STATE_WARN(!!encoder->base.crtc != enabled,
12866                      "encoder's enabled state mismatch "
12867                      "(expected %i, found %i)\n",
12868                      !!encoder->base.crtc, enabled);
12869
12870                 if (!encoder->base.crtc) {
12871                         bool active;
12872
12873                         active = encoder->get_hw_state(encoder, &pipe);
12874                         I915_STATE_WARN(active,
12875                              "encoder detached but still enabled on pipe %c.\n",
12876                              pipe_name(pipe));
12877                 }
12878         }
12879 }
12880
12881 static void
12882 check_crtc_state(struct drm_device *dev, struct drm_atomic_state *old_state)
12883 {
12884         struct drm_i915_private *dev_priv = dev->dev_private;
12885         struct intel_encoder *encoder;
12886         struct drm_crtc_state *old_crtc_state;
12887         struct drm_crtc *crtc;
12888         int i;
12889
12890         for_each_crtc_in_state(old_state, crtc, old_crtc_state, i) {
12891                 struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
12892                 struct intel_crtc_state *pipe_config, *sw_config;
12893                 bool active;
12894
12895                 if (!needs_modeset(crtc->state) &&
12896                     !to_intel_crtc_state(crtc->state)->update_pipe)
12897                         continue;
12898
12899                 __drm_atomic_helper_crtc_destroy_state(crtc, old_crtc_state);
12900                 pipe_config = to_intel_crtc_state(old_crtc_state);
12901                 memset(pipe_config, 0, sizeof(*pipe_config));
12902                 pipe_config->base.crtc = crtc;
12903                 pipe_config->base.state = old_state;
12904
12905                 DRM_DEBUG_KMS("[CRTC:%d]\n",
12906                               crtc->base.id);
12907
12908                 active = dev_priv->display.get_pipe_config(intel_crtc,
12909                                                            pipe_config);
12910
12911                 /* hw state is inconsistent with the pipe quirk */
12912                 if ((intel_crtc->pipe == PIPE_A && dev_priv->quirks & QUIRK_PIPEA_FORCE) ||
12913                     (intel_crtc->pipe == PIPE_B && dev_priv->quirks & QUIRK_PIPEB_FORCE))
12914                         active = crtc->state->active;
12915
12916                 I915_STATE_WARN(crtc->state->active != active,
12917                      "crtc active state doesn't match with hw state "
12918                      "(expected %i, found %i)\n", crtc->state->active, active);
12919
12920                 I915_STATE_WARN(intel_crtc->active != crtc->state->active,
12921                      "transitional active state does not match atomic hw state "
12922                      "(expected %i, found %i)\n", crtc->state->active, intel_crtc->active);
12923
12924                 for_each_encoder_on_crtc(dev, crtc, encoder) {
12925                         enum pipe pipe;
12926
12927                         active = encoder->get_hw_state(encoder, &pipe);
12928                         I915_STATE_WARN(active != crtc->state->active,
12929                                 "[ENCODER:%i] active %i with crtc active %i\n",
12930                                 encoder->base.base.id, active, crtc->state->active);
12931
12932                         I915_STATE_WARN(active && intel_crtc->pipe != pipe,
12933                                         "Encoder connected to wrong pipe %c\n",
12934                                         pipe_name(pipe));
12935
12936                         if (active)
12937                                 encoder->get_config(encoder, pipe_config);
12938                 }
12939
12940                 if (!crtc->state->active)
12941                         continue;
12942
12943                 intel_pipe_config_sanity_check(dev_priv, pipe_config);
12944
12945                 sw_config = to_intel_crtc_state(crtc->state);
12946                 if (!intel_pipe_config_compare(dev, sw_config,
12947                                                pipe_config, false)) {
12948                         I915_STATE_WARN(1, "pipe state doesn't match!\n");
12949                         intel_dump_pipe_config(intel_crtc, pipe_config,
12950                                                "[hw state]");
12951                         intel_dump_pipe_config(intel_crtc, sw_config,
12952                                                "[sw state]");
12953                 }
12954         }
12955 }
12956
12957 static void
12958 check_shared_dpll_state(struct drm_device *dev)
12959 {
12960         struct drm_i915_private *dev_priv = dev->dev_private;
12961         struct intel_crtc *crtc;
12962         struct intel_dpll_hw_state dpll_hw_state;
12963         int i;
12964
12965         for (i = 0; i < dev_priv->num_shared_dpll; i++) {
12966                 struct intel_shared_dpll *pll =
12967                         intel_get_shared_dpll_by_id(dev_priv, i);
12968                 unsigned enabled_crtcs = 0, active_crtcs = 0;
12969                 bool active;
12970
12971                 memset(&dpll_hw_state, 0, sizeof(dpll_hw_state));
12972
12973                 DRM_DEBUG_KMS("%s\n", pll->name);
12974
12975                 active = pll->funcs.get_hw_state(dev_priv, pll, &dpll_hw_state);
12976
12977                 I915_STATE_WARN(pll->active_mask & ~pll->config.crtc_mask,
12978                      "more active pll users than references: %x vs %x\n",
12979                      pll->active_mask, pll->config.crtc_mask);
12980
12981                 if (!(pll->flags & INTEL_DPLL_ALWAYS_ON)) {
12982                         I915_STATE_WARN(!pll->on && pll->active_mask,
12983                              "pll in active use but not on in sw tracking\n");
12984                         I915_STATE_WARN(pll->on && !pll->active_mask,
12985                              "pll is on but not used by any active crtc\n");
12986                         I915_STATE_WARN(pll->on != active,
12987                              "pll on state mismatch (expected %i, found %i)\n",
12988                              pll->on, active);
12989                 }
12990
12991                 for_each_intel_crtc(dev, crtc) {
12992                         if (crtc->base.state->enable && crtc->config->shared_dpll == pll)
12993                                 enabled_crtcs |= 1 << drm_crtc_index(&crtc->base);
12994                         if (crtc->base.state->active && crtc->config->shared_dpll == pll)
12995                                 active_crtcs |= 1 << drm_crtc_index(&crtc->base);
12996                 }
12997
12998                 I915_STATE_WARN(pll->active_mask != active_crtcs,
12999                      "pll active crtcs mismatch (expected %x, found %x)\n",
13000                      pll->active_mask, active_crtcs);
13001                 I915_STATE_WARN(pll->config.crtc_mask != enabled_crtcs,
13002                      "pll enabled crtcs mismatch (expected %x, found %x)\n",
13003                      pll->config.crtc_mask, enabled_crtcs);
13004
13005                 I915_STATE_WARN(pll->on && memcmp(&pll->config.hw_state, &dpll_hw_state,
13006                                        sizeof(dpll_hw_state)),
13007                      "pll hw state mismatch\n");
13008         }
13009 }
13010
13011 static void
13012 intel_modeset_check_state(struct drm_device *dev,
13013                           struct drm_atomic_state *old_state)
13014 {
13015         check_wm_state(dev);
13016         check_connector_state(dev, old_state);
13017         check_encoder_state(dev);
13018         check_crtc_state(dev, old_state);
13019         check_shared_dpll_state(dev);
13020 }
13021
13022 static void update_scanline_offset(struct intel_crtc *crtc)
13023 {
13024         struct drm_device *dev = crtc->base.dev;
13025
13026         /*
13027          * The scanline counter increments at the leading edge of hsync.
13028          *
13029          * On most platforms it starts counting from vtotal-1 on the
13030          * first active line. That means the scanline counter value is
13031          * always one less than what we would expect. Ie. just after
13032          * start of vblank, which also occurs at start of hsync (on the
13033          * last active line), the scanline counter will read vblank_start-1.
13034          *
13035          * On gen2 the scanline counter starts counting from 1 instead
13036          * of vtotal-1, so we have to subtract one (or rather add vtotal-1
13037          * to keep the value positive), instead of adding one.
13038          *
13039          * On HSW+ the behaviour of the scanline counter depends on the output
13040          * type. For DP ports it behaves like most other platforms, but on HDMI
13041          * there's an extra 1 line difference. So we need to add two instead of
13042          * one to the value.
13043          */
13044         if (IS_GEN2(dev)) {
13045                 const struct drm_display_mode *adjusted_mode = &crtc->config->base.adjusted_mode;
13046                 int vtotal;
13047
13048                 vtotal = adjusted_mode->crtc_vtotal;
13049                 if (adjusted_mode->flags & DRM_MODE_FLAG_INTERLACE)
13050                         vtotal /= 2;
13051
13052                 crtc->scanline_offset = vtotal - 1;
13053         } else if (HAS_DDI(dev) &&
13054                    intel_pipe_has_type(crtc, INTEL_OUTPUT_HDMI)) {
13055                 crtc->scanline_offset = 2;
13056         } else
13057                 crtc->scanline_offset = 1;
13058 }
13059
13060 static void intel_modeset_clear_plls(struct drm_atomic_state *state)
13061 {
13062         struct drm_device *dev = state->dev;
13063         struct drm_i915_private *dev_priv = to_i915(dev);
13064         struct intel_shared_dpll_config *shared_dpll = NULL;
13065         struct drm_crtc *crtc;
13066         struct drm_crtc_state *crtc_state;
13067         int i;
13068
13069         if (!dev_priv->display.crtc_compute_clock)
13070                 return;
13071
13072         for_each_crtc_in_state(state, crtc, crtc_state, i) {
13073                 struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
13074                 struct intel_shared_dpll *old_dpll =
13075                         to_intel_crtc_state(crtc->state)->shared_dpll;
13076
13077                 if (!needs_modeset(crtc_state))
13078                         continue;
13079
13080                 to_intel_crtc_state(crtc_state)->shared_dpll = NULL;
13081
13082                 if (!old_dpll)
13083                         continue;
13084
13085                 if (!shared_dpll)
13086                         shared_dpll = intel_atomic_get_shared_dpll_state(state);
13087
13088                 intel_shared_dpll_config_put(shared_dpll, old_dpll, intel_crtc);
13089         }
13090 }
13091
13092 /*
13093  * This implements the workaround described in the "notes" section of the mode
13094  * set sequence documentation. When going from no pipes or single pipe to
13095  * multiple pipes, and planes are enabled after the pipe, we need to wait at
13096  * least 2 vblanks on the first pipe before enabling planes on the second pipe.
13097  */
13098 static int haswell_mode_set_planes_workaround(struct drm_atomic_state *state)
13099 {
13100         struct drm_crtc_state *crtc_state;
13101         struct intel_crtc *intel_crtc;
13102         struct drm_crtc *crtc;
13103         struct intel_crtc_state *first_crtc_state = NULL;
13104         struct intel_crtc_state *other_crtc_state = NULL;
13105         enum pipe first_pipe = INVALID_PIPE, enabled_pipe = INVALID_PIPE;
13106         int i;
13107
13108         /* look at all crtc's that are going to be enabled in during modeset */
13109         for_each_crtc_in_state(state, crtc, crtc_state, i) {
13110                 intel_crtc = to_intel_crtc(crtc);
13111
13112                 if (!crtc_state->active || !needs_modeset(crtc_state))
13113                         continue;
13114
13115                 if (first_crtc_state) {
13116                         other_crtc_state = to_intel_crtc_state(crtc_state);
13117                         break;
13118                 } else {
13119                         first_crtc_state = to_intel_crtc_state(crtc_state);
13120                         first_pipe = intel_crtc->pipe;
13121                 }
13122         }
13123
13124         /* No workaround needed? */
13125         if (!first_crtc_state)
13126                 return 0;
13127
13128         /* w/a possibly needed, check how many crtc's are already enabled. */
13129         for_each_intel_crtc(state->dev, intel_crtc) {
13130                 struct intel_crtc_state *pipe_config;
13131
13132                 pipe_config = intel_atomic_get_crtc_state(state, intel_crtc);
13133                 if (IS_ERR(pipe_config))
13134                         return PTR_ERR(pipe_config);
13135
13136                 pipe_config->hsw_workaround_pipe = INVALID_PIPE;
13137
13138                 if (!pipe_config->base.active ||
13139                     needs_modeset(&pipe_config->base))
13140                         continue;
13141
13142                 /* 2 or more enabled crtcs means no need for w/a */
13143                 if (enabled_pipe != INVALID_PIPE)
13144                         return 0;
13145
13146                 enabled_pipe = intel_crtc->pipe;
13147         }
13148
13149         if (enabled_pipe != INVALID_PIPE)
13150                 first_crtc_state->hsw_workaround_pipe = enabled_pipe;
13151         else if (other_crtc_state)
13152                 other_crtc_state->hsw_workaround_pipe = first_pipe;
13153
13154         return 0;
13155 }
13156
13157 static int intel_modeset_all_pipes(struct drm_atomic_state *state)
13158 {
13159         struct drm_crtc *crtc;
13160         struct drm_crtc_state *crtc_state;
13161         int ret = 0;
13162
13163         /* add all active pipes to the state */
13164         for_each_crtc(state->dev, crtc) {
13165                 crtc_state = drm_atomic_get_crtc_state(state, crtc);
13166                 if (IS_ERR(crtc_state))
13167                         return PTR_ERR(crtc_state);
13168
13169                 if (!crtc_state->active || needs_modeset(crtc_state))
13170                         continue;
13171
13172                 crtc_state->mode_changed = true;
13173
13174                 ret = drm_atomic_add_affected_connectors(state, crtc);
13175                 if (ret)
13176                         break;
13177
13178                 ret = drm_atomic_add_affected_planes(state, crtc);
13179                 if (ret)
13180                         break;
13181         }
13182
13183         return ret;
13184 }
13185
13186 static int intel_modeset_checks(struct drm_atomic_state *state)
13187 {
13188         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
13189         struct drm_i915_private *dev_priv = state->dev->dev_private;
13190         struct drm_crtc *crtc;
13191         struct drm_crtc_state *crtc_state;
13192         int ret = 0, i;
13193
13194         if (!check_digital_port_conflicts(state)) {
13195                 DRM_DEBUG_KMS("rejecting conflicting digital port configuration\n");
13196                 return -EINVAL;
13197         }
13198
13199         intel_state->modeset = true;
13200         intel_state->active_crtcs = dev_priv->active_crtcs;
13201
13202         for_each_crtc_in_state(state, crtc, crtc_state, i) {
13203                 if (crtc_state->active)
13204                         intel_state->active_crtcs |= 1 << i;
13205                 else
13206                         intel_state->active_crtcs &= ~(1 << i);
13207         }
13208
13209         /*
13210          * See if the config requires any additional preparation, e.g.
13211          * to adjust global state with pipes off.  We need to do this
13212          * here so we can get the modeset_pipe updated config for the new
13213          * mode set on this crtc.  For other crtcs we need to use the
13214          * adjusted_mode bits in the crtc directly.
13215          */
13216         if (dev_priv->display.modeset_calc_cdclk) {
13217                 ret = dev_priv->display.modeset_calc_cdclk(state);
13218
13219                 if (!ret && intel_state->dev_cdclk != dev_priv->cdclk_freq)
13220                         ret = intel_modeset_all_pipes(state);
13221
13222                 if (ret < 0)
13223                         return ret;
13224
13225                 DRM_DEBUG_KMS("New cdclk calculated to be atomic %u, actual %u\n",
13226                               intel_state->cdclk, intel_state->dev_cdclk);
13227         } else
13228                 to_intel_atomic_state(state)->cdclk = dev_priv->atomic_cdclk_freq;
13229
13230         intel_modeset_clear_plls(state);
13231
13232         if (IS_HASWELL(dev_priv))
13233                 return haswell_mode_set_planes_workaround(state);
13234
13235         return 0;
13236 }
13237
13238 /*
13239  * Handle calculation of various watermark data at the end of the atomic check
13240  * phase.  The code here should be run after the per-crtc and per-plane 'check'
13241  * handlers to ensure that all derived state has been updated.
13242  */
13243 static void calc_watermark_data(struct drm_atomic_state *state)
13244 {
13245         struct drm_device *dev = state->dev;
13246         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
13247         struct drm_crtc *crtc;
13248         struct drm_crtc_state *cstate;
13249         struct drm_plane *plane;
13250         struct drm_plane_state *pstate;
13251
13252         /*
13253          * Calculate watermark configuration details now that derived
13254          * plane/crtc state is all properly updated.
13255          */
13256         drm_for_each_crtc(crtc, dev) {
13257                 cstate = drm_atomic_get_existing_crtc_state(state, crtc) ?:
13258                         crtc->state;
13259
13260                 if (cstate->active)
13261                         intel_state->wm_config.num_pipes_active++;
13262         }
13263         drm_for_each_legacy_plane(plane, dev) {
13264                 pstate = drm_atomic_get_existing_plane_state(state, plane) ?:
13265                         plane->state;
13266
13267                 if (!to_intel_plane_state(pstate)->visible)
13268                         continue;
13269
13270                 intel_state->wm_config.sprites_enabled = true;
13271                 if (pstate->crtc_w != pstate->src_w >> 16 ||
13272                     pstate->crtc_h != pstate->src_h >> 16)
13273                         intel_state->wm_config.sprites_scaled = true;
13274         }
13275 }
13276
13277 /**
13278  * intel_atomic_check - validate state object
13279  * @dev: drm device
13280  * @state: state to validate
13281  */
13282 static int intel_atomic_check(struct drm_device *dev,
13283                               struct drm_atomic_state *state)
13284 {
13285         struct drm_i915_private *dev_priv = to_i915(dev);
13286         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
13287         struct drm_crtc *crtc;
13288         struct drm_crtc_state *crtc_state;
13289         int ret, i;
13290         bool any_ms = false;
13291
13292         ret = drm_atomic_helper_check_modeset(dev, state);
13293         if (ret)
13294                 return ret;
13295
13296         for_each_crtc_in_state(state, crtc, crtc_state, i) {
13297                 struct intel_crtc_state *pipe_config =
13298                         to_intel_crtc_state(crtc_state);
13299
13300                 /* Catch I915_MODE_FLAG_INHERITED */
13301                 if (crtc_state->mode.private_flags != crtc->state->mode.private_flags)
13302                         crtc_state->mode_changed = true;
13303
13304                 if (!crtc_state->enable) {
13305                         if (needs_modeset(crtc_state))
13306                                 any_ms = true;
13307                         continue;
13308                 }
13309
13310                 if (!needs_modeset(crtc_state))
13311                         continue;
13312
13313                 /* FIXME: For only active_changed we shouldn't need to do any
13314                  * state recomputation at all. */
13315
13316                 ret = drm_atomic_add_affected_connectors(state, crtc);
13317                 if (ret)
13318                         return ret;
13319
13320                 ret = intel_modeset_pipe_config(crtc, pipe_config);
13321                 if (ret)
13322                         return ret;
13323
13324                 if (i915.fastboot &&
13325                     intel_pipe_config_compare(dev,
13326                                         to_intel_crtc_state(crtc->state),
13327                                         pipe_config, true)) {
13328                         crtc_state->mode_changed = false;
13329                         to_intel_crtc_state(crtc_state)->update_pipe = true;
13330                 }
13331
13332                 if (needs_modeset(crtc_state)) {
13333                         any_ms = true;
13334
13335                         ret = drm_atomic_add_affected_planes(state, crtc);
13336                         if (ret)
13337                                 return ret;
13338                 }
13339
13340                 intel_dump_pipe_config(to_intel_crtc(crtc), pipe_config,
13341                                        needs_modeset(crtc_state) ?
13342                                        "[modeset]" : "[fastset]");
13343         }
13344
13345         if (any_ms) {
13346                 ret = intel_modeset_checks(state);
13347
13348                 if (ret)
13349                         return ret;
13350         } else
13351                 intel_state->cdclk = dev_priv->cdclk_freq;
13352
13353         ret = drm_atomic_helper_check_planes(dev, state);
13354         if (ret)
13355                 return ret;
13356
13357         intel_fbc_choose_crtc(dev_priv, state);
13358         calc_watermark_data(state);
13359
13360         return 0;
13361 }
13362
13363 static int intel_atomic_prepare_commit(struct drm_device *dev,
13364                                        struct drm_atomic_state *state,
13365                                        bool async)
13366 {
13367         struct drm_i915_private *dev_priv = dev->dev_private;
13368         struct drm_plane_state *plane_state;
13369         struct drm_crtc_state *crtc_state;
13370         struct drm_plane *plane;
13371         struct drm_crtc *crtc;
13372         int i, ret;
13373
13374         if (async) {
13375                 DRM_DEBUG_KMS("i915 does not yet support async commit\n");
13376                 return -EINVAL;
13377         }
13378
13379         for_each_crtc_in_state(state, crtc, crtc_state, i) {
13380                 ret = intel_crtc_wait_for_pending_flips(crtc);
13381                 if (ret)
13382                         return ret;
13383
13384                 if (atomic_read(&to_intel_crtc(crtc)->unpin_work_count) >= 2)
13385                         flush_workqueue(dev_priv->wq);
13386         }
13387
13388         ret = mutex_lock_interruptible(&dev->struct_mutex);
13389         if (ret)
13390                 return ret;
13391
13392         ret = drm_atomic_helper_prepare_planes(dev, state);
13393         if (!ret && !async && !i915_reset_in_progress(&dev_priv->gpu_error)) {
13394                 u32 reset_counter;
13395
13396                 reset_counter = atomic_read(&dev_priv->gpu_error.reset_counter);
13397                 mutex_unlock(&dev->struct_mutex);
13398
13399                 for_each_plane_in_state(state, plane, plane_state, i) {
13400                         struct intel_plane_state *intel_plane_state =
13401                                 to_intel_plane_state(plane_state);
13402
13403                         if (!intel_plane_state->wait_req)
13404                                 continue;
13405
13406                         ret = __i915_wait_request(intel_plane_state->wait_req,
13407                                                   reset_counter, true,
13408                                                   NULL, NULL);
13409
13410                         /* Swallow -EIO errors to allow updates during hw lockup. */
13411                         if (ret == -EIO)
13412                                 ret = 0;
13413
13414                         if (ret)
13415                                 break;
13416                 }
13417
13418                 if (!ret)
13419                         return 0;
13420
13421                 mutex_lock(&dev->struct_mutex);
13422                 drm_atomic_helper_cleanup_planes(dev, state);
13423         }
13424
13425         mutex_unlock(&dev->struct_mutex);
13426         return ret;
13427 }
13428
13429 static void intel_atomic_wait_for_vblanks(struct drm_device *dev,
13430                                           struct drm_i915_private *dev_priv,
13431                                           unsigned crtc_mask)
13432 {
13433         unsigned last_vblank_count[I915_MAX_PIPES];
13434         enum pipe pipe;
13435         int ret;
13436
13437         if (!crtc_mask)
13438                 return;
13439
13440         for_each_pipe(dev_priv, pipe) {
13441                 struct drm_crtc *crtc = dev_priv->pipe_to_crtc_mapping[pipe];
13442
13443                 if (!((1 << pipe) & crtc_mask))
13444                         continue;
13445
13446                 ret = drm_crtc_vblank_get(crtc);
13447                 if (WARN_ON(ret != 0)) {
13448                         crtc_mask &= ~(1 << pipe);
13449                         continue;
13450                 }
13451
13452                 last_vblank_count[pipe] = drm_crtc_vblank_count(crtc);
13453         }
13454
13455         for_each_pipe(dev_priv, pipe) {
13456                 struct drm_crtc *crtc = dev_priv->pipe_to_crtc_mapping[pipe];
13457                 long lret;
13458
13459                 if (!((1 << pipe) & crtc_mask))
13460                         continue;
13461
13462                 lret = wait_event_timeout(dev->vblank[pipe].queue,
13463                                 last_vblank_count[pipe] !=
13464                                         drm_crtc_vblank_count(crtc),
13465                                 msecs_to_jiffies(50));
13466
13467                 WARN_ON(!lret);
13468
13469                 drm_crtc_vblank_put(crtc);
13470         }
13471 }
13472
13473 static bool needs_vblank_wait(struct intel_crtc_state *crtc_state)
13474 {
13475         /* fb updated, need to unpin old fb */
13476         if (crtc_state->fb_changed)
13477                 return true;
13478
13479         /* wm changes, need vblank before final wm's */
13480         if (crtc_state->update_wm_post)
13481                 return true;
13482
13483         /*
13484          * cxsr is re-enabled after vblank.
13485          * This is already handled by crtc_state->update_wm_post,
13486          * but added for clarity.
13487          */
13488         if (crtc_state->disable_cxsr)
13489                 return true;
13490
13491         return false;
13492 }
13493
13494 /**
13495  * intel_atomic_commit - commit validated state object
13496  * @dev: DRM device
13497  * @state: the top-level driver state object
13498  * @async: asynchronous commit
13499  *
13500  * This function commits a top-level state object that has been validated
13501  * with drm_atomic_helper_check().
13502  *
13503  * FIXME:  Atomic modeset support for i915 is not yet complete.  At the moment
13504  * we can only handle plane-related operations and do not yet support
13505  * asynchronous commit.
13506  *
13507  * RETURNS
13508  * Zero for success or -errno.
13509  */
13510 static int intel_atomic_commit(struct drm_device *dev,
13511                                struct drm_atomic_state *state,
13512                                bool async)
13513 {
13514         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
13515         struct drm_i915_private *dev_priv = dev->dev_private;
13516         struct drm_crtc_state *old_crtc_state;
13517         struct drm_crtc *crtc;
13518         struct intel_crtc_state *intel_cstate;
13519         int ret = 0, i;
13520         bool hw_check = intel_state->modeset;
13521         unsigned long put_domains[I915_MAX_PIPES] = {};
13522         unsigned crtc_vblank_mask = 0;
13523
13524         ret = intel_atomic_prepare_commit(dev, state, async);
13525         if (ret) {
13526                 DRM_DEBUG_ATOMIC("Preparing state failed with %i\n", ret);
13527                 return ret;
13528         }
13529
13530         drm_atomic_helper_swap_state(dev, state);
13531         dev_priv->wm.config = intel_state->wm_config;
13532         intel_shared_dpll_commit(state);
13533
13534         if (intel_state->modeset) {
13535                 memcpy(dev_priv->min_pixclk, intel_state->min_pixclk,
13536                        sizeof(intel_state->min_pixclk));
13537                 dev_priv->active_crtcs = intel_state->active_crtcs;
13538                 dev_priv->atomic_cdclk_freq = intel_state->cdclk;
13539
13540                 intel_display_power_get(dev_priv, POWER_DOMAIN_MODESET);
13541         }
13542
13543         for_each_crtc_in_state(state, crtc, old_crtc_state, i) {
13544                 struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
13545
13546                 if (needs_modeset(crtc->state) ||
13547                     to_intel_crtc_state(crtc->state)->update_pipe) {
13548                         hw_check = true;
13549
13550                         put_domains[to_intel_crtc(crtc)->pipe] =
13551                                 modeset_get_crtc_power_domains(crtc,
13552                                         to_intel_crtc_state(crtc->state));
13553                 }
13554
13555                 if (!needs_modeset(crtc->state))
13556                         continue;
13557
13558                 intel_pre_plane_update(to_intel_crtc_state(old_crtc_state));
13559
13560                 if (old_crtc_state->active) {
13561                         intel_crtc_disable_planes(crtc, old_crtc_state->plane_mask);
13562                         dev_priv->display.crtc_disable(crtc);
13563                         intel_crtc->active = false;
13564                         intel_fbc_disable(intel_crtc);
13565                         intel_disable_shared_dpll(intel_crtc);
13566
13567                         /*
13568                          * Underruns don't always raise
13569                          * interrupts, so check manually.
13570                          */
13571                         intel_check_cpu_fifo_underruns(dev_priv);
13572                         intel_check_pch_fifo_underruns(dev_priv);
13573
13574                         if (!crtc->state->active)
13575                                 intel_update_watermarks(crtc);
13576                 }
13577         }
13578
13579         /* Only after disabling all output pipelines that will be changed can we
13580          * update the the output configuration. */
13581         intel_modeset_update_crtc_state(state);
13582
13583         if (intel_state->modeset) {
13584                 drm_atomic_helper_update_legacy_modeset_state(state->dev, state);
13585
13586                 if (dev_priv->display.modeset_commit_cdclk &&
13587                     intel_state->dev_cdclk != dev_priv->cdclk_freq)
13588                         dev_priv->display.modeset_commit_cdclk(state);
13589         }
13590
13591         /* Now enable the clocks, plane, pipe, and connectors that we set up. */
13592         for_each_crtc_in_state(state, crtc, old_crtc_state, i) {
13593                 struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
13594                 bool modeset = needs_modeset(crtc->state);
13595                 struct intel_crtc_state *pipe_config =
13596                         to_intel_crtc_state(crtc->state);
13597                 bool update_pipe = !modeset && pipe_config->update_pipe;
13598
13599                 if (modeset && crtc->state->active) {
13600                         update_scanline_offset(to_intel_crtc(crtc));
13601                         dev_priv->display.crtc_enable(crtc);
13602                 }
13603
13604                 if (!modeset)
13605                         intel_pre_plane_update(to_intel_crtc_state(old_crtc_state));
13606
13607                 if (crtc->state->active &&
13608                     drm_atomic_get_existing_plane_state(state, crtc->primary))
13609                         intel_fbc_enable(intel_crtc);
13610
13611                 if (crtc->state->active &&
13612                     (crtc->state->planes_changed || update_pipe))
13613                         drm_atomic_helper_commit_planes_on_crtc(old_crtc_state);
13614
13615                 if (pipe_config->base.active && needs_vblank_wait(pipe_config))
13616                         crtc_vblank_mask |= 1 << i;
13617         }
13618
13619         /* FIXME: add subpixel order */
13620
13621         if (!state->legacy_cursor_update)
13622                 intel_atomic_wait_for_vblanks(dev, dev_priv, crtc_vblank_mask);
13623
13624         for_each_crtc_in_state(state, crtc, old_crtc_state, i) {
13625                 intel_post_plane_update(to_intel_crtc_state(old_crtc_state));
13626
13627                 if (put_domains[i])
13628                         modeset_put_power_domains(dev_priv, put_domains[i]);
13629         }
13630
13631         if (intel_state->modeset)
13632                 intel_display_power_put(dev_priv, POWER_DOMAIN_MODESET);
13633
13634         /*
13635          * Now that the vblank has passed, we can go ahead and program the
13636          * optimal watermarks on platforms that need two-step watermark
13637          * programming.
13638          *
13639          * TODO: Move this (and other cleanup) to an async worker eventually.
13640          */
13641         for_each_crtc_in_state(state, crtc, old_crtc_state, i) {
13642                 intel_cstate = to_intel_crtc_state(crtc->state);
13643
13644                 if (dev_priv->display.optimize_watermarks)
13645                         dev_priv->display.optimize_watermarks(intel_cstate);
13646         }
13647
13648         mutex_lock(&dev->struct_mutex);
13649         drm_atomic_helper_cleanup_planes(dev, state);
13650         mutex_unlock(&dev->struct_mutex);
13651
13652         if (hw_check)
13653                 intel_modeset_check_state(dev, state);
13654
13655         drm_atomic_state_free(state);
13656
13657         /* As one of the primary mmio accessors, KMS has a high likelihood
13658          * of triggering bugs in unclaimed access. After we finish
13659          * modesetting, see if an error has been flagged, and if so
13660          * enable debugging for the next modeset - and hope we catch
13661          * the culprit.
13662          *
13663          * XXX note that we assume display power is on at this point.
13664          * This might hold true now but we need to add pm helper to check
13665          * unclaimed only when the hardware is on, as atomic commits
13666          * can happen also when the device is completely off.
13667          */
13668         intel_uncore_arm_unclaimed_mmio_detection(dev_priv);
13669
13670         return 0;
13671 }
13672
13673 void intel_crtc_restore_mode(struct drm_crtc *crtc)
13674 {
13675         struct drm_device *dev = crtc->dev;
13676         struct drm_atomic_state *state;
13677         struct drm_crtc_state *crtc_state;
13678         int ret;
13679
13680         state = drm_atomic_state_alloc(dev);
13681         if (!state) {
13682                 DRM_DEBUG_KMS("[CRTC:%d] crtc restore failed, out of memory",
13683                               crtc->base.id);
13684                 return;
13685         }
13686
13687         state->acquire_ctx = drm_modeset_legacy_acquire_ctx(crtc);
13688
13689 retry:
13690         crtc_state = drm_atomic_get_crtc_state(state, crtc);
13691         ret = PTR_ERR_OR_ZERO(crtc_state);
13692         if (!ret) {
13693                 if (!crtc_state->active)
13694                         goto out;
13695
13696                 crtc_state->mode_changed = true;
13697                 ret = drm_atomic_commit(state);
13698         }
13699
13700         if (ret == -EDEADLK) {
13701                 drm_atomic_state_clear(state);
13702                 drm_modeset_backoff(state->acquire_ctx);
13703                 goto retry;
13704         }
13705
13706         if (ret)
13707 out:
13708                 drm_atomic_state_free(state);
13709 }
13710
13711 #undef for_each_intel_crtc_masked
13712
13713 static const struct drm_crtc_funcs intel_crtc_funcs = {
13714         .gamma_set = intel_crtc_gamma_set,
13715         .set_config = drm_atomic_helper_set_config,
13716         .destroy = intel_crtc_destroy,
13717         .page_flip = intel_crtc_page_flip,
13718         .atomic_duplicate_state = intel_crtc_duplicate_state,
13719         .atomic_destroy_state = intel_crtc_destroy_state,
13720 };
13721
13722 /**
13723  * intel_prepare_plane_fb - Prepare fb for usage on plane
13724  * @plane: drm plane to prepare for
13725  * @fb: framebuffer to prepare for presentation
13726  *
13727  * Prepares a framebuffer for usage on a display plane.  Generally this
13728  * involves pinning the underlying object and updating the frontbuffer tracking
13729  * bits.  Some older platforms need special physical address handling for
13730  * cursor planes.
13731  *
13732  * Must be called with struct_mutex held.
13733  *
13734  * Returns 0 on success, negative error code on failure.
13735  */
13736 int
13737 intel_prepare_plane_fb(struct drm_plane *plane,
13738                        const struct drm_plane_state *new_state)
13739 {
13740         struct drm_device *dev = plane->dev;
13741         struct drm_framebuffer *fb = new_state->fb;
13742         struct intel_plane *intel_plane = to_intel_plane(plane);
13743         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
13744         struct drm_i915_gem_object *old_obj = intel_fb_obj(plane->state->fb);
13745         int ret = 0;
13746
13747         if (!obj && !old_obj)
13748                 return 0;
13749
13750         if (old_obj) {
13751                 struct drm_crtc_state *crtc_state =
13752                         drm_atomic_get_existing_crtc_state(new_state->state, plane->state->crtc);
13753
13754                 /* Big Hammer, we also need to ensure that any pending
13755                  * MI_WAIT_FOR_EVENT inside a user batch buffer on the
13756                  * current scanout is retired before unpinning the old
13757                  * framebuffer. Note that we rely on userspace rendering
13758                  * into the buffer attached to the pipe they are waiting
13759                  * on. If not, userspace generates a GPU hang with IPEHR
13760                  * point to the MI_WAIT_FOR_EVENT.
13761                  *
13762                  * This should only fail upon a hung GPU, in which case we
13763                  * can safely continue.
13764                  */
13765                 if (needs_modeset(crtc_state))
13766                         ret = i915_gem_object_wait_rendering(old_obj, true);
13767
13768                 /* Swallow -EIO errors to allow updates during hw lockup. */
13769                 if (ret && ret != -EIO)
13770                         return ret;
13771         }
13772
13773         /* For framebuffer backed by dmabuf, wait for fence */
13774         if (obj && obj->base.dma_buf) {
13775                 long lret;
13776
13777                 lret = reservation_object_wait_timeout_rcu(obj->base.dma_buf->resv,
13778                                                            false, true,
13779                                                            MAX_SCHEDULE_TIMEOUT);
13780                 if (lret == -ERESTARTSYS)
13781                         return lret;
13782
13783                 WARN(lret < 0, "waiting returns %li\n", lret);
13784         }
13785
13786         if (!obj) {
13787                 ret = 0;
13788         } else if (plane->type == DRM_PLANE_TYPE_CURSOR &&
13789             INTEL_INFO(dev)->cursor_needs_physical) {
13790                 int align = IS_I830(dev) ? 16 * 1024 : 256;
13791                 ret = i915_gem_object_attach_phys(obj, align);
13792                 if (ret)
13793                         DRM_DEBUG_KMS("failed to attach phys object\n");
13794         } else {
13795                 ret = intel_pin_and_fence_fb_obj(fb, new_state->rotation);
13796         }
13797
13798         if (ret == 0) {
13799                 if (obj) {
13800                         struct intel_plane_state *plane_state =
13801                                 to_intel_plane_state(new_state);
13802
13803                         i915_gem_request_assign(&plane_state->wait_req,
13804                                                 obj->last_write_req);
13805                 }
13806
13807                 i915_gem_track_fb(old_obj, obj, intel_plane->frontbuffer_bit);
13808         }
13809
13810         return ret;
13811 }
13812
13813 /**
13814  * intel_cleanup_plane_fb - Cleans up an fb after plane use
13815  * @plane: drm plane to clean up for
13816  * @fb: old framebuffer that was on plane
13817  *
13818  * Cleans up a framebuffer that has just been removed from a plane.
13819  *
13820  * Must be called with struct_mutex held.
13821  */
13822 void
13823 intel_cleanup_plane_fb(struct drm_plane *plane,
13824                        const struct drm_plane_state *old_state)
13825 {
13826         struct drm_device *dev = plane->dev;
13827         struct intel_plane *intel_plane = to_intel_plane(plane);
13828         struct intel_plane_state *old_intel_state;
13829         struct drm_i915_gem_object *old_obj = intel_fb_obj(old_state->fb);
13830         struct drm_i915_gem_object *obj = intel_fb_obj(plane->state->fb);
13831
13832         old_intel_state = to_intel_plane_state(old_state);
13833
13834         if (!obj && !old_obj)
13835                 return;
13836
13837         if (old_obj && (plane->type != DRM_PLANE_TYPE_CURSOR ||
13838             !INTEL_INFO(dev)->cursor_needs_physical))
13839                 intel_unpin_fb_obj(old_state->fb, old_state->rotation);
13840
13841         /* prepare_fb aborted? */
13842         if ((old_obj && (old_obj->frontbuffer_bits & intel_plane->frontbuffer_bit)) ||
13843             (obj && !(obj->frontbuffer_bits & intel_plane->frontbuffer_bit)))
13844                 i915_gem_track_fb(old_obj, obj, intel_plane->frontbuffer_bit);
13845
13846         i915_gem_request_assign(&old_intel_state->wait_req, NULL);
13847 }
13848
13849 int
13850 skl_max_scale(struct intel_crtc *intel_crtc, struct intel_crtc_state *crtc_state)
13851 {
13852         int max_scale;
13853         struct drm_device *dev;
13854         struct drm_i915_private *dev_priv;
13855         int crtc_clock, cdclk;
13856
13857         if (!intel_crtc || !crtc_state->base.enable)
13858                 return DRM_PLANE_HELPER_NO_SCALING;
13859
13860         dev = intel_crtc->base.dev;
13861         dev_priv = dev->dev_private;
13862         crtc_clock = crtc_state->base.adjusted_mode.crtc_clock;
13863         cdclk = to_intel_atomic_state(crtc_state->base.state)->cdclk;
13864
13865         if (WARN_ON_ONCE(!crtc_clock || cdclk < crtc_clock))
13866                 return DRM_PLANE_HELPER_NO_SCALING;
13867
13868         /*
13869          * skl max scale is lower of:
13870          *    close to 3 but not 3, -1 is for that purpose
13871          *            or
13872          *    cdclk/crtc_clock
13873          */
13874         max_scale = min((1 << 16) * 3 - 1, (1 << 8) * ((cdclk << 8) / crtc_clock));
13875
13876         return max_scale;
13877 }
13878
13879 static int
13880 intel_check_primary_plane(struct drm_plane *plane,
13881                           struct intel_crtc_state *crtc_state,
13882                           struct intel_plane_state *state)
13883 {
13884         struct drm_crtc *crtc = state->base.crtc;
13885         struct drm_framebuffer *fb = state->base.fb;
13886         int min_scale = DRM_PLANE_HELPER_NO_SCALING;
13887         int max_scale = DRM_PLANE_HELPER_NO_SCALING;
13888         bool can_position = false;
13889
13890         if (INTEL_INFO(plane->dev)->gen >= 9) {
13891                 /* use scaler when colorkey is not required */
13892                 if (state->ckey.flags == I915_SET_COLORKEY_NONE) {
13893                         min_scale = 1;
13894                         max_scale = skl_max_scale(to_intel_crtc(crtc), crtc_state);
13895                 }
13896                 can_position = true;
13897         }
13898
13899         return drm_plane_helper_check_update(plane, crtc, fb, &state->src,
13900                                              &state->dst, &state->clip,
13901                                              min_scale, max_scale,
13902                                              can_position, true,
13903                                              &state->visible);
13904 }
13905
13906 static void intel_begin_crtc_commit(struct drm_crtc *crtc,
13907                                     struct drm_crtc_state *old_crtc_state)
13908 {
13909         struct drm_device *dev = crtc->dev;
13910         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
13911         struct intel_crtc_state *old_intel_state =
13912                 to_intel_crtc_state(old_crtc_state);
13913         bool modeset = needs_modeset(crtc->state);
13914
13915         /* Perform vblank evasion around commit operation */
13916         intel_pipe_update_start(intel_crtc);
13917
13918         if (modeset)
13919                 return;
13920
13921         if (to_intel_crtc_state(crtc->state)->update_pipe)
13922                 intel_update_pipe_config(intel_crtc, old_intel_state);
13923         else if (INTEL_INFO(dev)->gen >= 9)
13924                 skl_detach_scalers(intel_crtc);
13925 }
13926
13927 static void intel_finish_crtc_commit(struct drm_crtc *crtc,
13928                                      struct drm_crtc_state *old_crtc_state)
13929 {
13930         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
13931
13932         intel_pipe_update_end(intel_crtc);
13933 }
13934
13935 /**
13936  * intel_plane_destroy - destroy a plane
13937  * @plane: plane to destroy
13938  *
13939  * Common destruction function for all types of planes (primary, cursor,
13940  * sprite).
13941  */
13942 void intel_plane_destroy(struct drm_plane *plane)
13943 {
13944         struct intel_plane *intel_plane = to_intel_plane(plane);
13945         drm_plane_cleanup(plane);
13946         kfree(intel_plane);
13947 }
13948
13949 const struct drm_plane_funcs intel_plane_funcs = {
13950         .update_plane = drm_atomic_helper_update_plane,
13951         .disable_plane = drm_atomic_helper_disable_plane,
13952         .destroy = intel_plane_destroy,
13953         .set_property = drm_atomic_helper_plane_set_property,
13954         .atomic_get_property = intel_plane_atomic_get_property,
13955         .atomic_set_property = intel_plane_atomic_set_property,
13956         .atomic_duplicate_state = intel_plane_duplicate_state,
13957         .atomic_destroy_state = intel_plane_destroy_state,
13958
13959 };
13960
13961 static struct drm_plane *intel_primary_plane_create(struct drm_device *dev,
13962                                                     int pipe)
13963 {
13964         struct intel_plane *primary;
13965         struct intel_plane_state *state;
13966         const uint32_t *intel_primary_formats;
13967         unsigned int num_formats;
13968
13969         primary = kzalloc(sizeof(*primary), GFP_KERNEL);
13970         if (primary == NULL)
13971                 return NULL;
13972
13973         state = intel_create_plane_state(&primary->base);
13974         if (!state) {
13975                 kfree(primary);
13976                 return NULL;
13977         }
13978         primary->base.state = &state->base;
13979
13980         primary->can_scale = false;
13981         primary->max_downscale = 1;
13982         if (INTEL_INFO(dev)->gen >= 9) {
13983                 primary->can_scale = true;
13984                 state->scaler_id = -1;
13985         }
13986         primary->pipe = pipe;
13987         primary->plane = pipe;
13988         primary->frontbuffer_bit = INTEL_FRONTBUFFER_PRIMARY(pipe);
13989         primary->check_plane = intel_check_primary_plane;
13990         if (HAS_FBC(dev) && INTEL_INFO(dev)->gen < 4)
13991                 primary->plane = !pipe;
13992
13993         if (INTEL_INFO(dev)->gen >= 9) {
13994                 intel_primary_formats = skl_primary_formats;
13995                 num_formats = ARRAY_SIZE(skl_primary_formats);
13996
13997                 primary->update_plane = skylake_update_primary_plane;
13998                 primary->disable_plane = skylake_disable_primary_plane;
13999         } else if (HAS_PCH_SPLIT(dev)) {
14000                 intel_primary_formats = i965_primary_formats;
14001                 num_formats = ARRAY_SIZE(i965_primary_formats);
14002
14003                 primary->update_plane = ironlake_update_primary_plane;
14004                 primary->disable_plane = i9xx_disable_primary_plane;
14005         } else if (INTEL_INFO(dev)->gen >= 4) {
14006                 intel_primary_formats = i965_primary_formats;
14007                 num_formats = ARRAY_SIZE(i965_primary_formats);
14008
14009                 primary->update_plane = i9xx_update_primary_plane;
14010                 primary->disable_plane = i9xx_disable_primary_plane;
14011         } else {
14012                 intel_primary_formats = i8xx_primary_formats;
14013                 num_formats = ARRAY_SIZE(i8xx_primary_formats);
14014
14015                 primary->update_plane = i9xx_update_primary_plane;
14016                 primary->disable_plane = i9xx_disable_primary_plane;
14017         }
14018
14019         drm_universal_plane_init(dev, &primary->base, 0,
14020                                  &intel_plane_funcs,
14021                                  intel_primary_formats, num_formats,
14022                                  DRM_PLANE_TYPE_PRIMARY, NULL);
14023
14024         if (INTEL_INFO(dev)->gen >= 4)
14025                 intel_create_rotation_property(dev, primary);
14026
14027         drm_plane_helper_add(&primary->base, &intel_plane_helper_funcs);
14028
14029         return &primary->base;
14030 }
14031
14032 void intel_create_rotation_property(struct drm_device *dev, struct intel_plane *plane)
14033 {
14034         if (!dev->mode_config.rotation_property) {
14035                 unsigned long flags = BIT(DRM_ROTATE_0) |
14036                         BIT(DRM_ROTATE_180);
14037
14038                 if (INTEL_INFO(dev)->gen >= 9)
14039                         flags |= BIT(DRM_ROTATE_90) | BIT(DRM_ROTATE_270);
14040
14041                 dev->mode_config.rotation_property =
14042                         drm_mode_create_rotation_property(dev, flags);
14043         }
14044         if (dev->mode_config.rotation_property)
14045                 drm_object_attach_property(&plane->base.base,
14046                                 dev->mode_config.rotation_property,
14047                                 plane->base.state->rotation);
14048 }
14049
14050 static int
14051 intel_check_cursor_plane(struct drm_plane *plane,
14052                          struct intel_crtc_state *crtc_state,
14053                          struct intel_plane_state *state)
14054 {
14055         struct drm_crtc *crtc = crtc_state->base.crtc;
14056         struct drm_framebuffer *fb = state->base.fb;
14057         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
14058         enum pipe pipe = to_intel_plane(plane)->pipe;
14059         unsigned stride;
14060         int ret;
14061
14062         ret = drm_plane_helper_check_update(plane, crtc, fb, &state->src,
14063                                             &state->dst, &state->clip,
14064                                             DRM_PLANE_HELPER_NO_SCALING,
14065                                             DRM_PLANE_HELPER_NO_SCALING,
14066                                             true, true, &state->visible);
14067         if (ret)
14068                 return ret;
14069
14070         /* if we want to turn off the cursor ignore width and height */
14071         if (!obj)
14072                 return 0;
14073
14074         /* Check for which cursor types we support */
14075         if (!cursor_size_ok(plane->dev, state->base.crtc_w, state->base.crtc_h)) {
14076                 DRM_DEBUG("Cursor dimension %dx%d not supported\n",
14077                           state->base.crtc_w, state->base.crtc_h);
14078                 return -EINVAL;
14079         }
14080
14081         stride = roundup_pow_of_two(state->base.crtc_w) * 4;
14082         if (obj->base.size < stride * state->base.crtc_h) {
14083                 DRM_DEBUG_KMS("buffer is too small\n");
14084                 return -ENOMEM;
14085         }
14086
14087         if (fb->modifier[0] != DRM_FORMAT_MOD_NONE) {
14088                 DRM_DEBUG_KMS("cursor cannot be tiled\n");
14089                 return -EINVAL;
14090         }
14091
14092         /*
14093          * There's something wrong with the cursor on CHV pipe C.
14094          * If it straddles the left edge of the screen then
14095          * moving it away from the edge or disabling it often
14096          * results in a pipe underrun, and often that can lead to
14097          * dead pipe (constant underrun reported, and it scans
14098          * out just a solid color). To recover from that, the
14099          * display power well must be turned off and on again.
14100          * Refuse the put the cursor into that compromised position.
14101          */
14102         if (IS_CHERRYVIEW(plane->dev) && pipe == PIPE_C &&
14103             state->visible && state->base.crtc_x < 0) {
14104                 DRM_DEBUG_KMS("CHV cursor C not allowed to straddle the left screen edge\n");
14105                 return -EINVAL;
14106         }
14107
14108         return 0;
14109 }
14110
14111 static void
14112 intel_disable_cursor_plane(struct drm_plane *plane,
14113                            struct drm_crtc *crtc)
14114 {
14115         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
14116
14117         intel_crtc->cursor_addr = 0;
14118         intel_crtc_update_cursor(crtc, NULL);
14119 }
14120
14121 static void
14122 intel_update_cursor_plane(struct drm_plane *plane,
14123                           const struct intel_crtc_state *crtc_state,
14124                           const struct intel_plane_state *state)
14125 {
14126         struct drm_crtc *crtc = crtc_state->base.crtc;
14127         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
14128         struct drm_device *dev = plane->dev;
14129         struct drm_i915_gem_object *obj = intel_fb_obj(state->base.fb);
14130         uint32_t addr;
14131
14132         if (!obj)
14133                 addr = 0;
14134         else if (!INTEL_INFO(dev)->cursor_needs_physical)
14135                 addr = i915_gem_obj_ggtt_offset(obj);
14136         else
14137                 addr = obj->phys_handle->busaddr;
14138
14139         intel_crtc->cursor_addr = addr;
14140         intel_crtc_update_cursor(crtc, state);
14141 }
14142
14143 static struct drm_plane *intel_cursor_plane_create(struct drm_device *dev,
14144                                                    int pipe)
14145 {
14146         struct intel_plane *cursor;
14147         struct intel_plane_state *state;
14148
14149         cursor = kzalloc(sizeof(*cursor), GFP_KERNEL);
14150         if (cursor == NULL)
14151                 return NULL;
14152
14153         state = intel_create_plane_state(&cursor->base);
14154         if (!state) {
14155                 kfree(cursor);
14156                 return NULL;
14157         }
14158         cursor->base.state = &state->base;
14159
14160         cursor->can_scale = false;
14161         cursor->max_downscale = 1;
14162         cursor->pipe = pipe;
14163         cursor->plane = pipe;
14164         cursor->frontbuffer_bit = INTEL_FRONTBUFFER_CURSOR(pipe);
14165         cursor->check_plane = intel_check_cursor_plane;
14166         cursor->update_plane = intel_update_cursor_plane;
14167         cursor->disable_plane = intel_disable_cursor_plane;
14168
14169         drm_universal_plane_init(dev, &cursor->base, 0,
14170                                  &intel_plane_funcs,
14171                                  intel_cursor_formats,
14172                                  ARRAY_SIZE(intel_cursor_formats),
14173                                  DRM_PLANE_TYPE_CURSOR, NULL);
14174
14175         if (INTEL_INFO(dev)->gen >= 4) {
14176                 if (!dev->mode_config.rotation_property)
14177                         dev->mode_config.rotation_property =
14178                                 drm_mode_create_rotation_property(dev,
14179                                                         BIT(DRM_ROTATE_0) |
14180                                                         BIT(DRM_ROTATE_180));
14181                 if (dev->mode_config.rotation_property)
14182                         drm_object_attach_property(&cursor->base.base,
14183                                 dev->mode_config.rotation_property,
14184                                 state->base.rotation);
14185         }
14186
14187         if (INTEL_INFO(dev)->gen >=9)
14188                 state->scaler_id = -1;
14189
14190         drm_plane_helper_add(&cursor->base, &intel_plane_helper_funcs);
14191
14192         return &cursor->base;
14193 }
14194
14195 static void skl_init_scalers(struct drm_device *dev, struct intel_crtc *intel_crtc,
14196         struct intel_crtc_state *crtc_state)
14197 {
14198         int i;
14199         struct intel_scaler *intel_scaler;
14200         struct intel_crtc_scaler_state *scaler_state = &crtc_state->scaler_state;
14201
14202         for (i = 0; i < intel_crtc->num_scalers; i++) {
14203                 intel_scaler = &scaler_state->scalers[i];
14204                 intel_scaler->in_use = 0;
14205                 intel_scaler->mode = PS_SCALER_MODE_DYN;
14206         }
14207
14208         scaler_state->scaler_id = -1;
14209 }
14210
14211 static void intel_crtc_init(struct drm_device *dev, int pipe)
14212 {
14213         struct drm_i915_private *dev_priv = dev->dev_private;
14214         struct intel_crtc *intel_crtc;
14215         struct intel_crtc_state *crtc_state = NULL;
14216         struct drm_plane *primary = NULL;
14217         struct drm_plane *cursor = NULL;
14218         int i, ret;
14219
14220         intel_crtc = kzalloc(sizeof(*intel_crtc), GFP_KERNEL);
14221         if (intel_crtc == NULL)
14222                 return;
14223
14224         crtc_state = kzalloc(sizeof(*crtc_state), GFP_KERNEL);
14225         if (!crtc_state)
14226                 goto fail;
14227         intel_crtc->config = crtc_state;
14228         intel_crtc->base.state = &crtc_state->base;
14229         crtc_state->base.crtc = &intel_crtc->base;
14230
14231         /* initialize shared scalers */
14232         if (INTEL_INFO(dev)->gen >= 9) {
14233                 if (pipe == PIPE_C)
14234                         intel_crtc->num_scalers = 1;
14235                 else
14236                         intel_crtc->num_scalers = SKL_NUM_SCALERS;
14237
14238                 skl_init_scalers(dev, intel_crtc, crtc_state);
14239         }
14240
14241         primary = intel_primary_plane_create(dev, pipe);
14242         if (!primary)
14243                 goto fail;
14244
14245         cursor = intel_cursor_plane_create(dev, pipe);
14246         if (!cursor)
14247                 goto fail;
14248
14249         ret = drm_crtc_init_with_planes(dev, &intel_crtc->base, primary,
14250                                         cursor, &intel_crtc_funcs, NULL);
14251         if (ret)
14252                 goto fail;
14253
14254         drm_mode_crtc_set_gamma_size(&intel_crtc->base, 256);
14255         for (i = 0; i < 256; i++) {
14256                 intel_crtc->lut_r[i] = i;
14257                 intel_crtc->lut_g[i] = i;
14258                 intel_crtc->lut_b[i] = i;
14259         }
14260
14261         /*
14262          * On gen2/3 only plane A can do fbc, but the panel fitter and lvds port
14263          * is hooked to pipe B. Hence we want plane A feeding pipe B.
14264          */
14265         intel_crtc->pipe = pipe;
14266         intel_crtc->plane = pipe;
14267         if (HAS_FBC(dev) && INTEL_INFO(dev)->gen < 4) {
14268                 DRM_DEBUG_KMS("swapping pipes & planes for FBC\n");
14269                 intel_crtc->plane = !pipe;
14270         }
14271
14272         intel_crtc->cursor_base = ~0;
14273         intel_crtc->cursor_cntl = ~0;
14274         intel_crtc->cursor_size = ~0;
14275
14276         intel_crtc->wm.cxsr_allowed = true;
14277
14278         BUG_ON(pipe >= ARRAY_SIZE(dev_priv->plane_to_crtc_mapping) ||
14279                dev_priv->plane_to_crtc_mapping[intel_crtc->plane] != NULL);
14280         dev_priv->plane_to_crtc_mapping[intel_crtc->plane] = &intel_crtc->base;
14281         dev_priv->pipe_to_crtc_mapping[intel_crtc->pipe] = &intel_crtc->base;
14282
14283         drm_crtc_helper_add(&intel_crtc->base, &intel_helper_funcs);
14284
14285         WARN_ON(drm_crtc_index(&intel_crtc->base) != intel_crtc->pipe);
14286         return;
14287
14288 fail:
14289         if (primary)
14290                 drm_plane_cleanup(primary);
14291         if (cursor)
14292                 drm_plane_cleanup(cursor);
14293         kfree(crtc_state);
14294         kfree(intel_crtc);
14295 }
14296
14297 enum pipe intel_get_pipe_from_connector(struct intel_connector *connector)
14298 {
14299         struct drm_encoder *encoder = connector->base.encoder;
14300         struct drm_device *dev = connector->base.dev;
14301
14302         WARN_ON(!drm_modeset_is_locked(&dev->mode_config.connection_mutex));
14303
14304         if (!encoder || WARN_ON(!encoder->crtc))
14305                 return INVALID_PIPE;
14306
14307         return to_intel_crtc(encoder->crtc)->pipe;
14308 }
14309
14310 int intel_get_pipe_from_crtc_id(struct drm_device *dev, void *data,
14311                                 struct drm_file *file)
14312 {
14313         struct drm_i915_get_pipe_from_crtc_id *pipe_from_crtc_id = data;
14314         struct drm_crtc *drmmode_crtc;
14315         struct intel_crtc *crtc;
14316
14317         drmmode_crtc = drm_crtc_find(dev, pipe_from_crtc_id->crtc_id);
14318
14319         if (!drmmode_crtc) {
14320                 DRM_ERROR("no such CRTC id\n");
14321                 return -ENOENT;
14322         }
14323
14324         crtc = to_intel_crtc(drmmode_crtc);
14325         pipe_from_crtc_id->pipe = crtc->pipe;
14326
14327         return 0;
14328 }
14329
14330 static int intel_encoder_clones(struct intel_encoder *encoder)
14331 {
14332         struct drm_device *dev = encoder->base.dev;
14333         struct intel_encoder *source_encoder;
14334         int index_mask = 0;
14335         int entry = 0;
14336
14337         for_each_intel_encoder(dev, source_encoder) {
14338                 if (encoders_cloneable(encoder, source_encoder))
14339                         index_mask |= (1 << entry);
14340
14341                 entry++;
14342         }
14343
14344         return index_mask;
14345 }
14346
14347 static bool has_edp_a(struct drm_device *dev)
14348 {
14349         struct drm_i915_private *dev_priv = dev->dev_private;
14350
14351         if (!IS_MOBILE(dev))
14352                 return false;
14353
14354         if ((I915_READ(DP_A) & DP_DETECTED) == 0)
14355                 return false;
14356
14357         if (IS_GEN5(dev) && (I915_READ(FUSE_STRAP) & ILK_eDP_A_DISABLE))
14358                 return false;
14359
14360         return true;
14361 }
14362
14363 static bool intel_crt_present(struct drm_device *dev)
14364 {
14365         struct drm_i915_private *dev_priv = dev->dev_private;
14366
14367         if (INTEL_INFO(dev)->gen >= 9)
14368                 return false;
14369
14370         if (IS_HSW_ULT(dev) || IS_BDW_ULT(dev))
14371                 return false;
14372
14373         if (IS_CHERRYVIEW(dev))
14374                 return false;
14375
14376         if (HAS_PCH_LPT_H(dev) && I915_READ(SFUSE_STRAP) & SFUSE_STRAP_CRT_DISABLED)
14377                 return false;
14378
14379         /* DDI E can't be used if DDI A requires 4 lanes */
14380         if (HAS_DDI(dev) && I915_READ(DDI_BUF_CTL(PORT_A)) & DDI_A_4_LANES)
14381                 return false;
14382
14383         if (!dev_priv->vbt.int_crt_support)
14384                 return false;
14385
14386         return true;
14387 }
14388
14389 static void intel_setup_outputs(struct drm_device *dev)
14390 {
14391         struct drm_i915_private *dev_priv = dev->dev_private;
14392         struct intel_encoder *encoder;
14393         bool dpd_is_edp = false;
14394
14395         intel_lvds_init(dev);
14396
14397         if (intel_crt_present(dev))
14398                 intel_crt_init(dev);
14399
14400         if (IS_BROXTON(dev)) {
14401                 /*
14402                  * FIXME: Broxton doesn't support port detection via the
14403                  * DDI_BUF_CTL_A or SFUSE_STRAP registers, find another way to
14404                  * detect the ports.
14405                  */
14406                 intel_ddi_init(dev, PORT_A);
14407                 intel_ddi_init(dev, PORT_B);
14408                 intel_ddi_init(dev, PORT_C);
14409         } else if (HAS_DDI(dev)) {
14410                 int found;
14411
14412                 /*
14413                  * Haswell uses DDI functions to detect digital outputs.
14414                  * On SKL pre-D0 the strap isn't connected, so we assume
14415                  * it's there.
14416                  */
14417                 found = I915_READ(DDI_BUF_CTL(PORT_A)) & DDI_INIT_DISPLAY_DETECTED;
14418                 /* WaIgnoreDDIAStrap: skl */
14419                 if (found || IS_SKYLAKE(dev) || IS_KABYLAKE(dev))
14420                         intel_ddi_init(dev, PORT_A);
14421
14422                 /* DDI B, C and D detection is indicated by the SFUSE_STRAP
14423                  * register */
14424                 found = I915_READ(SFUSE_STRAP);
14425
14426                 if (found & SFUSE_STRAP_DDIB_DETECTED)
14427                         intel_ddi_init(dev, PORT_B);
14428                 if (found & SFUSE_STRAP_DDIC_DETECTED)
14429                         intel_ddi_init(dev, PORT_C);
14430                 if (found & SFUSE_STRAP_DDID_DETECTED)
14431                         intel_ddi_init(dev, PORT_D);
14432                 /*
14433                  * On SKL we don't have a way to detect DDI-E so we rely on VBT.
14434                  */
14435                 if ((IS_SKYLAKE(dev) || IS_KABYLAKE(dev)) &&
14436                     (dev_priv->vbt.ddi_port_info[PORT_E].supports_dp ||
14437                      dev_priv->vbt.ddi_port_info[PORT_E].supports_dvi ||
14438                      dev_priv->vbt.ddi_port_info[PORT_E].supports_hdmi))
14439                         intel_ddi_init(dev, PORT_E);
14440
14441         } else if (HAS_PCH_SPLIT(dev)) {
14442                 int found;
14443                 dpd_is_edp = intel_dp_is_edp(dev, PORT_D);
14444
14445                 if (has_edp_a(dev))
14446                         intel_dp_init(dev, DP_A, PORT_A);
14447
14448                 if (I915_READ(PCH_HDMIB) & SDVO_DETECTED) {
14449                         /* PCH SDVOB multiplex with HDMIB */
14450                         found = intel_sdvo_init(dev, PCH_SDVOB, PORT_B);
14451                         if (!found)
14452                                 intel_hdmi_init(dev, PCH_HDMIB, PORT_B);
14453                         if (!found && (I915_READ(PCH_DP_B) & DP_DETECTED))
14454                                 intel_dp_init(dev, PCH_DP_B, PORT_B);
14455                 }
14456
14457                 if (I915_READ(PCH_HDMIC) & SDVO_DETECTED)
14458                         intel_hdmi_init(dev, PCH_HDMIC, PORT_C);
14459
14460                 if (!dpd_is_edp && I915_READ(PCH_HDMID) & SDVO_DETECTED)
14461                         intel_hdmi_init(dev, PCH_HDMID, PORT_D);
14462
14463                 if (I915_READ(PCH_DP_C) & DP_DETECTED)
14464                         intel_dp_init(dev, PCH_DP_C, PORT_C);
14465
14466                 if (I915_READ(PCH_DP_D) & DP_DETECTED)
14467                         intel_dp_init(dev, PCH_DP_D, PORT_D);
14468         } else if (IS_VALLEYVIEW(dev) || IS_CHERRYVIEW(dev)) {
14469                 /*
14470                  * The DP_DETECTED bit is the latched state of the DDC
14471                  * SDA pin at boot. However since eDP doesn't require DDC
14472                  * (no way to plug in a DP->HDMI dongle) the DDC pins for
14473                  * eDP ports may have been muxed to an alternate function.
14474                  * Thus we can't rely on the DP_DETECTED bit alone to detect
14475                  * eDP ports. Consult the VBT as well as DP_DETECTED to
14476                  * detect eDP ports.
14477                  */
14478                 if (I915_READ(VLV_HDMIB) & SDVO_DETECTED &&
14479                     !intel_dp_is_edp(dev, PORT_B))
14480                         intel_hdmi_init(dev, VLV_HDMIB, PORT_B);
14481                 if (I915_READ(VLV_DP_B) & DP_DETECTED ||
14482                     intel_dp_is_edp(dev, PORT_B))
14483                         intel_dp_init(dev, VLV_DP_B, PORT_B);
14484
14485                 if (I915_READ(VLV_HDMIC) & SDVO_DETECTED &&
14486                     !intel_dp_is_edp(dev, PORT_C))
14487                         intel_hdmi_init(dev, VLV_HDMIC, PORT_C);
14488                 if (I915_READ(VLV_DP_C) & DP_DETECTED ||
14489                     intel_dp_is_edp(dev, PORT_C))
14490                         intel_dp_init(dev, VLV_DP_C, PORT_C);
14491
14492                 if (IS_CHERRYVIEW(dev)) {
14493                         /* eDP not supported on port D, so don't check VBT */
14494                         if (I915_READ(CHV_HDMID) & SDVO_DETECTED)
14495                                 intel_hdmi_init(dev, CHV_HDMID, PORT_D);
14496                         if (I915_READ(CHV_DP_D) & DP_DETECTED)
14497                                 intel_dp_init(dev, CHV_DP_D, PORT_D);
14498                 }
14499
14500                 intel_dsi_init(dev);
14501         } else if (!IS_GEN2(dev) && !IS_PINEVIEW(dev)) {
14502                 bool found = false;
14503
14504                 if (I915_READ(GEN3_SDVOB) & SDVO_DETECTED) {
14505                         DRM_DEBUG_KMS("probing SDVOB\n");
14506                         found = intel_sdvo_init(dev, GEN3_SDVOB, PORT_B);
14507                         if (!found && IS_G4X(dev)) {
14508                                 DRM_DEBUG_KMS("probing HDMI on SDVOB\n");
14509                                 intel_hdmi_init(dev, GEN4_HDMIB, PORT_B);
14510                         }
14511
14512                         if (!found && IS_G4X(dev))
14513                                 intel_dp_init(dev, DP_B, PORT_B);
14514                 }
14515
14516                 /* Before G4X SDVOC doesn't have its own detect register */
14517
14518                 if (I915_READ(GEN3_SDVOB) & SDVO_DETECTED) {
14519                         DRM_DEBUG_KMS("probing SDVOC\n");
14520                         found = intel_sdvo_init(dev, GEN3_SDVOC, PORT_C);
14521                 }
14522
14523                 if (!found && (I915_READ(GEN3_SDVOC) & SDVO_DETECTED)) {
14524
14525                         if (IS_G4X(dev)) {
14526                                 DRM_DEBUG_KMS("probing HDMI on SDVOC\n");
14527                                 intel_hdmi_init(dev, GEN4_HDMIC, PORT_C);
14528                         }
14529                         if (IS_G4X(dev))
14530                                 intel_dp_init(dev, DP_C, PORT_C);
14531                 }
14532
14533                 if (IS_G4X(dev) &&
14534                     (I915_READ(DP_D) & DP_DETECTED))
14535                         intel_dp_init(dev, DP_D, PORT_D);
14536         } else if (IS_GEN2(dev))
14537                 intel_dvo_init(dev);
14538
14539         if (SUPPORTS_TV(dev))
14540                 intel_tv_init(dev);
14541
14542         intel_psr_init(dev);
14543
14544         for_each_intel_encoder(dev, encoder) {
14545                 encoder->base.possible_crtcs = encoder->crtc_mask;
14546                 encoder->base.possible_clones =
14547                         intel_encoder_clones(encoder);
14548         }
14549
14550         intel_init_pch_refclk(dev);
14551
14552         drm_helper_move_panel_connectors_to_head(dev);
14553 }
14554
14555 static void intel_user_framebuffer_destroy(struct drm_framebuffer *fb)
14556 {
14557         struct drm_device *dev = fb->dev;
14558         struct intel_framebuffer *intel_fb = to_intel_framebuffer(fb);
14559
14560         drm_framebuffer_cleanup(fb);
14561         mutex_lock(&dev->struct_mutex);
14562         WARN_ON(!intel_fb->obj->framebuffer_references--);
14563         drm_gem_object_unreference(&intel_fb->obj->base);
14564         mutex_unlock(&dev->struct_mutex);
14565         kfree(intel_fb);
14566 }
14567
14568 static int intel_user_framebuffer_create_handle(struct drm_framebuffer *fb,
14569                                                 struct drm_file *file,
14570                                                 unsigned int *handle)
14571 {
14572         struct intel_framebuffer *intel_fb = to_intel_framebuffer(fb);
14573         struct drm_i915_gem_object *obj = intel_fb->obj;
14574
14575         if (obj->userptr.mm) {
14576                 DRM_DEBUG("attempting to use a userptr for a framebuffer, denied\n");
14577                 return -EINVAL;
14578         }
14579
14580         return drm_gem_handle_create(file, &obj->base, handle);
14581 }
14582
14583 static int intel_user_framebuffer_dirty(struct drm_framebuffer *fb,
14584                                         struct drm_file *file,
14585                                         unsigned flags, unsigned color,
14586                                         struct drm_clip_rect *clips,
14587                                         unsigned num_clips)
14588 {
14589         struct drm_device *dev = fb->dev;
14590         struct intel_framebuffer *intel_fb = to_intel_framebuffer(fb);
14591         struct drm_i915_gem_object *obj = intel_fb->obj;
14592
14593         mutex_lock(&dev->struct_mutex);
14594         intel_fb_obj_flush(obj, false, ORIGIN_DIRTYFB);
14595         mutex_unlock(&dev->struct_mutex);
14596
14597         return 0;
14598 }
14599
14600 static const struct drm_framebuffer_funcs intel_fb_funcs = {
14601         .destroy = intel_user_framebuffer_destroy,
14602         .create_handle = intel_user_framebuffer_create_handle,
14603         .dirty = intel_user_framebuffer_dirty,
14604 };
14605
14606 static
14607 u32 intel_fb_pitch_limit(struct drm_device *dev, uint64_t fb_modifier,
14608                          uint32_t pixel_format)
14609 {
14610         u32 gen = INTEL_INFO(dev)->gen;
14611
14612         if (gen >= 9) {
14613                 int cpp = drm_format_plane_cpp(pixel_format, 0);
14614
14615                 /* "The stride in bytes must not exceed the of the size of 8K
14616                  *  pixels and 32K bytes."
14617                  */
14618                 return min(8192 * cpp, 32768);
14619         } else if (gen >= 5 && !IS_VALLEYVIEW(dev) && !IS_CHERRYVIEW(dev)) {
14620                 return 32*1024;
14621         } else if (gen >= 4) {
14622                 if (fb_modifier == I915_FORMAT_MOD_X_TILED)
14623                         return 16*1024;
14624                 else
14625                         return 32*1024;
14626         } else if (gen >= 3) {
14627                 if (fb_modifier == I915_FORMAT_MOD_X_TILED)
14628                         return 8*1024;
14629                 else
14630                         return 16*1024;
14631         } else {
14632                 /* XXX DSPC is limited to 4k tiled */
14633                 return 8*1024;
14634         }
14635 }
14636
14637 static int intel_framebuffer_init(struct drm_device *dev,
14638                                   struct intel_framebuffer *intel_fb,
14639                                   struct drm_mode_fb_cmd2 *mode_cmd,
14640                                   struct drm_i915_gem_object *obj)
14641 {
14642         struct drm_i915_private *dev_priv = to_i915(dev);
14643         unsigned int aligned_height;
14644         int ret;
14645         u32 pitch_limit, stride_alignment;
14646
14647         WARN_ON(!mutex_is_locked(&dev->struct_mutex));
14648
14649         if (mode_cmd->flags & DRM_MODE_FB_MODIFIERS) {
14650                 /* Enforce that fb modifier and tiling mode match, but only for
14651                  * X-tiled. This is needed for FBC. */
14652                 if (!!(obj->tiling_mode == I915_TILING_X) !=
14653                     !!(mode_cmd->modifier[0] == I915_FORMAT_MOD_X_TILED)) {
14654                         DRM_DEBUG("tiling_mode doesn't match fb modifier\n");
14655                         return -EINVAL;
14656                 }
14657         } else {
14658                 if (obj->tiling_mode == I915_TILING_X)
14659                         mode_cmd->modifier[0] = I915_FORMAT_MOD_X_TILED;
14660                 else if (obj->tiling_mode == I915_TILING_Y) {
14661                         DRM_DEBUG("No Y tiling for legacy addfb\n");
14662                         return -EINVAL;
14663                 }
14664         }
14665
14666         /* Passed in modifier sanity checking. */
14667         switch (mode_cmd->modifier[0]) {
14668         case I915_FORMAT_MOD_Y_TILED:
14669         case I915_FORMAT_MOD_Yf_TILED:
14670                 if (INTEL_INFO(dev)->gen < 9) {
14671                         DRM_DEBUG("Unsupported tiling 0x%llx!\n",
14672                                   mode_cmd->modifier[0]);
14673                         return -EINVAL;
14674                 }
14675         case DRM_FORMAT_MOD_NONE:
14676         case I915_FORMAT_MOD_X_TILED:
14677                 break;
14678         default:
14679                 DRM_DEBUG("Unsupported fb modifier 0x%llx!\n",
14680                           mode_cmd->modifier[0]);
14681                 return -EINVAL;
14682         }
14683
14684         stride_alignment = intel_fb_stride_alignment(dev_priv,
14685                                                      mode_cmd->modifier[0],
14686                                                      mode_cmd->pixel_format);
14687         if (mode_cmd->pitches[0] & (stride_alignment - 1)) {
14688                 DRM_DEBUG("pitch (%d) must be at least %u byte aligned\n",
14689                           mode_cmd->pitches[0], stride_alignment);
14690                 return -EINVAL;
14691         }
14692
14693         pitch_limit = intel_fb_pitch_limit(dev, mode_cmd->modifier[0],
14694                                            mode_cmd->pixel_format);
14695         if (mode_cmd->pitches[0] > pitch_limit) {
14696                 DRM_DEBUG("%s pitch (%u) must be at less than %d\n",
14697                           mode_cmd->modifier[0] != DRM_FORMAT_MOD_NONE ?
14698                           "tiled" : "linear",
14699                           mode_cmd->pitches[0], pitch_limit);
14700                 return -EINVAL;
14701         }
14702
14703         if (mode_cmd->modifier[0] == I915_FORMAT_MOD_X_TILED &&
14704             mode_cmd->pitches[0] != obj->stride) {
14705                 DRM_DEBUG("pitch (%d) must match tiling stride (%d)\n",
14706                           mode_cmd->pitches[0], obj->stride);
14707                 return -EINVAL;
14708         }
14709
14710         /* Reject formats not supported by any plane early. */
14711         switch (mode_cmd->pixel_format) {
14712         case DRM_FORMAT_C8:
14713         case DRM_FORMAT_RGB565:
14714         case DRM_FORMAT_XRGB8888:
14715         case DRM_FORMAT_ARGB8888:
14716                 break;
14717         case DRM_FORMAT_XRGB1555:
14718                 if (INTEL_INFO(dev)->gen > 3) {
14719                         DRM_DEBUG("unsupported pixel format: %s\n",
14720                                   drm_get_format_name(mode_cmd->pixel_format));
14721                         return -EINVAL;
14722                 }
14723                 break;
14724         case DRM_FORMAT_ABGR8888:
14725                 if (!IS_VALLEYVIEW(dev) && !IS_CHERRYVIEW(dev) &&
14726                     INTEL_INFO(dev)->gen < 9) {
14727                         DRM_DEBUG("unsupported pixel format: %s\n",
14728                                   drm_get_format_name(mode_cmd->pixel_format));
14729                         return -EINVAL;
14730                 }
14731                 break;
14732         case DRM_FORMAT_XBGR8888:
14733         case DRM_FORMAT_XRGB2101010:
14734         case DRM_FORMAT_XBGR2101010:
14735                 if (INTEL_INFO(dev)->gen < 4) {
14736                         DRM_DEBUG("unsupported pixel format: %s\n",
14737                                   drm_get_format_name(mode_cmd->pixel_format));
14738                         return -EINVAL;
14739                 }
14740                 break;
14741         case DRM_FORMAT_ABGR2101010:
14742                 if (!IS_VALLEYVIEW(dev) && !IS_CHERRYVIEW(dev)) {
14743                         DRM_DEBUG("unsupported pixel format: %s\n",
14744                                   drm_get_format_name(mode_cmd->pixel_format));
14745                         return -EINVAL;
14746                 }
14747                 break;
14748         case DRM_FORMAT_YUYV:
14749         case DRM_FORMAT_UYVY:
14750         case DRM_FORMAT_YVYU:
14751         case DRM_FORMAT_VYUY:
14752                 if (INTEL_INFO(dev)->gen < 5) {
14753                         DRM_DEBUG("unsupported pixel format: %s\n",
14754                                   drm_get_format_name(mode_cmd->pixel_format));
14755                         return -EINVAL;
14756                 }
14757                 break;
14758         default:
14759                 DRM_DEBUG("unsupported pixel format: %s\n",
14760                           drm_get_format_name(mode_cmd->pixel_format));
14761                 return -EINVAL;
14762         }
14763
14764         /* FIXME need to adjust LINOFF/TILEOFF accordingly. */
14765         if (mode_cmd->offsets[0] != 0)
14766                 return -EINVAL;
14767
14768         aligned_height = intel_fb_align_height(dev, mode_cmd->height,
14769                                                mode_cmd->pixel_format,
14770                                                mode_cmd->modifier[0]);
14771         /* FIXME drm helper for size checks (especially planar formats)? */
14772         if (obj->base.size < aligned_height * mode_cmd->pitches[0])
14773                 return -EINVAL;
14774
14775         drm_helper_mode_fill_fb_struct(&intel_fb->base, mode_cmd);
14776         intel_fb->obj = obj;
14777
14778         intel_fill_fb_info(dev_priv, &intel_fb->base);
14779
14780         ret = drm_framebuffer_init(dev, &intel_fb->base, &intel_fb_funcs);
14781         if (ret) {
14782                 DRM_ERROR("framebuffer init failed %d\n", ret);
14783                 return ret;
14784         }
14785
14786         intel_fb->obj->framebuffer_references++;
14787
14788         return 0;
14789 }
14790
14791 static struct drm_framebuffer *
14792 intel_user_framebuffer_create(struct drm_device *dev,
14793                               struct drm_file *filp,
14794                               const struct drm_mode_fb_cmd2 *user_mode_cmd)
14795 {
14796         struct drm_framebuffer *fb;
14797         struct drm_i915_gem_object *obj;
14798         struct drm_mode_fb_cmd2 mode_cmd = *user_mode_cmd;
14799
14800         obj = to_intel_bo(drm_gem_object_lookup(dev, filp,
14801                                                 mode_cmd.handles[0]));
14802         if (&obj->base == NULL)
14803                 return ERR_PTR(-ENOENT);
14804
14805         fb = intel_framebuffer_create(dev, &mode_cmd, obj);
14806         if (IS_ERR(fb))
14807                 drm_gem_object_unreference_unlocked(&obj->base);
14808
14809         return fb;
14810 }
14811
14812 #ifndef CONFIG_DRM_FBDEV_EMULATION
14813 static inline void intel_fbdev_output_poll_changed(struct drm_device *dev)
14814 {
14815 }
14816 #endif
14817
14818 static const struct drm_mode_config_funcs intel_mode_funcs = {
14819         .fb_create = intel_user_framebuffer_create,
14820         .output_poll_changed = intel_fbdev_output_poll_changed,
14821         .atomic_check = intel_atomic_check,
14822         .atomic_commit = intel_atomic_commit,
14823         .atomic_state_alloc = intel_atomic_state_alloc,
14824         .atomic_state_clear = intel_atomic_state_clear,
14825 };
14826
14827 /**
14828  * intel_init_display_hooks - initialize the display modesetting hooks
14829  * @dev_priv: device private
14830  */
14831 void intel_init_display_hooks(struct drm_i915_private *dev_priv)
14832 {
14833         if (HAS_PCH_SPLIT(dev_priv) || IS_G4X(dev_priv))
14834                 dev_priv->display.find_dpll = g4x_find_best_dpll;
14835         else if (IS_CHERRYVIEW(dev_priv))
14836                 dev_priv->display.find_dpll = chv_find_best_dpll;
14837         else if (IS_VALLEYVIEW(dev_priv))
14838                 dev_priv->display.find_dpll = vlv_find_best_dpll;
14839         else if (IS_PINEVIEW(dev_priv))
14840                 dev_priv->display.find_dpll = pnv_find_best_dpll;
14841         else
14842                 dev_priv->display.find_dpll = i9xx_find_best_dpll;
14843
14844         if (INTEL_INFO(dev_priv)->gen >= 9) {
14845                 dev_priv->display.get_pipe_config = haswell_get_pipe_config;
14846                 dev_priv->display.get_initial_plane_config =
14847                         skylake_get_initial_plane_config;
14848                 dev_priv->display.crtc_compute_clock =
14849                         haswell_crtc_compute_clock;
14850                 dev_priv->display.crtc_enable = haswell_crtc_enable;
14851                 dev_priv->display.crtc_disable = haswell_crtc_disable;
14852         } else if (HAS_DDI(dev_priv)) {
14853                 dev_priv->display.get_pipe_config = haswell_get_pipe_config;
14854                 dev_priv->display.get_initial_plane_config =
14855                         ironlake_get_initial_plane_config;
14856                 dev_priv->display.crtc_compute_clock =
14857                         haswell_crtc_compute_clock;
14858                 dev_priv->display.crtc_enable = haswell_crtc_enable;
14859                 dev_priv->display.crtc_disable = haswell_crtc_disable;
14860         } else if (HAS_PCH_SPLIT(dev_priv)) {
14861                 dev_priv->display.get_pipe_config = ironlake_get_pipe_config;
14862                 dev_priv->display.get_initial_plane_config =
14863                         ironlake_get_initial_plane_config;
14864                 dev_priv->display.crtc_compute_clock =
14865                         ironlake_crtc_compute_clock;
14866                 dev_priv->display.crtc_enable = ironlake_crtc_enable;
14867                 dev_priv->display.crtc_disable = ironlake_crtc_disable;
14868         } else if (IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv)) {
14869                 dev_priv->display.get_pipe_config = i9xx_get_pipe_config;
14870                 dev_priv->display.get_initial_plane_config =
14871                         i9xx_get_initial_plane_config;
14872                 dev_priv->display.crtc_compute_clock = i9xx_crtc_compute_clock;
14873                 dev_priv->display.crtc_enable = valleyview_crtc_enable;
14874                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
14875         } else {
14876                 dev_priv->display.get_pipe_config = i9xx_get_pipe_config;
14877                 dev_priv->display.get_initial_plane_config =
14878                         i9xx_get_initial_plane_config;
14879                 dev_priv->display.crtc_compute_clock = i9xx_crtc_compute_clock;
14880                 dev_priv->display.crtc_enable = i9xx_crtc_enable;
14881                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
14882         }
14883
14884         /* Returns the core display clock speed */
14885         if (IS_SKYLAKE(dev_priv) || IS_KABYLAKE(dev_priv))
14886                 dev_priv->display.get_display_clock_speed =
14887                         skylake_get_display_clock_speed;
14888         else if (IS_BROXTON(dev_priv))
14889                 dev_priv->display.get_display_clock_speed =
14890                         broxton_get_display_clock_speed;
14891         else if (IS_BROADWELL(dev_priv))
14892                 dev_priv->display.get_display_clock_speed =
14893                         broadwell_get_display_clock_speed;
14894         else if (IS_HASWELL(dev_priv))
14895                 dev_priv->display.get_display_clock_speed =
14896                         haswell_get_display_clock_speed;
14897         else if (IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv))
14898                 dev_priv->display.get_display_clock_speed =
14899                         valleyview_get_display_clock_speed;
14900         else if (IS_GEN5(dev_priv))
14901                 dev_priv->display.get_display_clock_speed =
14902                         ilk_get_display_clock_speed;
14903         else if (IS_I945G(dev_priv) || IS_BROADWATER(dev_priv) ||
14904                  IS_GEN6(dev_priv) || IS_IVYBRIDGE(dev_priv))
14905                 dev_priv->display.get_display_clock_speed =
14906                         i945_get_display_clock_speed;
14907         else if (IS_GM45(dev_priv))
14908                 dev_priv->display.get_display_clock_speed =
14909                         gm45_get_display_clock_speed;
14910         else if (IS_CRESTLINE(dev_priv))
14911                 dev_priv->display.get_display_clock_speed =
14912                         i965gm_get_display_clock_speed;
14913         else if (IS_PINEVIEW(dev_priv))
14914                 dev_priv->display.get_display_clock_speed =
14915                         pnv_get_display_clock_speed;
14916         else if (IS_G33(dev_priv) || IS_G4X(dev_priv))
14917                 dev_priv->display.get_display_clock_speed =
14918                         g33_get_display_clock_speed;
14919         else if (IS_I915G(dev_priv))
14920                 dev_priv->display.get_display_clock_speed =
14921                         i915_get_display_clock_speed;
14922         else if (IS_I945GM(dev_priv) || IS_845G(dev_priv))
14923                 dev_priv->display.get_display_clock_speed =
14924                         i9xx_misc_get_display_clock_speed;
14925         else if (IS_I915GM(dev_priv))
14926                 dev_priv->display.get_display_clock_speed =
14927                         i915gm_get_display_clock_speed;
14928         else if (IS_I865G(dev_priv))
14929                 dev_priv->display.get_display_clock_speed =
14930                         i865_get_display_clock_speed;
14931         else if (IS_I85X(dev_priv))
14932                 dev_priv->display.get_display_clock_speed =
14933                         i85x_get_display_clock_speed;
14934         else { /* 830 */
14935                 WARN(!IS_I830(dev_priv), "Unknown platform. Assuming 133 MHz CDCLK\n");
14936                 dev_priv->display.get_display_clock_speed =
14937                         i830_get_display_clock_speed;
14938         }
14939
14940         if (IS_GEN5(dev_priv)) {
14941                 dev_priv->display.fdi_link_train = ironlake_fdi_link_train;
14942         } else if (IS_GEN6(dev_priv)) {
14943                 dev_priv->display.fdi_link_train = gen6_fdi_link_train;
14944         } else if (IS_IVYBRIDGE(dev_priv)) {
14945                 /* FIXME: detect B0+ stepping and use auto training */
14946                 dev_priv->display.fdi_link_train = ivb_manual_fdi_link_train;
14947         } else if (IS_HASWELL(dev_priv) || IS_BROADWELL(dev_priv)) {
14948                 dev_priv->display.fdi_link_train = hsw_fdi_link_train;
14949                 if (IS_BROADWELL(dev_priv)) {
14950                         dev_priv->display.modeset_commit_cdclk =
14951                                 broadwell_modeset_commit_cdclk;
14952                         dev_priv->display.modeset_calc_cdclk =
14953                                 broadwell_modeset_calc_cdclk;
14954                 }
14955         } else if (IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv)) {
14956                 dev_priv->display.modeset_commit_cdclk =
14957                         valleyview_modeset_commit_cdclk;
14958                 dev_priv->display.modeset_calc_cdclk =
14959                         valleyview_modeset_calc_cdclk;
14960         } else if (IS_BROXTON(dev_priv)) {
14961                 dev_priv->display.modeset_commit_cdclk =
14962                         broxton_modeset_commit_cdclk;
14963                 dev_priv->display.modeset_calc_cdclk =
14964                         broxton_modeset_calc_cdclk;
14965         }
14966
14967         switch (INTEL_INFO(dev_priv)->gen) {
14968         case 2:
14969                 dev_priv->display.queue_flip = intel_gen2_queue_flip;
14970                 break;
14971
14972         case 3:
14973                 dev_priv->display.queue_flip = intel_gen3_queue_flip;
14974                 break;
14975
14976         case 4:
14977         case 5:
14978                 dev_priv->display.queue_flip = intel_gen4_queue_flip;
14979                 break;
14980
14981         case 6:
14982                 dev_priv->display.queue_flip = intel_gen6_queue_flip;
14983                 break;
14984         case 7:
14985         case 8: /* FIXME(BDW): Check that the gen8 RCS flip works. */
14986                 dev_priv->display.queue_flip = intel_gen7_queue_flip;
14987                 break;
14988         case 9:
14989                 /* Drop through - unsupported since execlist only. */
14990         default:
14991                 /* Default just returns -ENODEV to indicate unsupported */
14992                 dev_priv->display.queue_flip = intel_default_queue_flip;
14993         }
14994 }
14995
14996 /*
14997  * Some BIOSes insist on assuming the GPU's pipe A is enabled at suspend,
14998  * resume, or other times.  This quirk makes sure that's the case for
14999  * affected systems.
15000  */
15001 static void quirk_pipea_force(struct drm_device *dev)
15002 {
15003         struct drm_i915_private *dev_priv = dev->dev_private;
15004
15005         dev_priv->quirks |= QUIRK_PIPEA_FORCE;
15006         DRM_INFO("applying pipe a force quirk\n");
15007 }
15008
15009 static void quirk_pipeb_force(struct drm_device *dev)
15010 {
15011         struct drm_i915_private *dev_priv = dev->dev_private;
15012
15013         dev_priv->quirks |= QUIRK_PIPEB_FORCE;
15014         DRM_INFO("applying pipe b force quirk\n");
15015 }
15016
15017 /*
15018  * Some machines (Lenovo U160) do not work with SSC on LVDS for some reason
15019  */
15020 static void quirk_ssc_force_disable(struct drm_device *dev)
15021 {
15022         struct drm_i915_private *dev_priv = dev->dev_private;
15023         dev_priv->quirks |= QUIRK_LVDS_SSC_DISABLE;
15024         DRM_INFO("applying lvds SSC disable quirk\n");
15025 }
15026
15027 /*
15028  * A machine (e.g. Acer Aspire 5734Z) may need to invert the panel backlight
15029  * brightness value
15030  */
15031 static void quirk_invert_brightness(struct drm_device *dev)
15032 {
15033         struct drm_i915_private *dev_priv = dev->dev_private;
15034         dev_priv->quirks |= QUIRK_INVERT_BRIGHTNESS;
15035         DRM_INFO("applying inverted panel brightness quirk\n");
15036 }
15037
15038 /* Some VBT's incorrectly indicate no backlight is present */
15039 static void quirk_backlight_present(struct drm_device *dev)
15040 {
15041         struct drm_i915_private *dev_priv = dev->dev_private;
15042         dev_priv->quirks |= QUIRK_BACKLIGHT_PRESENT;
15043         DRM_INFO("applying backlight present quirk\n");
15044 }
15045
15046 struct intel_quirk {
15047         int device;
15048         int subsystem_vendor;
15049         int subsystem_device;
15050         void (*hook)(struct drm_device *dev);
15051 };
15052
15053 /* For systems that don't have a meaningful PCI subdevice/subvendor ID */
15054 struct intel_dmi_quirk {
15055         void (*hook)(struct drm_device *dev);
15056         const struct dmi_system_id (*dmi_id_list)[];
15057 };
15058
15059 static int intel_dmi_reverse_brightness(const struct dmi_system_id *id)
15060 {
15061         DRM_INFO("Backlight polarity reversed on %s\n", id->ident);
15062         return 1;
15063 }
15064
15065 static const struct intel_dmi_quirk intel_dmi_quirks[] = {
15066         {
15067                 .dmi_id_list = &(const struct dmi_system_id[]) {
15068                         {
15069                                 .callback = intel_dmi_reverse_brightness,
15070                                 .ident = "NCR Corporation",
15071                                 .matches = {DMI_MATCH(DMI_SYS_VENDOR, "NCR Corporation"),
15072                                             DMI_MATCH(DMI_PRODUCT_NAME, ""),
15073                                 },
15074                         },
15075                         { }  /* terminating entry */
15076                 },
15077                 .hook = quirk_invert_brightness,
15078         },
15079 };
15080
15081 static struct intel_quirk intel_quirks[] = {
15082         /* Toshiba Protege R-205, S-209 needs pipe A force quirk */
15083         { 0x2592, 0x1179, 0x0001, quirk_pipea_force },
15084
15085         /* ThinkPad T60 needs pipe A force quirk (bug #16494) */
15086         { 0x2782, 0x17aa, 0x201a, quirk_pipea_force },
15087
15088         /* 830 needs to leave pipe A & dpll A up */
15089         { 0x3577, PCI_ANY_ID, PCI_ANY_ID, quirk_pipea_force },
15090
15091         /* 830 needs to leave pipe B & dpll B up */
15092         { 0x3577, PCI_ANY_ID, PCI_ANY_ID, quirk_pipeb_force },
15093
15094         /* Lenovo U160 cannot use SSC on LVDS */
15095         { 0x0046, 0x17aa, 0x3920, quirk_ssc_force_disable },
15096
15097         /* Sony Vaio Y cannot use SSC on LVDS */
15098         { 0x0046, 0x104d, 0x9076, quirk_ssc_force_disable },
15099
15100         /* Acer Aspire 5734Z must invert backlight brightness */
15101         { 0x2a42, 0x1025, 0x0459, quirk_invert_brightness },
15102
15103         /* Acer/eMachines G725 */
15104         { 0x2a42, 0x1025, 0x0210, quirk_invert_brightness },
15105
15106         /* Acer/eMachines e725 */
15107         { 0x2a42, 0x1025, 0x0212, quirk_invert_brightness },
15108
15109         /* Acer/Packard Bell NCL20 */
15110         { 0x2a42, 0x1025, 0x034b, quirk_invert_brightness },
15111
15112         /* Acer Aspire 4736Z */
15113         { 0x2a42, 0x1025, 0x0260, quirk_invert_brightness },
15114
15115         /* Acer Aspire 5336 */
15116         { 0x2a42, 0x1025, 0x048a, quirk_invert_brightness },
15117
15118         /* Acer C720 and C720P Chromebooks (Celeron 2955U) have backlights */
15119         { 0x0a06, 0x1025, 0x0a11, quirk_backlight_present },
15120
15121         /* Acer C720 Chromebook (Core i3 4005U) */
15122         { 0x0a16, 0x1025, 0x0a11, quirk_backlight_present },
15123
15124         /* Apple Macbook 2,1 (Core 2 T7400) */
15125         { 0x27a2, 0x8086, 0x7270, quirk_backlight_present },
15126
15127         /* Apple Macbook 4,1 */
15128         { 0x2a02, 0x106b, 0x00a1, quirk_backlight_present },
15129
15130         /* Toshiba CB35 Chromebook (Celeron 2955U) */
15131         { 0x0a06, 0x1179, 0x0a88, quirk_backlight_present },
15132
15133         /* HP Chromebook 14 (Celeron 2955U) */
15134         { 0x0a06, 0x103c, 0x21ed, quirk_backlight_present },
15135
15136         /* Dell Chromebook 11 */
15137         { 0x0a06, 0x1028, 0x0a35, quirk_backlight_present },
15138
15139         /* Dell Chromebook 11 (2015 version) */
15140         { 0x0a16, 0x1028, 0x0a35, quirk_backlight_present },
15141 };
15142
15143 static void intel_init_quirks(struct drm_device *dev)
15144 {
15145         struct pci_dev *d = dev->pdev;
15146         int i;
15147
15148         for (i = 0; i < ARRAY_SIZE(intel_quirks); i++) {
15149                 struct intel_quirk *q = &intel_quirks[i];
15150
15151                 if (d->device == q->device &&
15152                     (d->subsystem_vendor == q->subsystem_vendor ||
15153                      q->subsystem_vendor == PCI_ANY_ID) &&
15154                     (d->subsystem_device == q->subsystem_device ||
15155                      q->subsystem_device == PCI_ANY_ID))
15156                         q->hook(dev);
15157         }
15158         for (i = 0; i < ARRAY_SIZE(intel_dmi_quirks); i++) {
15159                 if (dmi_check_system(*intel_dmi_quirks[i].dmi_id_list) != 0)
15160                         intel_dmi_quirks[i].hook(dev);
15161         }
15162 }
15163
15164 /* Disable the VGA plane that we never use */
15165 static void i915_disable_vga(struct drm_device *dev)
15166 {
15167         struct drm_i915_private *dev_priv = dev->dev_private;
15168         u8 sr1;
15169         i915_reg_t vga_reg = i915_vgacntrl_reg(dev);
15170
15171         /* WaEnableVGAAccessThroughIOPort:ctg,elk,ilk,snb,ivb,vlv,hsw */
15172         vga_get_uninterruptible(dev->pdev, VGA_RSRC_LEGACY_IO);
15173         outb(SR01, VGA_SR_INDEX);
15174         sr1 = inb(VGA_SR_DATA);
15175         outb(sr1 | 1<<5, VGA_SR_DATA);
15176         vga_put(dev->pdev, VGA_RSRC_LEGACY_IO);
15177         udelay(300);
15178
15179         I915_WRITE(vga_reg, VGA_DISP_DISABLE);
15180         POSTING_READ(vga_reg);
15181 }
15182
15183 void intel_modeset_init_hw(struct drm_device *dev)
15184 {
15185         struct drm_i915_private *dev_priv = dev->dev_private;
15186
15187         intel_update_cdclk(dev);
15188
15189         dev_priv->atomic_cdclk_freq = dev_priv->cdclk_freq;
15190
15191         intel_init_clock_gating(dev);
15192         intel_enable_gt_powersave(dev);
15193 }
15194
15195 /*
15196  * Calculate what we think the watermarks should be for the state we've read
15197  * out of the hardware and then immediately program those watermarks so that
15198  * we ensure the hardware settings match our internal state.
15199  *
15200  * We can calculate what we think WM's should be by creating a duplicate of the
15201  * current state (which was constructed during hardware readout) and running it
15202  * through the atomic check code to calculate new watermark values in the
15203  * state object.
15204  */
15205 static void sanitize_watermarks(struct drm_device *dev)
15206 {
15207         struct drm_i915_private *dev_priv = to_i915(dev);
15208         struct drm_atomic_state *state;
15209         struct drm_crtc *crtc;
15210         struct drm_crtc_state *cstate;
15211         struct drm_modeset_acquire_ctx ctx;
15212         int ret;
15213         int i;
15214
15215         /* Only supported on platforms that use atomic watermark design */
15216         if (!dev_priv->display.optimize_watermarks)
15217                 return;
15218
15219         /*
15220          * We need to hold connection_mutex before calling duplicate_state so
15221          * that the connector loop is protected.
15222          */
15223         drm_modeset_acquire_init(&ctx, 0);
15224 retry:
15225         ret = drm_modeset_lock_all_ctx(dev, &ctx);
15226         if (ret == -EDEADLK) {
15227                 drm_modeset_backoff(&ctx);
15228                 goto retry;
15229         } else if (WARN_ON(ret)) {
15230                 goto fail;
15231         }
15232
15233         state = drm_atomic_helper_duplicate_state(dev, &ctx);
15234         if (WARN_ON(IS_ERR(state)))
15235                 goto fail;
15236
15237         /*
15238          * Hardware readout is the only time we don't want to calculate
15239          * intermediate watermarks (since we don't trust the current
15240          * watermarks).
15241          */
15242         to_intel_atomic_state(state)->skip_intermediate_wm = true;
15243
15244         ret = intel_atomic_check(dev, state);
15245         if (ret) {
15246                 /*
15247                  * If we fail here, it means that the hardware appears to be
15248                  * programmed in a way that shouldn't be possible, given our
15249                  * understanding of watermark requirements.  This might mean a
15250                  * mistake in the hardware readout code or a mistake in the
15251                  * watermark calculations for a given platform.  Raise a WARN
15252                  * so that this is noticeable.
15253                  *
15254                  * If this actually happens, we'll have to just leave the
15255                  * BIOS-programmed watermarks untouched and hope for the best.
15256                  */
15257                 WARN(true, "Could not determine valid watermarks for inherited state\n");
15258                 goto fail;
15259         }
15260
15261         /* Write calculated watermark values back */
15262         to_i915(dev)->wm.config = to_intel_atomic_state(state)->wm_config;
15263         for_each_crtc_in_state(state, crtc, cstate, i) {
15264                 struct intel_crtc_state *cs = to_intel_crtc_state(cstate);
15265
15266                 cs->wm.need_postvbl_update = true;
15267                 dev_priv->display.optimize_watermarks(cs);
15268         }
15269
15270         drm_atomic_state_free(state);
15271 fail:
15272         drm_modeset_drop_locks(&ctx);
15273         drm_modeset_acquire_fini(&ctx);
15274 }
15275
15276 void intel_modeset_init(struct drm_device *dev)
15277 {
15278         struct drm_i915_private *dev_priv = dev->dev_private;
15279         int sprite, ret;
15280         enum pipe pipe;
15281         struct intel_crtc *crtc;
15282
15283         drm_mode_config_init(dev);
15284
15285         dev->mode_config.min_width = 0;
15286         dev->mode_config.min_height = 0;
15287
15288         dev->mode_config.preferred_depth = 24;
15289         dev->mode_config.prefer_shadow = 1;
15290
15291         dev->mode_config.allow_fb_modifiers = true;
15292
15293         dev->mode_config.funcs = &intel_mode_funcs;
15294
15295         intel_init_quirks(dev);
15296
15297         intel_init_pm(dev);
15298
15299         if (INTEL_INFO(dev)->num_pipes == 0)
15300                 return;
15301
15302         /*
15303          * There may be no VBT; and if the BIOS enabled SSC we can
15304          * just keep using it to avoid unnecessary flicker.  Whereas if the
15305          * BIOS isn't using it, don't assume it will work even if the VBT
15306          * indicates as much.
15307          */
15308         if (HAS_PCH_IBX(dev) || HAS_PCH_CPT(dev)) {
15309                 bool bios_lvds_use_ssc = !!(I915_READ(PCH_DREF_CONTROL) &
15310                                             DREF_SSC1_ENABLE);
15311
15312                 if (dev_priv->vbt.lvds_use_ssc != bios_lvds_use_ssc) {
15313                         DRM_DEBUG_KMS("SSC %sabled by BIOS, overriding VBT which says %sabled\n",
15314                                      bios_lvds_use_ssc ? "en" : "dis",
15315                                      dev_priv->vbt.lvds_use_ssc ? "en" : "dis");
15316                         dev_priv->vbt.lvds_use_ssc = bios_lvds_use_ssc;
15317                 }
15318         }
15319
15320         if (IS_GEN2(dev)) {
15321                 dev->mode_config.max_width = 2048;
15322                 dev->mode_config.max_height = 2048;
15323         } else if (IS_GEN3(dev)) {
15324                 dev->mode_config.max_width = 4096;
15325                 dev->mode_config.max_height = 4096;
15326         } else {
15327                 dev->mode_config.max_width = 8192;
15328                 dev->mode_config.max_height = 8192;
15329         }
15330
15331         if (IS_845G(dev) || IS_I865G(dev)) {
15332                 dev->mode_config.cursor_width = IS_845G(dev) ? 64 : 512;
15333                 dev->mode_config.cursor_height = 1023;
15334         } else if (IS_GEN2(dev)) {
15335                 dev->mode_config.cursor_width = GEN2_CURSOR_WIDTH;
15336                 dev->mode_config.cursor_height = GEN2_CURSOR_HEIGHT;
15337         } else {
15338                 dev->mode_config.cursor_width = MAX_CURSOR_WIDTH;
15339                 dev->mode_config.cursor_height = MAX_CURSOR_HEIGHT;
15340         }
15341
15342         dev->mode_config.fb_base = dev_priv->gtt.mappable_base;
15343
15344         DRM_DEBUG_KMS("%d display pipe%s available.\n",
15345                       INTEL_INFO(dev)->num_pipes,
15346                       INTEL_INFO(dev)->num_pipes > 1 ? "s" : "");
15347
15348         for_each_pipe(dev_priv, pipe) {
15349                 intel_crtc_init(dev, pipe);
15350                 for_each_sprite(dev_priv, pipe, sprite) {
15351                         ret = intel_plane_init(dev, pipe, sprite);
15352                         if (ret)
15353                                 DRM_DEBUG_KMS("pipe %c sprite %c init failed: %d\n",
15354                                               pipe_name(pipe), sprite_name(pipe, sprite), ret);
15355                 }
15356         }
15357
15358         intel_update_czclk(dev_priv);
15359         intel_update_rawclk(dev_priv);
15360         intel_update_cdclk(dev);
15361
15362         intel_shared_dpll_init(dev);
15363
15364         /* Just disable it once at startup */
15365         i915_disable_vga(dev);
15366         intel_setup_outputs(dev);
15367
15368         drm_modeset_lock_all(dev);
15369         intel_modeset_setup_hw_state(dev);
15370         drm_modeset_unlock_all(dev);
15371
15372         for_each_intel_crtc(dev, crtc) {
15373                 struct intel_initial_plane_config plane_config = {};
15374
15375                 if (!crtc->active)
15376                         continue;
15377
15378                 /*
15379                  * Note that reserving the BIOS fb up front prevents us
15380                  * from stuffing other stolen allocations like the ring
15381                  * on top.  This prevents some ugliness at boot time, and
15382                  * can even allow for smooth boot transitions if the BIOS
15383                  * fb is large enough for the active pipe configuration.
15384                  */
15385                 dev_priv->display.get_initial_plane_config(crtc,
15386                                                            &plane_config);
15387
15388                 /*
15389                  * If the fb is shared between multiple heads, we'll
15390                  * just get the first one.
15391                  */
15392                 intel_find_initial_plane_obj(crtc, &plane_config);
15393         }
15394
15395         /*
15396          * Make sure hardware watermarks really match the state we read out.
15397          * Note that we need to do this after reconstructing the BIOS fb's
15398          * since the watermark calculation done here will use pstate->fb.
15399          */
15400         sanitize_watermarks(dev);
15401 }
15402
15403 static void intel_enable_pipe_a(struct drm_device *dev)
15404 {
15405         struct intel_connector *connector;
15406         struct drm_connector *crt = NULL;
15407         struct intel_load_detect_pipe load_detect_temp;
15408         struct drm_modeset_acquire_ctx *ctx = dev->mode_config.acquire_ctx;
15409
15410         /* We can't just switch on the pipe A, we need to set things up with a
15411          * proper mode and output configuration. As a gross hack, enable pipe A
15412          * by enabling the load detect pipe once. */
15413         for_each_intel_connector(dev, connector) {
15414                 if (connector->encoder->type == INTEL_OUTPUT_ANALOG) {
15415                         crt = &connector->base;
15416                         break;
15417                 }
15418         }
15419
15420         if (!crt)
15421                 return;
15422
15423         if (intel_get_load_detect_pipe(crt, NULL, &load_detect_temp, ctx))
15424                 intel_release_load_detect_pipe(crt, &load_detect_temp, ctx);
15425 }
15426
15427 static bool
15428 intel_check_plane_mapping(struct intel_crtc *crtc)
15429 {
15430         struct drm_device *dev = crtc->base.dev;
15431         struct drm_i915_private *dev_priv = dev->dev_private;
15432         u32 val;
15433
15434         if (INTEL_INFO(dev)->num_pipes == 1)
15435                 return true;
15436
15437         val = I915_READ(DSPCNTR(!crtc->plane));
15438
15439         if ((val & DISPLAY_PLANE_ENABLE) &&
15440             (!!(val & DISPPLANE_SEL_PIPE_MASK) == crtc->pipe))
15441                 return false;
15442
15443         return true;
15444 }
15445
15446 static bool intel_crtc_has_encoders(struct intel_crtc *crtc)
15447 {
15448         struct drm_device *dev = crtc->base.dev;
15449         struct intel_encoder *encoder;
15450
15451         for_each_encoder_on_crtc(dev, &crtc->base, encoder)
15452                 return true;
15453
15454         return false;
15455 }
15456
15457 static bool intel_encoder_has_connectors(struct intel_encoder *encoder)
15458 {
15459         struct drm_device *dev = encoder->base.dev;
15460         struct intel_connector *connector;
15461
15462         for_each_connector_on_encoder(dev, &encoder->base, connector)
15463                 return true;
15464
15465         return false;
15466 }
15467
15468 static void intel_sanitize_crtc(struct intel_crtc *crtc)
15469 {
15470         struct drm_device *dev = crtc->base.dev;
15471         struct drm_i915_private *dev_priv = dev->dev_private;
15472         i915_reg_t reg = PIPECONF(crtc->config->cpu_transcoder);
15473
15474         /* Clear any frame start delays used for debugging left by the BIOS */
15475         I915_WRITE(reg, I915_READ(reg) & ~PIPECONF_FRAME_START_DELAY_MASK);
15476
15477         /* restore vblank interrupts to correct state */
15478         drm_crtc_vblank_reset(&crtc->base);
15479         if (crtc->active) {
15480                 struct intel_plane *plane;
15481
15482                 drm_crtc_vblank_on(&crtc->base);
15483
15484                 /* Disable everything but the primary plane */
15485                 for_each_intel_plane_on_crtc(dev, crtc, plane) {
15486                         if (plane->base.type == DRM_PLANE_TYPE_PRIMARY)
15487                                 continue;
15488
15489                         plane->disable_plane(&plane->base, &crtc->base);
15490                 }
15491         }
15492
15493         /* We need to sanitize the plane -> pipe mapping first because this will
15494          * disable the crtc (and hence change the state) if it is wrong. Note
15495          * that gen4+ has a fixed plane -> pipe mapping.  */
15496         if (INTEL_INFO(dev)->gen < 4 && !intel_check_plane_mapping(crtc)) {
15497                 bool plane;
15498
15499                 DRM_DEBUG_KMS("[CRTC:%d] wrong plane connection detected!\n",
15500                               crtc->base.base.id);
15501
15502                 /* Pipe has the wrong plane attached and the plane is active.
15503                  * Temporarily change the plane mapping and disable everything
15504                  * ...  */
15505                 plane = crtc->plane;
15506                 to_intel_plane_state(crtc->base.primary->state)->visible = true;
15507                 crtc->plane = !plane;
15508                 intel_crtc_disable_noatomic(&crtc->base);
15509                 crtc->plane = plane;
15510         }
15511
15512         if (dev_priv->quirks & QUIRK_PIPEA_FORCE &&
15513             crtc->pipe == PIPE_A && !crtc->active) {
15514                 /* BIOS forgot to enable pipe A, this mostly happens after
15515                  * resume. Force-enable the pipe to fix this, the update_dpms
15516                  * call below we restore the pipe to the right state, but leave
15517                  * the required bits on. */
15518                 intel_enable_pipe_a(dev);
15519         }
15520
15521         /* Adjust the state of the output pipe according to whether we
15522          * have active connectors/encoders. */
15523         if (crtc->active && !intel_crtc_has_encoders(crtc))
15524                 intel_crtc_disable_noatomic(&crtc->base);
15525
15526         if (crtc->active || HAS_GMCH_DISPLAY(dev)) {
15527                 /*
15528                  * We start out with underrun reporting disabled to avoid races.
15529                  * For correct bookkeeping mark this on active crtcs.
15530                  *
15531                  * Also on gmch platforms we dont have any hardware bits to
15532                  * disable the underrun reporting. Which means we need to start
15533                  * out with underrun reporting disabled also on inactive pipes,
15534                  * since otherwise we'll complain about the garbage we read when
15535                  * e.g. coming up after runtime pm.
15536                  *
15537                  * No protection against concurrent access is required - at
15538                  * worst a fifo underrun happens which also sets this to false.
15539                  */
15540                 crtc->cpu_fifo_underrun_disabled = true;
15541                 crtc->pch_fifo_underrun_disabled = true;
15542         }
15543 }
15544
15545 static void intel_sanitize_encoder(struct intel_encoder *encoder)
15546 {
15547         struct intel_connector *connector;
15548         struct drm_device *dev = encoder->base.dev;
15549
15550         /* We need to check both for a crtc link (meaning that the
15551          * encoder is active and trying to read from a pipe) and the
15552          * pipe itself being active. */
15553         bool has_active_crtc = encoder->base.crtc &&
15554                 to_intel_crtc(encoder->base.crtc)->active;
15555
15556         if (intel_encoder_has_connectors(encoder) && !has_active_crtc) {
15557                 DRM_DEBUG_KMS("[ENCODER:%d:%s] has active connectors but no active pipe!\n",
15558                               encoder->base.base.id,
15559                               encoder->base.name);
15560
15561                 /* Connector is active, but has no active pipe. This is
15562                  * fallout from our resume register restoring. Disable
15563                  * the encoder manually again. */
15564                 if (encoder->base.crtc) {
15565                         DRM_DEBUG_KMS("[ENCODER:%d:%s] manually disabled\n",
15566                                       encoder->base.base.id,
15567                                       encoder->base.name);
15568                         encoder->disable(encoder);
15569                         if (encoder->post_disable)
15570                                 encoder->post_disable(encoder);
15571                 }
15572                 encoder->base.crtc = NULL;
15573
15574                 /* Inconsistent output/port/pipe state happens presumably due to
15575                  * a bug in one of the get_hw_state functions. Or someplace else
15576                  * in our code, like the register restore mess on resume. Clamp
15577                  * things to off as a safer default. */
15578                 for_each_intel_connector(dev, connector) {
15579                         if (connector->encoder != encoder)
15580                                 continue;
15581                         connector->base.dpms = DRM_MODE_DPMS_OFF;
15582                         connector->base.encoder = NULL;
15583                 }
15584         }
15585         /* Enabled encoders without active connectors will be fixed in
15586          * the crtc fixup. */
15587 }
15588
15589 void i915_redisable_vga_power_on(struct drm_device *dev)
15590 {
15591         struct drm_i915_private *dev_priv = dev->dev_private;
15592         i915_reg_t vga_reg = i915_vgacntrl_reg(dev);
15593
15594         if (!(I915_READ(vga_reg) & VGA_DISP_DISABLE)) {
15595                 DRM_DEBUG_KMS("Something enabled VGA plane, disabling it\n");
15596                 i915_disable_vga(dev);
15597         }
15598 }
15599
15600 void i915_redisable_vga(struct drm_device *dev)
15601 {
15602         struct drm_i915_private *dev_priv = dev->dev_private;
15603
15604         /* This function can be called both from intel_modeset_setup_hw_state or
15605          * at a very early point in our resume sequence, where the power well
15606          * structures are not yet restored. Since this function is at a very
15607          * paranoid "someone might have enabled VGA while we were not looking"
15608          * level, just check if the power well is enabled instead of trying to
15609          * follow the "don't touch the power well if we don't need it" policy
15610          * the rest of the driver uses. */
15611         if (!intel_display_power_get_if_enabled(dev_priv, POWER_DOMAIN_VGA))
15612                 return;
15613
15614         i915_redisable_vga_power_on(dev);
15615
15616         intel_display_power_put(dev_priv, POWER_DOMAIN_VGA);
15617 }
15618
15619 static bool primary_get_hw_state(struct intel_plane *plane)
15620 {
15621         struct drm_i915_private *dev_priv = to_i915(plane->base.dev);
15622
15623         return I915_READ(DSPCNTR(plane->plane)) & DISPLAY_PLANE_ENABLE;
15624 }
15625
15626 /* FIXME read out full plane state for all planes */
15627 static void readout_plane_state(struct intel_crtc *crtc)
15628 {
15629         struct drm_plane *primary = crtc->base.primary;
15630         struct intel_plane_state *plane_state =
15631                 to_intel_plane_state(primary->state);
15632
15633         plane_state->visible = crtc->active &&
15634                 primary_get_hw_state(to_intel_plane(primary));
15635
15636         if (plane_state->visible)
15637                 crtc->base.state->plane_mask |= 1 << drm_plane_index(primary);
15638 }
15639
15640 static void intel_modeset_readout_hw_state(struct drm_device *dev)
15641 {
15642         struct drm_i915_private *dev_priv = dev->dev_private;
15643         enum pipe pipe;
15644         struct intel_crtc *crtc;
15645         struct intel_encoder *encoder;
15646         struct intel_connector *connector;
15647         int i;
15648
15649         dev_priv->active_crtcs = 0;
15650
15651         for_each_intel_crtc(dev, crtc) {
15652                 struct intel_crtc_state *crtc_state = crtc->config;
15653                 int pixclk = 0;
15654
15655                 __drm_atomic_helper_crtc_destroy_state(&crtc->base, &crtc_state->base);
15656                 memset(crtc_state, 0, sizeof(*crtc_state));
15657                 crtc_state->base.crtc = &crtc->base;
15658
15659                 crtc_state->base.active = crtc_state->base.enable =
15660                         dev_priv->display.get_pipe_config(crtc, crtc_state);
15661
15662                 crtc->base.enabled = crtc_state->base.enable;
15663                 crtc->active = crtc_state->base.active;
15664
15665                 if (crtc_state->base.active) {
15666                         dev_priv->active_crtcs |= 1 << crtc->pipe;
15667
15668                         if (IS_BROADWELL(dev_priv)) {
15669                                 pixclk = ilk_pipe_pixel_rate(crtc_state);
15670
15671                                 /* pixel rate mustn't exceed 95% of cdclk with IPS on BDW */
15672                                 if (crtc_state->ips_enabled)
15673                                         pixclk = DIV_ROUND_UP(pixclk * 100, 95);
15674                         } else if (IS_VALLEYVIEW(dev_priv) ||
15675                                    IS_CHERRYVIEW(dev_priv) ||
15676                                    IS_BROXTON(dev_priv))
15677                                 pixclk = crtc_state->base.adjusted_mode.crtc_clock;
15678                         else
15679                                 WARN_ON(dev_priv->display.modeset_calc_cdclk);
15680                 }
15681
15682                 dev_priv->min_pixclk[crtc->pipe] = pixclk;
15683
15684                 readout_plane_state(crtc);
15685
15686                 DRM_DEBUG_KMS("[CRTC:%d] hw state readout: %s\n",
15687                               crtc->base.base.id,
15688                               crtc->active ? "enabled" : "disabled");
15689         }
15690
15691         for (i = 0; i < dev_priv->num_shared_dpll; i++) {
15692                 struct intel_shared_dpll *pll = &dev_priv->shared_dplls[i];
15693
15694                 pll->on = pll->funcs.get_hw_state(dev_priv, pll,
15695                                                   &pll->config.hw_state);
15696                 pll->config.crtc_mask = 0;
15697                 for_each_intel_crtc(dev, crtc) {
15698                         if (crtc->active && crtc->config->shared_dpll == pll)
15699                                 pll->config.crtc_mask |= 1 << crtc->pipe;
15700                 }
15701                 pll->active_mask = pll->config.crtc_mask;
15702
15703                 DRM_DEBUG_KMS("%s hw state readout: crtc_mask 0x%08x, on %i\n",
15704                               pll->name, pll->config.crtc_mask, pll->on);
15705         }
15706
15707         for_each_intel_encoder(dev, encoder) {
15708                 pipe = 0;
15709
15710                 if (encoder->get_hw_state(encoder, &pipe)) {
15711                         crtc = to_intel_crtc(dev_priv->pipe_to_crtc_mapping[pipe]);
15712                         encoder->base.crtc = &crtc->base;
15713                         encoder->get_config(encoder, crtc->config);
15714                 } else {
15715                         encoder->base.crtc = NULL;
15716                 }
15717
15718                 DRM_DEBUG_KMS("[ENCODER:%d:%s] hw state readout: %s, pipe %c\n",
15719                               encoder->base.base.id,
15720                               encoder->base.name,
15721                               encoder->base.crtc ? "enabled" : "disabled",
15722                               pipe_name(pipe));
15723         }
15724
15725         for_each_intel_connector(dev, connector) {
15726                 if (connector->get_hw_state(connector)) {
15727                         connector->base.dpms = DRM_MODE_DPMS_ON;
15728
15729                         encoder = connector->encoder;
15730                         connector->base.encoder = &encoder->base;
15731
15732                         if (encoder->base.crtc &&
15733                             encoder->base.crtc->state->active) {
15734                                 /*
15735                                  * This has to be done during hardware readout
15736                                  * because anything calling .crtc_disable may
15737                                  * rely on the connector_mask being accurate.
15738                                  */
15739                                 encoder->base.crtc->state->connector_mask |=
15740                                         1 << drm_connector_index(&connector->base);
15741                                 encoder->base.crtc->state->encoder_mask |=
15742                                         1 << drm_encoder_index(&encoder->base);
15743                         }
15744
15745                 } else {
15746                         connector->base.dpms = DRM_MODE_DPMS_OFF;
15747                         connector->base.encoder = NULL;
15748                 }
15749                 DRM_DEBUG_KMS("[CONNECTOR:%d:%s] hw state readout: %s\n",
15750                               connector->base.base.id,
15751                               connector->base.name,
15752                               connector->base.encoder ? "enabled" : "disabled");
15753         }
15754
15755         for_each_intel_crtc(dev, crtc) {
15756                 crtc->base.hwmode = crtc->config->base.adjusted_mode;
15757
15758                 memset(&crtc->base.mode, 0, sizeof(crtc->base.mode));
15759                 if (crtc->base.state->active) {
15760                         intel_mode_from_pipe_config(&crtc->base.mode, crtc->config);
15761                         intel_mode_from_pipe_config(&crtc->base.state->adjusted_mode, crtc->config);
15762                         WARN_ON(drm_atomic_set_mode_for_crtc(crtc->base.state, &crtc->base.mode));
15763
15764                         /*
15765                          * The initial mode needs to be set in order to keep
15766                          * the atomic core happy. It wants a valid mode if the
15767                          * crtc's enabled, so we do the above call.
15768                          *
15769                          * At this point some state updated by the connectors
15770                          * in their ->detect() callback has not run yet, so
15771                          * no recalculation can be done yet.
15772                          *
15773                          * Even if we could do a recalculation and modeset
15774                          * right now it would cause a double modeset if
15775                          * fbdev or userspace chooses a different initial mode.
15776                          *
15777                          * If that happens, someone indicated they wanted a
15778                          * mode change, which means it's safe to do a full
15779                          * recalculation.
15780                          */
15781                         crtc->base.state->mode.private_flags = I915_MODE_FLAG_INHERITED;
15782
15783                         drm_calc_timestamping_constants(&crtc->base, &crtc->base.hwmode);
15784                         update_scanline_offset(crtc);
15785                 }
15786
15787                 intel_pipe_config_sanity_check(dev_priv, crtc->config);
15788         }
15789 }
15790
15791 /* Scan out the current hw modeset state,
15792  * and sanitizes it to the current state
15793  */
15794 static void
15795 intel_modeset_setup_hw_state(struct drm_device *dev)
15796 {
15797         struct drm_i915_private *dev_priv = dev->dev_private;
15798         enum pipe pipe;
15799         struct intel_crtc *crtc;
15800         struct intel_encoder *encoder;
15801         int i;
15802
15803         intel_modeset_readout_hw_state(dev);
15804
15805         /* HW state is read out, now we need to sanitize this mess. */
15806         for_each_intel_encoder(dev, encoder) {
15807                 intel_sanitize_encoder(encoder);
15808         }
15809
15810         for_each_pipe(dev_priv, pipe) {
15811                 crtc = to_intel_crtc(dev_priv->pipe_to_crtc_mapping[pipe]);
15812                 intel_sanitize_crtc(crtc);
15813                 intel_dump_pipe_config(crtc, crtc->config,
15814                                        "[setup_hw_state]");
15815         }
15816
15817         intel_modeset_update_connector_atomic_state(dev);
15818
15819         for (i = 0; i < dev_priv->num_shared_dpll; i++) {
15820                 struct intel_shared_dpll *pll = &dev_priv->shared_dplls[i];
15821
15822                 if (!pll->on || pll->active_mask)
15823                         continue;
15824
15825                 DRM_DEBUG_KMS("%s enabled but not in use, disabling\n", pll->name);
15826
15827                 pll->funcs.disable(dev_priv, pll);
15828                 pll->on = false;
15829         }
15830
15831         if (IS_VALLEYVIEW(dev) || IS_CHERRYVIEW(dev))
15832                 vlv_wm_get_hw_state(dev);
15833         else if (IS_GEN9(dev))
15834                 skl_wm_get_hw_state(dev);
15835         else if (HAS_PCH_SPLIT(dev))
15836                 ilk_wm_get_hw_state(dev);
15837
15838         for_each_intel_crtc(dev, crtc) {
15839                 unsigned long put_domains;
15840
15841                 put_domains = modeset_get_crtc_power_domains(&crtc->base, crtc->config);
15842                 if (WARN_ON(put_domains))
15843                         modeset_put_power_domains(dev_priv, put_domains);
15844         }
15845         intel_display_set_init_power(dev_priv, false);
15846
15847         intel_fbc_init_pipe_state(dev_priv);
15848 }
15849
15850 void intel_display_resume(struct drm_device *dev)
15851 {
15852         struct drm_i915_private *dev_priv = to_i915(dev);
15853         struct drm_atomic_state *state = dev_priv->modeset_restore_state;
15854         struct drm_modeset_acquire_ctx ctx;
15855         int ret;
15856         bool setup = false;
15857
15858         dev_priv->modeset_restore_state = NULL;
15859
15860         /*
15861          * This is a cludge because with real atomic modeset mode_config.mutex
15862          * won't be taken. Unfortunately some probed state like
15863          * audio_codec_enable is still protected by mode_config.mutex, so lock
15864          * it here for now.
15865          */
15866         mutex_lock(&dev->mode_config.mutex);
15867         drm_modeset_acquire_init(&ctx, 0);
15868
15869 retry:
15870         ret = drm_modeset_lock_all_ctx(dev, &ctx);
15871
15872         if (ret == 0 && !setup) {
15873                 setup = true;
15874
15875                 intel_modeset_setup_hw_state(dev);
15876                 i915_redisable_vga(dev);
15877         }
15878
15879         if (ret == 0 && state) {
15880                 struct drm_crtc_state *crtc_state;
15881                 struct drm_crtc *crtc;
15882                 int i;
15883
15884                 state->acquire_ctx = &ctx;
15885
15886                 for_each_crtc_in_state(state, crtc, crtc_state, i) {
15887                         /*
15888                          * Force recalculation even if we restore
15889                          * current state. With fast modeset this may not result
15890                          * in a modeset when the state is compatible.
15891                          */
15892                         crtc_state->mode_changed = true;
15893                 }
15894
15895                 ret = drm_atomic_commit(state);
15896         }
15897
15898         if (ret == -EDEADLK) {
15899                 drm_modeset_backoff(&ctx);
15900                 goto retry;
15901         }
15902
15903         drm_modeset_drop_locks(&ctx);
15904         drm_modeset_acquire_fini(&ctx);
15905         mutex_unlock(&dev->mode_config.mutex);
15906
15907         if (ret) {
15908                 DRM_ERROR("Restoring old state failed with %i\n", ret);
15909                 drm_atomic_state_free(state);
15910         }
15911 }
15912
15913 void intel_modeset_gem_init(struct drm_device *dev)
15914 {
15915         struct drm_crtc *c;
15916         struct drm_i915_gem_object *obj;
15917         int ret;
15918
15919         intel_init_gt_powersave(dev);
15920
15921         intel_modeset_init_hw(dev);
15922
15923         intel_setup_overlay(dev);
15924
15925         /*
15926          * Make sure any fbs we allocated at startup are properly
15927          * pinned & fenced.  When we do the allocation it's too early
15928          * for this.
15929          */
15930         for_each_crtc(dev, c) {
15931                 obj = intel_fb_obj(c->primary->fb);
15932                 if (obj == NULL)
15933                         continue;
15934
15935                 mutex_lock(&dev->struct_mutex);
15936                 ret = intel_pin_and_fence_fb_obj(c->primary->fb,
15937                                                  c->primary->state->rotation);
15938                 mutex_unlock(&dev->struct_mutex);
15939                 if (ret) {
15940                         DRM_ERROR("failed to pin boot fb on pipe %d\n",
15941                                   to_intel_crtc(c)->pipe);
15942                         drm_framebuffer_unreference(c->primary->fb);
15943                         c->primary->fb = NULL;
15944                         c->primary->crtc = c->primary->state->crtc = NULL;
15945                         update_state_fb(c->primary);
15946                         c->state->plane_mask &= ~(1 << drm_plane_index(c->primary));
15947                 }
15948         }
15949
15950         intel_backlight_register(dev);
15951 }
15952
15953 void intel_connector_unregister(struct intel_connector *intel_connector)
15954 {
15955         struct drm_connector *connector = &intel_connector->base;
15956
15957         intel_panel_destroy_backlight(connector);
15958         drm_connector_unregister(connector);
15959 }
15960
15961 void intel_modeset_cleanup(struct drm_device *dev)
15962 {
15963         struct drm_i915_private *dev_priv = dev->dev_private;
15964         struct intel_connector *connector;
15965
15966         intel_disable_gt_powersave(dev);
15967
15968         intel_backlight_unregister(dev);
15969
15970         /*
15971          * Interrupts and polling as the first thing to avoid creating havoc.
15972          * Too much stuff here (turning of connectors, ...) would
15973          * experience fancy races otherwise.
15974          */
15975         intel_irq_uninstall(dev_priv);
15976
15977         /*
15978          * Due to the hpd irq storm handling the hotplug work can re-arm the
15979          * poll handlers. Hence disable polling after hpd handling is shut down.
15980          */
15981         drm_kms_helper_poll_fini(dev);
15982
15983         intel_unregister_dsm_handler();
15984
15985         intel_fbc_global_disable(dev_priv);
15986
15987         /* flush any delayed tasks or pending work */
15988         flush_scheduled_work();
15989
15990         /* destroy the backlight and sysfs files before encoders/connectors */
15991         for_each_intel_connector(dev, connector)
15992                 connector->unregister(connector);
15993
15994         drm_mode_config_cleanup(dev);
15995
15996         intel_cleanup_overlay(dev);
15997
15998         intel_cleanup_gt_powersave(dev);
15999
16000         intel_teardown_gmbus(dev);
16001 }
16002
16003 /*
16004  * Return which encoder is currently attached for connector.
16005  */
16006 struct drm_encoder *intel_best_encoder(struct drm_connector *connector)
16007 {
16008         return &intel_attached_encoder(connector)->base;
16009 }
16010
16011 void intel_connector_attach_encoder(struct intel_connector *connector,
16012                                     struct intel_encoder *encoder)
16013 {
16014         connector->encoder = encoder;
16015         drm_mode_connector_attach_encoder(&connector->base,
16016                                           &encoder->base);
16017 }
16018
16019 /*
16020  * set vga decode state - true == enable VGA decode
16021  */
16022 int intel_modeset_vga_set_state(struct drm_device *dev, bool state)
16023 {
16024         struct drm_i915_private *dev_priv = dev->dev_private;
16025         unsigned reg = INTEL_INFO(dev)->gen >= 6 ? SNB_GMCH_CTRL : INTEL_GMCH_CTRL;
16026         u16 gmch_ctrl;
16027
16028         if (pci_read_config_word(dev_priv->bridge_dev, reg, &gmch_ctrl)) {
16029                 DRM_ERROR("failed to read control word\n");
16030                 return -EIO;
16031         }
16032
16033         if (!!(gmch_ctrl & INTEL_GMCH_VGA_DISABLE) == !state)
16034                 return 0;
16035
16036         if (state)
16037                 gmch_ctrl &= ~INTEL_GMCH_VGA_DISABLE;
16038         else
16039                 gmch_ctrl |= INTEL_GMCH_VGA_DISABLE;
16040
16041         if (pci_write_config_word(dev_priv->bridge_dev, reg, gmch_ctrl)) {
16042                 DRM_ERROR("failed to write control word\n");
16043                 return -EIO;
16044         }
16045
16046         return 0;
16047 }
16048
16049 struct intel_display_error_state {
16050
16051         u32 power_well_driver;
16052
16053         int num_transcoders;
16054
16055         struct intel_cursor_error_state {
16056                 u32 control;
16057                 u32 position;
16058                 u32 base;
16059                 u32 size;
16060         } cursor[I915_MAX_PIPES];
16061
16062         struct intel_pipe_error_state {
16063                 bool power_domain_on;
16064                 u32 source;
16065                 u32 stat;
16066         } pipe[I915_MAX_PIPES];
16067
16068         struct intel_plane_error_state {
16069                 u32 control;
16070                 u32 stride;
16071                 u32 size;
16072                 u32 pos;
16073                 u32 addr;
16074                 u32 surface;
16075                 u32 tile_offset;
16076         } plane[I915_MAX_PIPES];
16077
16078         struct intel_transcoder_error_state {
16079                 bool power_domain_on;
16080                 enum transcoder cpu_transcoder;
16081
16082                 u32 conf;
16083
16084                 u32 htotal;
16085                 u32 hblank;
16086                 u32 hsync;
16087                 u32 vtotal;
16088                 u32 vblank;
16089                 u32 vsync;
16090         } transcoder[4];
16091 };
16092
16093 struct intel_display_error_state *
16094 intel_display_capture_error_state(struct drm_device *dev)
16095 {
16096         struct drm_i915_private *dev_priv = dev->dev_private;
16097         struct intel_display_error_state *error;
16098         int transcoders[] = {
16099                 TRANSCODER_A,
16100                 TRANSCODER_B,
16101                 TRANSCODER_C,
16102                 TRANSCODER_EDP,
16103         };
16104         int i;
16105
16106         if (INTEL_INFO(dev)->num_pipes == 0)
16107                 return NULL;
16108
16109         error = kzalloc(sizeof(*error), GFP_ATOMIC);
16110         if (error == NULL)
16111                 return NULL;
16112
16113         if (IS_HASWELL(dev) || IS_BROADWELL(dev))
16114                 error->power_well_driver = I915_READ(HSW_PWR_WELL_DRIVER);
16115
16116         for_each_pipe(dev_priv, i) {
16117                 error->pipe[i].power_domain_on =
16118                         __intel_display_power_is_enabled(dev_priv,
16119                                                          POWER_DOMAIN_PIPE(i));
16120                 if (!error->pipe[i].power_domain_on)
16121                         continue;
16122
16123                 error->cursor[i].control = I915_READ(CURCNTR(i));
16124                 error->cursor[i].position = I915_READ(CURPOS(i));
16125                 error->cursor[i].base = I915_READ(CURBASE(i));
16126
16127                 error->plane[i].control = I915_READ(DSPCNTR(i));
16128                 error->plane[i].stride = I915_READ(DSPSTRIDE(i));
16129                 if (INTEL_INFO(dev)->gen <= 3) {
16130                         error->plane[i].size = I915_READ(DSPSIZE(i));
16131                         error->plane[i].pos = I915_READ(DSPPOS(i));
16132                 }
16133                 if (INTEL_INFO(dev)->gen <= 7 && !IS_HASWELL(dev))
16134                         error->plane[i].addr = I915_READ(DSPADDR(i));
16135                 if (INTEL_INFO(dev)->gen >= 4) {
16136                         error->plane[i].surface = I915_READ(DSPSURF(i));
16137                         error->plane[i].tile_offset = I915_READ(DSPTILEOFF(i));
16138                 }
16139
16140                 error->pipe[i].source = I915_READ(PIPESRC(i));
16141
16142                 if (HAS_GMCH_DISPLAY(dev))
16143                         error->pipe[i].stat = I915_READ(PIPESTAT(i));
16144         }
16145
16146         error->num_transcoders = INTEL_INFO(dev)->num_pipes;
16147         if (HAS_DDI(dev_priv->dev))
16148                 error->num_transcoders++; /* Account for eDP. */
16149
16150         for (i = 0; i < error->num_transcoders; i++) {
16151                 enum transcoder cpu_transcoder = transcoders[i];
16152
16153                 error->transcoder[i].power_domain_on =
16154                         __intel_display_power_is_enabled(dev_priv,
16155                                 POWER_DOMAIN_TRANSCODER(cpu_transcoder));
16156                 if (!error->transcoder[i].power_domain_on)
16157                         continue;
16158
16159                 error->transcoder[i].cpu_transcoder = cpu_transcoder;
16160
16161                 error->transcoder[i].conf = I915_READ(PIPECONF(cpu_transcoder));
16162                 error->transcoder[i].htotal = I915_READ(HTOTAL(cpu_transcoder));
16163                 error->transcoder[i].hblank = I915_READ(HBLANK(cpu_transcoder));
16164                 error->transcoder[i].hsync = I915_READ(HSYNC(cpu_transcoder));
16165                 error->transcoder[i].vtotal = I915_READ(VTOTAL(cpu_transcoder));
16166                 error->transcoder[i].vblank = I915_READ(VBLANK(cpu_transcoder));
16167                 error->transcoder[i].vsync = I915_READ(VSYNC(cpu_transcoder));
16168         }
16169
16170         return error;
16171 }
16172
16173 #define err_printf(e, ...) i915_error_printf(e, __VA_ARGS__)
16174
16175 void
16176 intel_display_print_error_state(struct drm_i915_error_state_buf *m,
16177                                 struct drm_device *dev,
16178                                 struct intel_display_error_state *error)
16179 {
16180         struct drm_i915_private *dev_priv = dev->dev_private;
16181         int i;
16182
16183         if (!error)
16184                 return;
16185
16186         err_printf(m, "Num Pipes: %d\n", INTEL_INFO(dev)->num_pipes);
16187         if (IS_HASWELL(dev) || IS_BROADWELL(dev))
16188                 err_printf(m, "PWR_WELL_CTL2: %08x\n",
16189                            error->power_well_driver);
16190         for_each_pipe(dev_priv, i) {
16191                 err_printf(m, "Pipe [%d]:\n", i);
16192                 err_printf(m, "  Power: %s\n",
16193                            onoff(error->pipe[i].power_domain_on));
16194                 err_printf(m, "  SRC: %08x\n", error->pipe[i].source);
16195                 err_printf(m, "  STAT: %08x\n", error->pipe[i].stat);
16196
16197                 err_printf(m, "Plane [%d]:\n", i);
16198                 err_printf(m, "  CNTR: %08x\n", error->plane[i].control);
16199                 err_printf(m, "  STRIDE: %08x\n", error->plane[i].stride);
16200                 if (INTEL_INFO(dev)->gen <= 3) {
16201                         err_printf(m, "  SIZE: %08x\n", error->plane[i].size);
16202                         err_printf(m, "  POS: %08x\n", error->plane[i].pos);
16203                 }
16204                 if (INTEL_INFO(dev)->gen <= 7 && !IS_HASWELL(dev))
16205                         err_printf(m, "  ADDR: %08x\n", error->plane[i].addr);
16206                 if (INTEL_INFO(dev)->gen >= 4) {
16207                         err_printf(m, "  SURF: %08x\n", error->plane[i].surface);
16208                         err_printf(m, "  TILEOFF: %08x\n", error->plane[i].tile_offset);
16209                 }
16210
16211                 err_printf(m, "Cursor [%d]:\n", i);
16212                 err_printf(m, "  CNTR: %08x\n", error->cursor[i].control);
16213                 err_printf(m, "  POS: %08x\n", error->cursor[i].position);
16214                 err_printf(m, "  BASE: %08x\n", error->cursor[i].base);
16215         }
16216
16217         for (i = 0; i < error->num_transcoders; i++) {
16218                 err_printf(m, "CPU transcoder: %s\n",
16219                            transcoder_name(error->transcoder[i].cpu_transcoder));
16220                 err_printf(m, "  Power: %s\n",
16221                            onoff(error->transcoder[i].power_domain_on));
16222                 err_printf(m, "  CONF: %08x\n", error->transcoder[i].conf);
16223                 err_printf(m, "  HTOTAL: %08x\n", error->transcoder[i].htotal);
16224                 err_printf(m, "  HBLANK: %08x\n", error->transcoder[i].hblank);
16225                 err_printf(m, "  HSYNC: %08x\n", error->transcoder[i].hsync);
16226                 err_printf(m, "  VTOTAL: %08x\n", error->transcoder[i].vtotal);
16227                 err_printf(m, "  VBLANK: %08x\n", error->transcoder[i].vblank);
16228                 err_printf(m, "  VSYNC: %08x\n", error->transcoder[i].vsync);
16229         }
16230 }