Merge tag 'drm-intel-next-2015-12-18' of git://anongit.freedesktop.org/drm-intel...
[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 intel_crtc_update_cursor(struct drm_crtc *crtc, bool on);
89
90 static void i9xx_crtc_clock_get(struct intel_crtc *crtc,
91                                 struct intel_crtc_state *pipe_config);
92 static void ironlake_pch_clock_get(struct intel_crtc *crtc,
93                                    struct intel_crtc_state *pipe_config);
94
95 static int intel_framebuffer_init(struct drm_device *dev,
96                                   struct intel_framebuffer *ifb,
97                                   struct drm_mode_fb_cmd2 *mode_cmd,
98                                   struct drm_i915_gem_object *obj);
99 static void i9xx_set_pipeconf(struct intel_crtc *intel_crtc);
100 static void intel_set_pipe_timings(struct intel_crtc *intel_crtc);
101 static void intel_cpu_transcoder_set_m_n(struct intel_crtc *crtc,
102                                          struct intel_link_m_n *m_n,
103                                          struct intel_link_m_n *m2_n2);
104 static void ironlake_set_pipeconf(struct drm_crtc *crtc);
105 static void haswell_set_pipeconf(struct drm_crtc *crtc);
106 static void intel_set_pipe_csc(struct drm_crtc *crtc);
107 static void vlv_prepare_pll(struct intel_crtc *crtc,
108                             const struct intel_crtc_state *pipe_config);
109 static void chv_prepare_pll(struct intel_crtc *crtc,
110                             const struct intel_crtc_state *pipe_config);
111 static void intel_begin_crtc_commit(struct drm_crtc *, struct drm_crtc_state *);
112 static void intel_finish_crtc_commit(struct drm_crtc *, struct drm_crtc_state *);
113 static void skl_init_scalers(struct drm_device *dev, struct intel_crtc *intel_crtc,
114         struct intel_crtc_state *crtc_state);
115 static int i9xx_get_refclk(const struct intel_crtc_state *crtc_state,
116                            int num_connectors);
117 static void skylake_pfit_enable(struct intel_crtc *crtc);
118 static void ironlake_pfit_disable(struct intel_crtc *crtc, bool force);
119 static void ironlake_pfit_enable(struct intel_crtc *crtc);
120 static void intel_modeset_setup_hw_state(struct drm_device *dev);
121 static void intel_pre_disable_primary(struct drm_crtc *crtc);
122
123 typedef struct {
124         int     min, max;
125 } intel_range_t;
126
127 typedef struct {
128         int     dot_limit;
129         int     p2_slow, p2_fast;
130 } intel_p2_t;
131
132 typedef struct intel_limit intel_limit_t;
133 struct intel_limit {
134         intel_range_t   dot, vco, n, m, m1, m2, p, p1;
135         intel_p2_t          p2;
136 };
137
138 /* returns HPLL frequency in kHz */
139 static int valleyview_get_vco(struct drm_i915_private *dev_priv)
140 {
141         int hpll_freq, vco_freq[] = { 800, 1600, 2000, 2400 };
142
143         /* Obtain SKU information */
144         mutex_lock(&dev_priv->sb_lock);
145         hpll_freq = vlv_cck_read(dev_priv, CCK_FUSE_REG) &
146                 CCK_FUSE_HPLL_FREQ_MASK;
147         mutex_unlock(&dev_priv->sb_lock);
148
149         return vco_freq[hpll_freq] * 1000;
150 }
151
152 static int vlv_get_cck_clock_hpll(struct drm_i915_private *dev_priv,
153                                   const char *name, u32 reg)
154 {
155         u32 val;
156         int divider;
157
158         if (dev_priv->hpll_freq == 0)
159                 dev_priv->hpll_freq = valleyview_get_vco(dev_priv);
160
161         mutex_lock(&dev_priv->sb_lock);
162         val = vlv_cck_read(dev_priv, reg);
163         mutex_unlock(&dev_priv->sb_lock);
164
165         divider = val & CCK_FREQUENCY_VALUES;
166
167         WARN((val & CCK_FREQUENCY_STATUS) !=
168              (divider << CCK_FREQUENCY_STATUS_SHIFT),
169              "%s change in progress\n", name);
170
171         return DIV_ROUND_CLOSEST(dev_priv->hpll_freq << 1, divider + 1);
172 }
173
174 int
175 intel_pch_rawclk(struct drm_device *dev)
176 {
177         struct drm_i915_private *dev_priv = dev->dev_private;
178
179         WARN_ON(!HAS_PCH_SPLIT(dev));
180
181         return I915_READ(PCH_RAWCLK_FREQ) & RAWCLK_FREQ_MASK;
182 }
183
184 /* hrawclock is 1/4 the FSB frequency */
185 int intel_hrawclk(struct drm_device *dev)
186 {
187         struct drm_i915_private *dev_priv = dev->dev_private;
188         uint32_t clkcfg;
189
190         /* There is no CLKCFG reg in Valleyview. VLV hrawclk is 200 MHz */
191         if (IS_VALLEYVIEW(dev) || IS_CHERRYVIEW(dev))
192                 return 200;
193
194         clkcfg = I915_READ(CLKCFG);
195         switch (clkcfg & CLKCFG_FSB_MASK) {
196         case CLKCFG_FSB_400:
197                 return 100;
198         case CLKCFG_FSB_533:
199                 return 133;
200         case CLKCFG_FSB_667:
201                 return 166;
202         case CLKCFG_FSB_800:
203                 return 200;
204         case CLKCFG_FSB_1067:
205                 return 266;
206         case CLKCFG_FSB_1333:
207                 return 333;
208         /* these two are just a guess; one of them might be right */
209         case CLKCFG_FSB_1600:
210         case CLKCFG_FSB_1600_ALT:
211                 return 400;
212         default:
213                 return 133;
214         }
215 }
216
217 static void intel_update_czclk(struct drm_i915_private *dev_priv)
218 {
219         if (!(IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv)))
220                 return;
221
222         dev_priv->czclk_freq = vlv_get_cck_clock_hpll(dev_priv, "czclk",
223                                                       CCK_CZ_CLOCK_CONTROL);
224
225         DRM_DEBUG_DRIVER("CZ clock rate: %d kHz\n", dev_priv->czclk_freq);
226 }
227
228 static inline u32 /* units of 100MHz */
229 intel_fdi_link_freq(struct drm_device *dev)
230 {
231         if (IS_GEN5(dev)) {
232                 struct drm_i915_private *dev_priv = dev->dev_private;
233                 return (I915_READ(FDI_PLL_BIOS_0) & FDI_PLL_FB_CLOCK_MASK) + 2;
234         } else
235                 return 27;
236 }
237
238 static const intel_limit_t intel_limits_i8xx_dac = {
239         .dot = { .min = 25000, .max = 350000 },
240         .vco = { .min = 908000, .max = 1512000 },
241         .n = { .min = 2, .max = 16 },
242         .m = { .min = 96, .max = 140 },
243         .m1 = { .min = 18, .max = 26 },
244         .m2 = { .min = 6, .max = 16 },
245         .p = { .min = 4, .max = 128 },
246         .p1 = { .min = 2, .max = 33 },
247         .p2 = { .dot_limit = 165000,
248                 .p2_slow = 4, .p2_fast = 2 },
249 };
250
251 static const intel_limit_t intel_limits_i8xx_dvo = {
252         .dot = { .min = 25000, .max = 350000 },
253         .vco = { .min = 908000, .max = 1512000 },
254         .n = { .min = 2, .max = 16 },
255         .m = { .min = 96, .max = 140 },
256         .m1 = { .min = 18, .max = 26 },
257         .m2 = { .min = 6, .max = 16 },
258         .p = { .min = 4, .max = 128 },
259         .p1 = { .min = 2, .max = 33 },
260         .p2 = { .dot_limit = 165000,
261                 .p2_slow = 4, .p2_fast = 4 },
262 };
263
264 static const intel_limit_t intel_limits_i8xx_lvds = {
265         .dot = { .min = 25000, .max = 350000 },
266         .vco = { .min = 908000, .max = 1512000 },
267         .n = { .min = 2, .max = 16 },
268         .m = { .min = 96, .max = 140 },
269         .m1 = { .min = 18, .max = 26 },
270         .m2 = { .min = 6, .max = 16 },
271         .p = { .min = 4, .max = 128 },
272         .p1 = { .min = 1, .max = 6 },
273         .p2 = { .dot_limit = 165000,
274                 .p2_slow = 14, .p2_fast = 7 },
275 };
276
277 static const intel_limit_t intel_limits_i9xx_sdvo = {
278         .dot = { .min = 20000, .max = 400000 },
279         .vco = { .min = 1400000, .max = 2800000 },
280         .n = { .min = 1, .max = 6 },
281         .m = { .min = 70, .max = 120 },
282         .m1 = { .min = 8, .max = 18 },
283         .m2 = { .min = 3, .max = 7 },
284         .p = { .min = 5, .max = 80 },
285         .p1 = { .min = 1, .max = 8 },
286         .p2 = { .dot_limit = 200000,
287                 .p2_slow = 10, .p2_fast = 5 },
288 };
289
290 static const intel_limit_t intel_limits_i9xx_lvds = {
291         .dot = { .min = 20000, .max = 400000 },
292         .vco = { .min = 1400000, .max = 2800000 },
293         .n = { .min = 1, .max = 6 },
294         .m = { .min = 70, .max = 120 },
295         .m1 = { .min = 8, .max = 18 },
296         .m2 = { .min = 3, .max = 7 },
297         .p = { .min = 7, .max = 98 },
298         .p1 = { .min = 1, .max = 8 },
299         .p2 = { .dot_limit = 112000,
300                 .p2_slow = 14, .p2_fast = 7 },
301 };
302
303
304 static const intel_limit_t intel_limits_g4x_sdvo = {
305         .dot = { .min = 25000, .max = 270000 },
306         .vco = { .min = 1750000, .max = 3500000},
307         .n = { .min = 1, .max = 4 },
308         .m = { .min = 104, .max = 138 },
309         .m1 = { .min = 17, .max = 23 },
310         .m2 = { .min = 5, .max = 11 },
311         .p = { .min = 10, .max = 30 },
312         .p1 = { .min = 1, .max = 3},
313         .p2 = { .dot_limit = 270000,
314                 .p2_slow = 10,
315                 .p2_fast = 10
316         },
317 };
318
319 static const intel_limit_t intel_limits_g4x_hdmi = {
320         .dot = { .min = 22000, .max = 400000 },
321         .vco = { .min = 1750000, .max = 3500000},
322         .n = { .min = 1, .max = 4 },
323         .m = { .min = 104, .max = 138 },
324         .m1 = { .min = 16, .max = 23 },
325         .m2 = { .min = 5, .max = 11 },
326         .p = { .min = 5, .max = 80 },
327         .p1 = { .min = 1, .max = 8},
328         .p2 = { .dot_limit = 165000,
329                 .p2_slow = 10, .p2_fast = 5 },
330 };
331
332 static const intel_limit_t intel_limits_g4x_single_channel_lvds = {
333         .dot = { .min = 20000, .max = 115000 },
334         .vco = { .min = 1750000, .max = 3500000 },
335         .n = { .min = 1, .max = 3 },
336         .m = { .min = 104, .max = 138 },
337         .m1 = { .min = 17, .max = 23 },
338         .m2 = { .min = 5, .max = 11 },
339         .p = { .min = 28, .max = 112 },
340         .p1 = { .min = 2, .max = 8 },
341         .p2 = { .dot_limit = 0,
342                 .p2_slow = 14, .p2_fast = 14
343         },
344 };
345
346 static const intel_limit_t intel_limits_g4x_dual_channel_lvds = {
347         .dot = { .min = 80000, .max = 224000 },
348         .vco = { .min = 1750000, .max = 3500000 },
349         .n = { .min = 1, .max = 3 },
350         .m = { .min = 104, .max = 138 },
351         .m1 = { .min = 17, .max = 23 },
352         .m2 = { .min = 5, .max = 11 },
353         .p = { .min = 14, .max = 42 },
354         .p1 = { .min = 2, .max = 6 },
355         .p2 = { .dot_limit = 0,
356                 .p2_slow = 7, .p2_fast = 7
357         },
358 };
359
360 static const intel_limit_t intel_limits_pineview_sdvo = {
361         .dot = { .min = 20000, .max = 400000},
362         .vco = { .min = 1700000, .max = 3500000 },
363         /* Pineview's Ncounter is a ring counter */
364         .n = { .min = 3, .max = 6 },
365         .m = { .min = 2, .max = 256 },
366         /* Pineview only has one combined m divider, which we treat as m2. */
367         .m1 = { .min = 0, .max = 0 },
368         .m2 = { .min = 0, .max = 254 },
369         .p = { .min = 5, .max = 80 },
370         .p1 = { .min = 1, .max = 8 },
371         .p2 = { .dot_limit = 200000,
372                 .p2_slow = 10, .p2_fast = 5 },
373 };
374
375 static const intel_limit_t intel_limits_pineview_lvds = {
376         .dot = { .min = 20000, .max = 400000 },
377         .vco = { .min = 1700000, .max = 3500000 },
378         .n = { .min = 3, .max = 6 },
379         .m = { .min = 2, .max = 256 },
380         .m1 = { .min = 0, .max = 0 },
381         .m2 = { .min = 0, .max = 254 },
382         .p = { .min = 7, .max = 112 },
383         .p1 = { .min = 1, .max = 8 },
384         .p2 = { .dot_limit = 112000,
385                 .p2_slow = 14, .p2_fast = 14 },
386 };
387
388 /* Ironlake / Sandybridge
389  *
390  * We calculate clock using (register_value + 2) for N/M1/M2, so here
391  * the range value for them is (actual_value - 2).
392  */
393 static const intel_limit_t intel_limits_ironlake_dac = {
394         .dot = { .min = 25000, .max = 350000 },
395         .vco = { .min = 1760000, .max = 3510000 },
396         .n = { .min = 1, .max = 5 },
397         .m = { .min = 79, .max = 127 },
398         .m1 = { .min = 12, .max = 22 },
399         .m2 = { .min = 5, .max = 9 },
400         .p = { .min = 5, .max = 80 },
401         .p1 = { .min = 1, .max = 8 },
402         .p2 = { .dot_limit = 225000,
403                 .p2_slow = 10, .p2_fast = 5 },
404 };
405
406 static const intel_limit_t intel_limits_ironlake_single_lvds = {
407         .dot = { .min = 25000, .max = 350000 },
408         .vco = { .min = 1760000, .max = 3510000 },
409         .n = { .min = 1, .max = 3 },
410         .m = { .min = 79, .max = 118 },
411         .m1 = { .min = 12, .max = 22 },
412         .m2 = { .min = 5, .max = 9 },
413         .p = { .min = 28, .max = 112 },
414         .p1 = { .min = 2, .max = 8 },
415         .p2 = { .dot_limit = 225000,
416                 .p2_slow = 14, .p2_fast = 14 },
417 };
418
419 static const intel_limit_t intel_limits_ironlake_dual_lvds = {
420         .dot = { .min = 25000, .max = 350000 },
421         .vco = { .min = 1760000, .max = 3510000 },
422         .n = { .min = 1, .max = 3 },
423         .m = { .min = 79, .max = 127 },
424         .m1 = { .min = 12, .max = 22 },
425         .m2 = { .min = 5, .max = 9 },
426         .p = { .min = 14, .max = 56 },
427         .p1 = { .min = 2, .max = 8 },
428         .p2 = { .dot_limit = 225000,
429                 .p2_slow = 7, .p2_fast = 7 },
430 };
431
432 /* LVDS 100mhz refclk limits. */
433 static const intel_limit_t intel_limits_ironlake_single_lvds_100m = {
434         .dot = { .min = 25000, .max = 350000 },
435         .vco = { .min = 1760000, .max = 3510000 },
436         .n = { .min = 1, .max = 2 },
437         .m = { .min = 79, .max = 126 },
438         .m1 = { .min = 12, .max = 22 },
439         .m2 = { .min = 5, .max = 9 },
440         .p = { .min = 28, .max = 112 },
441         .p1 = { .min = 2, .max = 8 },
442         .p2 = { .dot_limit = 225000,
443                 .p2_slow = 14, .p2_fast = 14 },
444 };
445
446 static const intel_limit_t intel_limits_ironlake_dual_lvds_100m = {
447         .dot = { .min = 25000, .max = 350000 },
448         .vco = { .min = 1760000, .max = 3510000 },
449         .n = { .min = 1, .max = 3 },
450         .m = { .min = 79, .max = 126 },
451         .m1 = { .min = 12, .max = 22 },
452         .m2 = { .min = 5, .max = 9 },
453         .p = { .min = 14, .max = 42 },
454         .p1 = { .min = 2, .max = 6 },
455         .p2 = { .dot_limit = 225000,
456                 .p2_slow = 7, .p2_fast = 7 },
457 };
458
459 static const intel_limit_t intel_limits_vlv = {
460          /*
461           * These are the data rate limits (measured in fast clocks)
462           * since those are the strictest limits we have. The fast
463           * clock and actual rate limits are more relaxed, so checking
464           * them would make no difference.
465           */
466         .dot = { .min = 25000 * 5, .max = 270000 * 5 },
467         .vco = { .min = 4000000, .max = 6000000 },
468         .n = { .min = 1, .max = 7 },
469         .m1 = { .min = 2, .max = 3 },
470         .m2 = { .min = 11, .max = 156 },
471         .p1 = { .min = 2, .max = 3 },
472         .p2 = { .p2_slow = 2, .p2_fast = 20 }, /* slow=min, fast=max */
473 };
474
475 static const intel_limit_t intel_limits_chv = {
476         /*
477          * These are the data rate limits (measured in fast clocks)
478          * since those are the strictest limits we have.  The fast
479          * clock and actual rate limits are more relaxed, so checking
480          * them would make no difference.
481          */
482         .dot = { .min = 25000 * 5, .max = 540000 * 5},
483         .vco = { .min = 4800000, .max = 6480000 },
484         .n = { .min = 1, .max = 1 },
485         .m1 = { .min = 2, .max = 2 },
486         .m2 = { .min = 24 << 22, .max = 175 << 22 },
487         .p1 = { .min = 2, .max = 4 },
488         .p2 = { .p2_slow = 1, .p2_fast = 14 },
489 };
490
491 static const intel_limit_t intel_limits_bxt = {
492         /* FIXME: find real dot limits */
493         .dot = { .min = 0, .max = INT_MAX },
494         .vco = { .min = 4800000, .max = 6700000 },
495         .n = { .min = 1, .max = 1 },
496         .m1 = { .min = 2, .max = 2 },
497         /* FIXME: find real m2 limits */
498         .m2 = { .min = 2 << 22, .max = 255 << 22 },
499         .p1 = { .min = 2, .max = 4 },
500         .p2 = { .p2_slow = 1, .p2_fast = 20 },
501 };
502
503 static bool
504 needs_modeset(struct drm_crtc_state *state)
505 {
506         return drm_atomic_crtc_needs_modeset(state);
507 }
508
509 /**
510  * Returns whether any output on the specified pipe is of the specified type
511  */
512 bool intel_pipe_has_type(struct intel_crtc *crtc, enum intel_output_type type)
513 {
514         struct drm_device *dev = crtc->base.dev;
515         struct intel_encoder *encoder;
516
517         for_each_encoder_on_crtc(dev, &crtc->base, encoder)
518                 if (encoder->type == type)
519                         return true;
520
521         return false;
522 }
523
524 /**
525  * Returns whether any output on the specified pipe will have the specified
526  * type after a staged modeset is complete, i.e., the same as
527  * intel_pipe_has_type() but looking at encoder->new_crtc instead of
528  * encoder->crtc.
529  */
530 static bool intel_pipe_will_have_type(const struct intel_crtc_state *crtc_state,
531                                       int type)
532 {
533         struct drm_atomic_state *state = crtc_state->base.state;
534         struct drm_connector *connector;
535         struct drm_connector_state *connector_state;
536         struct intel_encoder *encoder;
537         int i, num_connectors = 0;
538
539         for_each_connector_in_state(state, connector, connector_state, i) {
540                 if (connector_state->crtc != crtc_state->base.crtc)
541                         continue;
542
543                 num_connectors++;
544
545                 encoder = to_intel_encoder(connector_state->best_encoder);
546                 if (encoder->type == type)
547                         return true;
548         }
549
550         WARN_ON(num_connectors == 0);
551
552         return false;
553 }
554
555 static const intel_limit_t *
556 intel_ironlake_limit(struct intel_crtc_state *crtc_state, int refclk)
557 {
558         struct drm_device *dev = crtc_state->base.crtc->dev;
559         const intel_limit_t *limit;
560
561         if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_LVDS)) {
562                 if (intel_is_dual_link_lvds(dev)) {
563                         if (refclk == 100000)
564                                 limit = &intel_limits_ironlake_dual_lvds_100m;
565                         else
566                                 limit = &intel_limits_ironlake_dual_lvds;
567                 } else {
568                         if (refclk == 100000)
569                                 limit = &intel_limits_ironlake_single_lvds_100m;
570                         else
571                                 limit = &intel_limits_ironlake_single_lvds;
572                 }
573         } else
574                 limit = &intel_limits_ironlake_dac;
575
576         return limit;
577 }
578
579 static const intel_limit_t *
580 intel_g4x_limit(struct intel_crtc_state *crtc_state)
581 {
582         struct drm_device *dev = crtc_state->base.crtc->dev;
583         const intel_limit_t *limit;
584
585         if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_LVDS)) {
586                 if (intel_is_dual_link_lvds(dev))
587                         limit = &intel_limits_g4x_dual_channel_lvds;
588                 else
589                         limit = &intel_limits_g4x_single_channel_lvds;
590         } else if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_HDMI) ||
591                    intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_ANALOG)) {
592                 limit = &intel_limits_g4x_hdmi;
593         } else if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_SDVO)) {
594                 limit = &intel_limits_g4x_sdvo;
595         } else /* The option is for other outputs */
596                 limit = &intel_limits_i9xx_sdvo;
597
598         return limit;
599 }
600
601 static const intel_limit_t *
602 intel_limit(struct intel_crtc_state *crtc_state, int refclk)
603 {
604         struct drm_device *dev = crtc_state->base.crtc->dev;
605         const intel_limit_t *limit;
606
607         if (IS_BROXTON(dev))
608                 limit = &intel_limits_bxt;
609         else if (HAS_PCH_SPLIT(dev))
610                 limit = intel_ironlake_limit(crtc_state, refclk);
611         else if (IS_G4X(dev)) {
612                 limit = intel_g4x_limit(crtc_state);
613         } else if (IS_PINEVIEW(dev)) {
614                 if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_LVDS))
615                         limit = &intel_limits_pineview_lvds;
616                 else
617                         limit = &intel_limits_pineview_sdvo;
618         } else if (IS_CHERRYVIEW(dev)) {
619                 limit = &intel_limits_chv;
620         } else if (IS_VALLEYVIEW(dev)) {
621                 limit = &intel_limits_vlv;
622         } else if (!IS_GEN2(dev)) {
623                 if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_LVDS))
624                         limit = &intel_limits_i9xx_lvds;
625                 else
626                         limit = &intel_limits_i9xx_sdvo;
627         } else {
628                 if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_LVDS))
629                         limit = &intel_limits_i8xx_lvds;
630                 else if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_DVO))
631                         limit = &intel_limits_i8xx_dvo;
632                 else
633                         limit = &intel_limits_i8xx_dac;
634         }
635         return limit;
636 }
637
638 /*
639  * Platform specific helpers to calculate the port PLL loopback- (clock.m),
640  * and post-divider (clock.p) values, pre- (clock.vco) and post-divided fast
641  * (clock.dot) clock rates. This fast dot clock is fed to the port's IO logic.
642  * The helpers' return value is the rate of the clock that is fed to the
643  * display engine's pipe which can be the above fast dot clock rate or a
644  * divided-down version of it.
645  */
646 /* m1 is reserved as 0 in Pineview, n is a ring counter */
647 static int pnv_calc_dpll_params(int refclk, intel_clock_t *clock)
648 {
649         clock->m = clock->m2 + 2;
650         clock->p = clock->p1 * clock->p2;
651         if (WARN_ON(clock->n == 0 || clock->p == 0))
652                 return 0;
653         clock->vco = DIV_ROUND_CLOSEST(refclk * clock->m, clock->n);
654         clock->dot = DIV_ROUND_CLOSEST(clock->vco, clock->p);
655
656         return clock->dot;
657 }
658
659 static uint32_t i9xx_dpll_compute_m(struct dpll *dpll)
660 {
661         return 5 * (dpll->m1 + 2) + (dpll->m2 + 2);
662 }
663
664 static int i9xx_calc_dpll_params(int refclk, intel_clock_t *clock)
665 {
666         clock->m = i9xx_dpll_compute_m(clock);
667         clock->p = clock->p1 * clock->p2;
668         if (WARN_ON(clock->n + 2 == 0 || clock->p == 0))
669                 return 0;
670         clock->vco = DIV_ROUND_CLOSEST(refclk * clock->m, clock->n + 2);
671         clock->dot = DIV_ROUND_CLOSEST(clock->vco, clock->p);
672
673         return clock->dot;
674 }
675
676 static int vlv_calc_dpll_params(int refclk, intel_clock_t *clock)
677 {
678         clock->m = clock->m1 * clock->m2;
679         clock->p = clock->p1 * clock->p2;
680         if (WARN_ON(clock->n == 0 || clock->p == 0))
681                 return 0;
682         clock->vco = DIV_ROUND_CLOSEST(refclk * clock->m, clock->n);
683         clock->dot = DIV_ROUND_CLOSEST(clock->vco, clock->p);
684
685         return clock->dot / 5;
686 }
687
688 int chv_calc_dpll_params(int refclk, intel_clock_t *clock)
689 {
690         clock->m = clock->m1 * clock->m2;
691         clock->p = clock->p1 * clock->p2;
692         if (WARN_ON(clock->n == 0 || clock->p == 0))
693                 return 0;
694         clock->vco = DIV_ROUND_CLOSEST_ULL((uint64_t)refclk * clock->m,
695                         clock->n << 22);
696         clock->dot = DIV_ROUND_CLOSEST(clock->vco, clock->p);
697
698         return clock->dot / 5;
699 }
700
701 #define INTELPllInvalid(s)   do { /* DRM_DEBUG(s); */ return false; } while (0)
702 /**
703  * Returns whether the given set of divisors are valid for a given refclk with
704  * the given connectors.
705  */
706
707 static bool intel_PLL_is_valid(struct drm_device *dev,
708                                const intel_limit_t *limit,
709                                const intel_clock_t *clock)
710 {
711         if (clock->n   < limit->n.min   || limit->n.max   < clock->n)
712                 INTELPllInvalid("n out of range\n");
713         if (clock->p1  < limit->p1.min  || limit->p1.max  < clock->p1)
714                 INTELPllInvalid("p1 out of range\n");
715         if (clock->m2  < limit->m2.min  || limit->m2.max  < clock->m2)
716                 INTELPllInvalid("m2 out of range\n");
717         if (clock->m1  < limit->m1.min  || limit->m1.max  < clock->m1)
718                 INTELPllInvalid("m1 out of range\n");
719
720         if (!IS_PINEVIEW(dev) && !IS_VALLEYVIEW(dev) &&
721             !IS_CHERRYVIEW(dev) && !IS_BROXTON(dev))
722                 if (clock->m1 <= clock->m2)
723                         INTELPllInvalid("m1 <= m2\n");
724
725         if (!IS_VALLEYVIEW(dev) && !IS_CHERRYVIEW(dev) && !IS_BROXTON(dev)) {
726                 if (clock->p < limit->p.min || limit->p.max < clock->p)
727                         INTELPllInvalid("p out of range\n");
728                 if (clock->m < limit->m.min || limit->m.max < clock->m)
729                         INTELPllInvalid("m out of range\n");
730         }
731
732         if (clock->vco < limit->vco.min || limit->vco.max < clock->vco)
733                 INTELPllInvalid("vco out of range\n");
734         /* XXX: We may need to be checking "Dot clock" depending on the multiplier,
735          * connector, etc., rather than just a single range.
736          */
737         if (clock->dot < limit->dot.min || limit->dot.max < clock->dot)
738                 INTELPllInvalid("dot out of range\n");
739
740         return true;
741 }
742
743 static int
744 i9xx_select_p2_div(const intel_limit_t *limit,
745                    const struct intel_crtc_state *crtc_state,
746                    int target)
747 {
748         struct drm_device *dev = crtc_state->base.crtc->dev;
749
750         if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_LVDS)) {
751                 /*
752                  * For LVDS just rely on its current settings for dual-channel.
753                  * We haven't figured out how to reliably set up different
754                  * single/dual channel state, if we even can.
755                  */
756                 if (intel_is_dual_link_lvds(dev))
757                         return limit->p2.p2_fast;
758                 else
759                         return limit->p2.p2_slow;
760         } else {
761                 if (target < limit->p2.dot_limit)
762                         return limit->p2.p2_slow;
763                 else
764                         return limit->p2.p2_fast;
765         }
766 }
767
768 static bool
769 i9xx_find_best_dpll(const intel_limit_t *limit,
770                     struct intel_crtc_state *crtc_state,
771                     int target, int refclk, intel_clock_t *match_clock,
772                     intel_clock_t *best_clock)
773 {
774         struct drm_device *dev = crtc_state->base.crtc->dev;
775         intel_clock_t clock;
776         int err = target;
777
778         memset(best_clock, 0, sizeof(*best_clock));
779
780         clock.p2 = i9xx_select_p2_div(limit, crtc_state, target);
781
782         for (clock.m1 = limit->m1.min; clock.m1 <= limit->m1.max;
783              clock.m1++) {
784                 for (clock.m2 = limit->m2.min;
785                      clock.m2 <= limit->m2.max; clock.m2++) {
786                         if (clock.m2 >= clock.m1)
787                                 break;
788                         for (clock.n = limit->n.min;
789                              clock.n <= limit->n.max; clock.n++) {
790                                 for (clock.p1 = limit->p1.min;
791                                         clock.p1 <= limit->p1.max; clock.p1++) {
792                                         int this_err;
793
794                                         i9xx_calc_dpll_params(refclk, &clock);
795                                         if (!intel_PLL_is_valid(dev, limit,
796                                                                 &clock))
797                                                 continue;
798                                         if (match_clock &&
799                                             clock.p != match_clock->p)
800                                                 continue;
801
802                                         this_err = abs(clock.dot - target);
803                                         if (this_err < err) {
804                                                 *best_clock = clock;
805                                                 err = this_err;
806                                         }
807                                 }
808                         }
809                 }
810         }
811
812         return (err != target);
813 }
814
815 static bool
816 pnv_find_best_dpll(const intel_limit_t *limit,
817                    struct intel_crtc_state *crtc_state,
818                    int target, int refclk, intel_clock_t *match_clock,
819                    intel_clock_t *best_clock)
820 {
821         struct drm_device *dev = crtc_state->base.crtc->dev;
822         intel_clock_t clock;
823         int err = target;
824
825         memset(best_clock, 0, sizeof(*best_clock));
826
827         clock.p2 = i9xx_select_p2_div(limit, crtc_state, target);
828
829         for (clock.m1 = limit->m1.min; clock.m1 <= limit->m1.max;
830              clock.m1++) {
831                 for (clock.m2 = limit->m2.min;
832                      clock.m2 <= limit->m2.max; clock.m2++) {
833                         for (clock.n = limit->n.min;
834                              clock.n <= limit->n.max; clock.n++) {
835                                 for (clock.p1 = limit->p1.min;
836                                         clock.p1 <= limit->p1.max; clock.p1++) {
837                                         int this_err;
838
839                                         pnv_calc_dpll_params(refclk, &clock);
840                                         if (!intel_PLL_is_valid(dev, limit,
841                                                                 &clock))
842                                                 continue;
843                                         if (match_clock &&
844                                             clock.p != match_clock->p)
845                                                 continue;
846
847                                         this_err = abs(clock.dot - target);
848                                         if (this_err < err) {
849                                                 *best_clock = clock;
850                                                 err = this_err;
851                                         }
852                                 }
853                         }
854                 }
855         }
856
857         return (err != target);
858 }
859
860 static bool
861 g4x_find_best_dpll(const intel_limit_t *limit,
862                    struct intel_crtc_state *crtc_state,
863                    int target, int refclk, intel_clock_t *match_clock,
864                    intel_clock_t *best_clock)
865 {
866         struct drm_device *dev = crtc_state->base.crtc->dev;
867         intel_clock_t clock;
868         int max_n;
869         bool found = false;
870         /* approximately equals target * 0.00585 */
871         int err_most = (target >> 8) + (target >> 9);
872
873         memset(best_clock, 0, sizeof(*best_clock));
874
875         clock.p2 = i9xx_select_p2_div(limit, crtc_state, target);
876
877         max_n = limit->n.max;
878         /* based on hardware requirement, prefer smaller n to precision */
879         for (clock.n = limit->n.min; clock.n <= max_n; clock.n++) {
880                 /* based on hardware requirement, prefere larger m1,m2 */
881                 for (clock.m1 = limit->m1.max;
882                      clock.m1 >= limit->m1.min; clock.m1--) {
883                         for (clock.m2 = limit->m2.max;
884                              clock.m2 >= limit->m2.min; clock.m2--) {
885                                 for (clock.p1 = limit->p1.max;
886                                      clock.p1 >= limit->p1.min; clock.p1--) {
887                                         int this_err;
888
889                                         i9xx_calc_dpll_params(refclk, &clock);
890                                         if (!intel_PLL_is_valid(dev, limit,
891                                                                 &clock))
892                                                 continue;
893
894                                         this_err = abs(clock.dot - target);
895                                         if (this_err < err_most) {
896                                                 *best_clock = clock;
897                                                 err_most = this_err;
898                                                 max_n = clock.n;
899                                                 found = true;
900                                         }
901                                 }
902                         }
903                 }
904         }
905         return found;
906 }
907
908 /*
909  * Check if the calculated PLL configuration is more optimal compared to the
910  * best configuration and error found so far. Return the calculated error.
911  */
912 static bool vlv_PLL_is_optimal(struct drm_device *dev, int target_freq,
913                                const intel_clock_t *calculated_clock,
914                                const intel_clock_t *best_clock,
915                                unsigned int best_error_ppm,
916                                unsigned int *error_ppm)
917 {
918         /*
919          * For CHV ignore the error and consider only the P value.
920          * Prefer a bigger P value based on HW requirements.
921          */
922         if (IS_CHERRYVIEW(dev)) {
923                 *error_ppm = 0;
924
925                 return calculated_clock->p > best_clock->p;
926         }
927
928         if (WARN_ON_ONCE(!target_freq))
929                 return false;
930
931         *error_ppm = div_u64(1000000ULL *
932                                 abs(target_freq - calculated_clock->dot),
933                              target_freq);
934         /*
935          * Prefer a better P value over a better (smaller) error if the error
936          * is small. Ensure this preference for future configurations too by
937          * setting the error to 0.
938          */
939         if (*error_ppm < 100 && calculated_clock->p > best_clock->p) {
940                 *error_ppm = 0;
941
942                 return true;
943         }
944
945         return *error_ppm + 10 < best_error_ppm;
946 }
947
948 static bool
949 vlv_find_best_dpll(const intel_limit_t *limit,
950                    struct intel_crtc_state *crtc_state,
951                    int target, int refclk, intel_clock_t *match_clock,
952                    intel_clock_t *best_clock)
953 {
954         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
955         struct drm_device *dev = crtc->base.dev;
956         intel_clock_t clock;
957         unsigned int bestppm = 1000000;
958         /* min update 19.2 MHz */
959         int max_n = min(limit->n.max, refclk / 19200);
960         bool found = false;
961
962         target *= 5; /* fast clock */
963
964         memset(best_clock, 0, sizeof(*best_clock));
965
966         /* based on hardware requirement, prefer smaller n to precision */
967         for (clock.n = limit->n.min; clock.n <= max_n; clock.n++) {
968                 for (clock.p1 = limit->p1.max; clock.p1 >= limit->p1.min; clock.p1--) {
969                         for (clock.p2 = limit->p2.p2_fast; clock.p2 >= limit->p2.p2_slow;
970                              clock.p2 -= clock.p2 > 10 ? 2 : 1) {
971                                 clock.p = clock.p1 * clock.p2;
972                                 /* based on hardware requirement, prefer bigger m1,m2 values */
973                                 for (clock.m1 = limit->m1.min; clock.m1 <= limit->m1.max; clock.m1++) {
974                                         unsigned int ppm;
975
976                                         clock.m2 = DIV_ROUND_CLOSEST(target * clock.p * clock.n,
977                                                                      refclk * clock.m1);
978
979                                         vlv_calc_dpll_params(refclk, &clock);
980
981                                         if (!intel_PLL_is_valid(dev, limit,
982                                                                 &clock))
983                                                 continue;
984
985                                         if (!vlv_PLL_is_optimal(dev, target,
986                                                                 &clock,
987                                                                 best_clock,
988                                                                 bestppm, &ppm))
989                                                 continue;
990
991                                         *best_clock = clock;
992                                         bestppm = ppm;
993                                         found = true;
994                                 }
995                         }
996                 }
997         }
998
999         return found;
1000 }
1001
1002 static bool
1003 chv_find_best_dpll(const intel_limit_t *limit,
1004                    struct intel_crtc_state *crtc_state,
1005                    int target, int refclk, intel_clock_t *match_clock,
1006                    intel_clock_t *best_clock)
1007 {
1008         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
1009         struct drm_device *dev = crtc->base.dev;
1010         unsigned int best_error_ppm;
1011         intel_clock_t clock;
1012         uint64_t m2;
1013         int found = false;
1014
1015         memset(best_clock, 0, sizeof(*best_clock));
1016         best_error_ppm = 1000000;
1017
1018         /*
1019          * Based on hardware doc, the n always set to 1, and m1 always
1020          * set to 2.  If requires to support 200Mhz refclk, we need to
1021          * revisit this because n may not 1 anymore.
1022          */
1023         clock.n = 1, clock.m1 = 2;
1024         target *= 5;    /* fast clock */
1025
1026         for (clock.p1 = limit->p1.max; clock.p1 >= limit->p1.min; clock.p1--) {
1027                 for (clock.p2 = limit->p2.p2_fast;
1028                                 clock.p2 >= limit->p2.p2_slow;
1029                                 clock.p2 -= clock.p2 > 10 ? 2 : 1) {
1030                         unsigned int error_ppm;
1031
1032                         clock.p = clock.p1 * clock.p2;
1033
1034                         m2 = DIV_ROUND_CLOSEST_ULL(((uint64_t)target * clock.p *
1035                                         clock.n) << 22, refclk * clock.m1);
1036
1037                         if (m2 > INT_MAX/clock.m1)
1038                                 continue;
1039
1040                         clock.m2 = m2;
1041
1042                         chv_calc_dpll_params(refclk, &clock);
1043
1044                         if (!intel_PLL_is_valid(dev, limit, &clock))
1045                                 continue;
1046
1047                         if (!vlv_PLL_is_optimal(dev, target, &clock, best_clock,
1048                                                 best_error_ppm, &error_ppm))
1049                                 continue;
1050
1051                         *best_clock = clock;
1052                         best_error_ppm = error_ppm;
1053                         found = true;
1054                 }
1055         }
1056
1057         return found;
1058 }
1059
1060 bool bxt_find_best_dpll(struct intel_crtc_state *crtc_state, int target_clock,
1061                         intel_clock_t *best_clock)
1062 {
1063         int refclk = i9xx_get_refclk(crtc_state, 0);
1064
1065         return chv_find_best_dpll(intel_limit(crtc_state, refclk), crtc_state,
1066                                   target_clock, refclk, NULL, best_clock);
1067 }
1068
1069 bool intel_crtc_active(struct drm_crtc *crtc)
1070 {
1071         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
1072
1073         /* Be paranoid as we can arrive here with only partial
1074          * state retrieved from the hardware during setup.
1075          *
1076          * We can ditch the adjusted_mode.crtc_clock check as soon
1077          * as Haswell has gained clock readout/fastboot support.
1078          *
1079          * We can ditch the crtc->primary->fb check as soon as we can
1080          * properly reconstruct framebuffers.
1081          *
1082          * FIXME: The intel_crtc->active here should be switched to
1083          * crtc->state->active once we have proper CRTC states wired up
1084          * for atomic.
1085          */
1086         return intel_crtc->active && crtc->primary->state->fb &&
1087                 intel_crtc->config->base.adjusted_mode.crtc_clock;
1088 }
1089
1090 enum transcoder intel_pipe_to_cpu_transcoder(struct drm_i915_private *dev_priv,
1091                                              enum pipe pipe)
1092 {
1093         struct drm_crtc *crtc = dev_priv->pipe_to_crtc_mapping[pipe];
1094         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
1095
1096         return intel_crtc->config->cpu_transcoder;
1097 }
1098
1099 static bool pipe_dsl_stopped(struct drm_device *dev, enum pipe pipe)
1100 {
1101         struct drm_i915_private *dev_priv = dev->dev_private;
1102         i915_reg_t reg = PIPEDSL(pipe);
1103         u32 line1, line2;
1104         u32 line_mask;
1105
1106         if (IS_GEN2(dev))
1107                 line_mask = DSL_LINEMASK_GEN2;
1108         else
1109                 line_mask = DSL_LINEMASK_GEN3;
1110
1111         line1 = I915_READ(reg) & line_mask;
1112         msleep(5);
1113         line2 = I915_READ(reg) & line_mask;
1114
1115         return line1 == line2;
1116 }
1117
1118 /*
1119  * intel_wait_for_pipe_off - wait for pipe to turn off
1120  * @crtc: crtc whose pipe to wait for
1121  *
1122  * After disabling a pipe, we can't wait for vblank in the usual way,
1123  * spinning on the vblank interrupt status bit, since we won't actually
1124  * see an interrupt when the pipe is disabled.
1125  *
1126  * On Gen4 and above:
1127  *   wait for the pipe register state bit to turn off
1128  *
1129  * Otherwise:
1130  *   wait for the display line value to settle (it usually
1131  *   ends up stopping at the start of the next frame).
1132  *
1133  */
1134 static void intel_wait_for_pipe_off(struct intel_crtc *crtc)
1135 {
1136         struct drm_device *dev = crtc->base.dev;
1137         struct drm_i915_private *dev_priv = dev->dev_private;
1138         enum transcoder cpu_transcoder = crtc->config->cpu_transcoder;
1139         enum pipe pipe = crtc->pipe;
1140
1141         if (INTEL_INFO(dev)->gen >= 4) {
1142                 i915_reg_t reg = PIPECONF(cpu_transcoder);
1143
1144                 /* Wait for the Pipe State to go off */
1145                 if (wait_for((I915_READ(reg) & I965_PIPECONF_ACTIVE) == 0,
1146                              100))
1147                         WARN(1, "pipe_off wait timed out\n");
1148         } else {
1149                 /* Wait for the display line to settle */
1150                 if (wait_for(pipe_dsl_stopped(dev, pipe), 100))
1151                         WARN(1, "pipe_off wait timed out\n");
1152         }
1153 }
1154
1155 static const char *state_string(bool enabled)
1156 {
1157         return enabled ? "on" : "off";
1158 }
1159
1160 /* Only for pre-ILK configs */
1161 void assert_pll(struct drm_i915_private *dev_priv,
1162                 enum pipe pipe, bool state)
1163 {
1164         u32 val;
1165         bool cur_state;
1166
1167         val = I915_READ(DPLL(pipe));
1168         cur_state = !!(val & DPLL_VCO_ENABLE);
1169         I915_STATE_WARN(cur_state != state,
1170              "PLL state assertion failure (expected %s, current %s)\n",
1171              state_string(state), state_string(cur_state));
1172 }
1173
1174 /* XXX: the dsi pll is shared between MIPI DSI ports */
1175 static void assert_dsi_pll(struct drm_i915_private *dev_priv, bool state)
1176 {
1177         u32 val;
1178         bool cur_state;
1179
1180         mutex_lock(&dev_priv->sb_lock);
1181         val = vlv_cck_read(dev_priv, CCK_REG_DSI_PLL_CONTROL);
1182         mutex_unlock(&dev_priv->sb_lock);
1183
1184         cur_state = val & DSI_PLL_VCO_EN;
1185         I915_STATE_WARN(cur_state != state,
1186              "DSI PLL state assertion failure (expected %s, current %s)\n",
1187              state_string(state), state_string(cur_state));
1188 }
1189 #define assert_dsi_pll_enabled(d) assert_dsi_pll(d, true)
1190 #define assert_dsi_pll_disabled(d) assert_dsi_pll(d, false)
1191
1192 struct intel_shared_dpll *
1193 intel_crtc_to_shared_dpll(struct intel_crtc *crtc)
1194 {
1195         struct drm_i915_private *dev_priv = crtc->base.dev->dev_private;
1196
1197         if (crtc->config->shared_dpll < 0)
1198                 return NULL;
1199
1200         return &dev_priv->shared_dplls[crtc->config->shared_dpll];
1201 }
1202
1203 /* For ILK+ */
1204 void assert_shared_dpll(struct drm_i915_private *dev_priv,
1205                         struct intel_shared_dpll *pll,
1206                         bool state)
1207 {
1208         bool cur_state;
1209         struct intel_dpll_hw_state hw_state;
1210
1211         if (WARN (!pll,
1212                   "asserting DPLL %s with no DPLL\n", state_string(state)))
1213                 return;
1214
1215         cur_state = pll->get_hw_state(dev_priv, pll, &hw_state);
1216         I915_STATE_WARN(cur_state != state,
1217              "%s assertion failure (expected %s, current %s)\n",
1218              pll->name, state_string(state), state_string(cur_state));
1219 }
1220
1221 static void assert_fdi_tx(struct drm_i915_private *dev_priv,
1222                           enum pipe pipe, bool state)
1223 {
1224         bool cur_state;
1225         enum transcoder cpu_transcoder = intel_pipe_to_cpu_transcoder(dev_priv,
1226                                                                       pipe);
1227
1228         if (HAS_DDI(dev_priv->dev)) {
1229                 /* DDI does not have a specific FDI_TX register */
1230                 u32 val = I915_READ(TRANS_DDI_FUNC_CTL(cpu_transcoder));
1231                 cur_state = !!(val & TRANS_DDI_FUNC_ENABLE);
1232         } else {
1233                 u32 val = I915_READ(FDI_TX_CTL(pipe));
1234                 cur_state = !!(val & FDI_TX_ENABLE);
1235         }
1236         I915_STATE_WARN(cur_state != state,
1237              "FDI TX state assertion failure (expected %s, current %s)\n",
1238              state_string(state), state_string(cur_state));
1239 }
1240 #define assert_fdi_tx_enabled(d, p) assert_fdi_tx(d, p, true)
1241 #define assert_fdi_tx_disabled(d, p) assert_fdi_tx(d, p, false)
1242
1243 static void assert_fdi_rx(struct drm_i915_private *dev_priv,
1244                           enum pipe pipe, bool state)
1245 {
1246         u32 val;
1247         bool cur_state;
1248
1249         val = I915_READ(FDI_RX_CTL(pipe));
1250         cur_state = !!(val & FDI_RX_ENABLE);
1251         I915_STATE_WARN(cur_state != state,
1252              "FDI RX state assertion failure (expected %s, current %s)\n",
1253              state_string(state), state_string(cur_state));
1254 }
1255 #define assert_fdi_rx_enabled(d, p) assert_fdi_rx(d, p, true)
1256 #define assert_fdi_rx_disabled(d, p) assert_fdi_rx(d, p, false)
1257
1258 static void assert_fdi_tx_pll_enabled(struct drm_i915_private *dev_priv,
1259                                       enum pipe pipe)
1260 {
1261         u32 val;
1262
1263         /* ILK FDI PLL is always enabled */
1264         if (INTEL_INFO(dev_priv->dev)->gen == 5)
1265                 return;
1266
1267         /* On Haswell, DDI ports are responsible for the FDI PLL setup */
1268         if (HAS_DDI(dev_priv->dev))
1269                 return;
1270
1271         val = I915_READ(FDI_TX_CTL(pipe));
1272         I915_STATE_WARN(!(val & FDI_TX_PLL_ENABLE), "FDI TX PLL assertion failure, should be active but is disabled\n");
1273 }
1274
1275 void assert_fdi_rx_pll(struct drm_i915_private *dev_priv,
1276                        enum pipe pipe, bool state)
1277 {
1278         u32 val;
1279         bool cur_state;
1280
1281         val = I915_READ(FDI_RX_CTL(pipe));
1282         cur_state = !!(val & FDI_RX_PLL_ENABLE);
1283         I915_STATE_WARN(cur_state != state,
1284              "FDI RX PLL assertion failure (expected %s, current %s)\n",
1285              state_string(state), state_string(cur_state));
1286 }
1287
1288 void assert_panel_unlocked(struct drm_i915_private *dev_priv,
1289                            enum pipe pipe)
1290 {
1291         struct drm_device *dev = dev_priv->dev;
1292         i915_reg_t pp_reg;
1293         u32 val;
1294         enum pipe panel_pipe = PIPE_A;
1295         bool locked = true;
1296
1297         if (WARN_ON(HAS_DDI(dev)))
1298                 return;
1299
1300         if (HAS_PCH_SPLIT(dev)) {
1301                 u32 port_sel;
1302
1303                 pp_reg = PCH_PP_CONTROL;
1304                 port_sel = I915_READ(PCH_PP_ON_DELAYS) & PANEL_PORT_SELECT_MASK;
1305
1306                 if (port_sel == PANEL_PORT_SELECT_LVDS &&
1307                     I915_READ(PCH_LVDS) & LVDS_PIPEB_SELECT)
1308                         panel_pipe = PIPE_B;
1309                 /* XXX: else fix for eDP */
1310         } else if (IS_VALLEYVIEW(dev) || IS_CHERRYVIEW(dev)) {
1311                 /* presumably write lock depends on pipe, not port select */
1312                 pp_reg = VLV_PIPE_PP_CONTROL(pipe);
1313                 panel_pipe = pipe;
1314         } else {
1315                 pp_reg = PP_CONTROL;
1316                 if (I915_READ(LVDS) & LVDS_PIPEB_SELECT)
1317                         panel_pipe = PIPE_B;
1318         }
1319
1320         val = I915_READ(pp_reg);
1321         if (!(val & PANEL_POWER_ON) ||
1322             ((val & PANEL_UNLOCK_MASK) == PANEL_UNLOCK_REGS))
1323                 locked = false;
1324
1325         I915_STATE_WARN(panel_pipe == pipe && locked,
1326              "panel assertion failure, pipe %c regs locked\n",
1327              pipe_name(pipe));
1328 }
1329
1330 static void assert_cursor(struct drm_i915_private *dev_priv,
1331                           enum pipe pipe, bool state)
1332 {
1333         struct drm_device *dev = dev_priv->dev;
1334         bool cur_state;
1335
1336         if (IS_845G(dev) || IS_I865G(dev))
1337                 cur_state = I915_READ(CURCNTR(PIPE_A)) & CURSOR_ENABLE;
1338         else
1339                 cur_state = I915_READ(CURCNTR(pipe)) & CURSOR_MODE;
1340
1341         I915_STATE_WARN(cur_state != state,
1342              "cursor on pipe %c assertion failure (expected %s, current %s)\n",
1343              pipe_name(pipe), state_string(state), state_string(cur_state));
1344 }
1345 #define assert_cursor_enabled(d, p) assert_cursor(d, p, true)
1346 #define assert_cursor_disabled(d, p) assert_cursor(d, p, false)
1347
1348 void assert_pipe(struct drm_i915_private *dev_priv,
1349                  enum pipe pipe, bool state)
1350 {
1351         bool cur_state;
1352         enum transcoder cpu_transcoder = intel_pipe_to_cpu_transcoder(dev_priv,
1353                                                                       pipe);
1354
1355         /* if we need the pipe quirk it must be always on */
1356         if ((pipe == PIPE_A && dev_priv->quirks & QUIRK_PIPEA_FORCE) ||
1357             (pipe == PIPE_B && dev_priv->quirks & QUIRK_PIPEB_FORCE))
1358                 state = true;
1359
1360         if (!intel_display_power_is_enabled(dev_priv,
1361                                 POWER_DOMAIN_TRANSCODER(cpu_transcoder))) {
1362                 cur_state = false;
1363         } else {
1364                 u32 val = I915_READ(PIPECONF(cpu_transcoder));
1365                 cur_state = !!(val & PIPECONF_ENABLE);
1366         }
1367
1368         I915_STATE_WARN(cur_state != state,
1369              "pipe %c assertion failure (expected %s, current %s)\n",
1370              pipe_name(pipe), state_string(state), state_string(cur_state));
1371 }
1372
1373 static void assert_plane(struct drm_i915_private *dev_priv,
1374                          enum plane plane, bool state)
1375 {
1376         u32 val;
1377         bool cur_state;
1378
1379         val = I915_READ(DSPCNTR(plane));
1380         cur_state = !!(val & DISPLAY_PLANE_ENABLE);
1381         I915_STATE_WARN(cur_state != state,
1382              "plane %c assertion failure (expected %s, current %s)\n",
1383              plane_name(plane), state_string(state), state_string(cur_state));
1384 }
1385
1386 #define assert_plane_enabled(d, p) assert_plane(d, p, true)
1387 #define assert_plane_disabled(d, p) assert_plane(d, p, false)
1388
1389 static void assert_planes_disabled(struct drm_i915_private *dev_priv,
1390                                    enum pipe pipe)
1391 {
1392         struct drm_device *dev = dev_priv->dev;
1393         int i;
1394
1395         /* Primary planes are fixed to pipes on gen4+ */
1396         if (INTEL_INFO(dev)->gen >= 4) {
1397                 u32 val = I915_READ(DSPCNTR(pipe));
1398                 I915_STATE_WARN(val & DISPLAY_PLANE_ENABLE,
1399                      "plane %c assertion failure, should be disabled but not\n",
1400                      plane_name(pipe));
1401                 return;
1402         }
1403
1404         /* Need to check both planes against the pipe */
1405         for_each_pipe(dev_priv, i) {
1406                 u32 val = I915_READ(DSPCNTR(i));
1407                 enum pipe cur_pipe = (val & DISPPLANE_SEL_PIPE_MASK) >>
1408                         DISPPLANE_SEL_PIPE_SHIFT;
1409                 I915_STATE_WARN((val & DISPLAY_PLANE_ENABLE) && pipe == cur_pipe,
1410                      "plane %c assertion failure, should be off on pipe %c but is still active\n",
1411                      plane_name(i), pipe_name(pipe));
1412         }
1413 }
1414
1415 static void assert_sprites_disabled(struct drm_i915_private *dev_priv,
1416                                     enum pipe pipe)
1417 {
1418         struct drm_device *dev = dev_priv->dev;
1419         int sprite;
1420
1421         if (INTEL_INFO(dev)->gen >= 9) {
1422                 for_each_sprite(dev_priv, pipe, sprite) {
1423                         u32 val = I915_READ(PLANE_CTL(pipe, sprite));
1424                         I915_STATE_WARN(val & PLANE_CTL_ENABLE,
1425                              "plane %d assertion failure, should be off on pipe %c but is still active\n",
1426                              sprite, pipe_name(pipe));
1427                 }
1428         } else if (IS_VALLEYVIEW(dev) || IS_CHERRYVIEW(dev)) {
1429                 for_each_sprite(dev_priv, pipe, sprite) {
1430                         u32 val = I915_READ(SPCNTR(pipe, sprite));
1431                         I915_STATE_WARN(val & SP_ENABLE,
1432                              "sprite %c assertion failure, should be off on pipe %c but is still active\n",
1433                              sprite_name(pipe, sprite), pipe_name(pipe));
1434                 }
1435         } else if (INTEL_INFO(dev)->gen >= 7) {
1436                 u32 val = I915_READ(SPRCTL(pipe));
1437                 I915_STATE_WARN(val & SPRITE_ENABLE,
1438                      "sprite %c assertion failure, should be off on pipe %c but is still active\n",
1439                      plane_name(pipe), pipe_name(pipe));
1440         } else if (INTEL_INFO(dev)->gen >= 5) {
1441                 u32 val = I915_READ(DVSCNTR(pipe));
1442                 I915_STATE_WARN(val & DVS_ENABLE,
1443                      "sprite %c assertion failure, should be off on pipe %c but is still active\n",
1444                      plane_name(pipe), pipe_name(pipe));
1445         }
1446 }
1447
1448 static void assert_vblank_disabled(struct drm_crtc *crtc)
1449 {
1450         if (I915_STATE_WARN_ON(drm_crtc_vblank_get(crtc) == 0))
1451                 drm_crtc_vblank_put(crtc);
1452 }
1453
1454 static void ibx_assert_pch_refclk_enabled(struct drm_i915_private *dev_priv)
1455 {
1456         u32 val;
1457         bool enabled;
1458
1459         I915_STATE_WARN_ON(!(HAS_PCH_IBX(dev_priv->dev) || HAS_PCH_CPT(dev_priv->dev)));
1460
1461         val = I915_READ(PCH_DREF_CONTROL);
1462         enabled = !!(val & (DREF_SSC_SOURCE_MASK | DREF_NONSPREAD_SOURCE_MASK |
1463                             DREF_SUPERSPREAD_SOURCE_MASK));
1464         I915_STATE_WARN(!enabled, "PCH refclk assertion failure, should be active but is disabled\n");
1465 }
1466
1467 static void assert_pch_transcoder_disabled(struct drm_i915_private *dev_priv,
1468                                            enum pipe pipe)
1469 {
1470         u32 val;
1471         bool enabled;
1472
1473         val = I915_READ(PCH_TRANSCONF(pipe));
1474         enabled = !!(val & TRANS_ENABLE);
1475         I915_STATE_WARN(enabled,
1476              "transcoder assertion failed, should be off on pipe %c but is still active\n",
1477              pipe_name(pipe));
1478 }
1479
1480 static bool dp_pipe_enabled(struct drm_i915_private *dev_priv,
1481                             enum pipe pipe, u32 port_sel, u32 val)
1482 {
1483         if ((val & DP_PORT_EN) == 0)
1484                 return false;
1485
1486         if (HAS_PCH_CPT(dev_priv->dev)) {
1487                 u32 trans_dp_ctl = I915_READ(TRANS_DP_CTL(pipe));
1488                 if ((trans_dp_ctl & TRANS_DP_PORT_SEL_MASK) != port_sel)
1489                         return false;
1490         } else if (IS_CHERRYVIEW(dev_priv->dev)) {
1491                 if ((val & DP_PIPE_MASK_CHV) != DP_PIPE_SELECT_CHV(pipe))
1492                         return false;
1493         } else {
1494                 if ((val & DP_PIPE_MASK) != (pipe << 30))
1495                         return false;
1496         }
1497         return true;
1498 }
1499
1500 static bool hdmi_pipe_enabled(struct drm_i915_private *dev_priv,
1501                               enum pipe pipe, u32 val)
1502 {
1503         if ((val & SDVO_ENABLE) == 0)
1504                 return false;
1505
1506         if (HAS_PCH_CPT(dev_priv->dev)) {
1507                 if ((val & SDVO_PIPE_SEL_MASK_CPT) != SDVO_PIPE_SEL_CPT(pipe))
1508                         return false;
1509         } else if (IS_CHERRYVIEW(dev_priv->dev)) {
1510                 if ((val & SDVO_PIPE_SEL_MASK_CHV) != SDVO_PIPE_SEL_CHV(pipe))
1511                         return false;
1512         } else {
1513                 if ((val & SDVO_PIPE_SEL_MASK) != SDVO_PIPE_SEL(pipe))
1514                         return false;
1515         }
1516         return true;
1517 }
1518
1519 static bool lvds_pipe_enabled(struct drm_i915_private *dev_priv,
1520                               enum pipe pipe, u32 val)
1521 {
1522         if ((val & LVDS_PORT_EN) == 0)
1523                 return false;
1524
1525         if (HAS_PCH_CPT(dev_priv->dev)) {
1526                 if ((val & PORT_TRANS_SEL_MASK) != PORT_TRANS_SEL_CPT(pipe))
1527                         return false;
1528         } else {
1529                 if ((val & LVDS_PIPE_MASK) != LVDS_PIPE(pipe))
1530                         return false;
1531         }
1532         return true;
1533 }
1534
1535 static bool adpa_pipe_enabled(struct drm_i915_private *dev_priv,
1536                               enum pipe pipe, u32 val)
1537 {
1538         if ((val & ADPA_DAC_ENABLE) == 0)
1539                 return false;
1540         if (HAS_PCH_CPT(dev_priv->dev)) {
1541                 if ((val & PORT_TRANS_SEL_MASK) != PORT_TRANS_SEL_CPT(pipe))
1542                         return false;
1543         } else {
1544                 if ((val & ADPA_PIPE_SELECT_MASK) != ADPA_PIPE_SELECT(pipe))
1545                         return false;
1546         }
1547         return true;
1548 }
1549
1550 static void assert_pch_dp_disabled(struct drm_i915_private *dev_priv,
1551                                    enum pipe pipe, i915_reg_t reg,
1552                                    u32 port_sel)
1553 {
1554         u32 val = I915_READ(reg);
1555         I915_STATE_WARN(dp_pipe_enabled(dev_priv, pipe, port_sel, val),
1556              "PCH DP (0x%08x) enabled on transcoder %c, should be disabled\n",
1557              i915_mmio_reg_offset(reg), pipe_name(pipe));
1558
1559         I915_STATE_WARN(HAS_PCH_IBX(dev_priv->dev) && (val & DP_PORT_EN) == 0
1560              && (val & DP_PIPEB_SELECT),
1561              "IBX PCH dp port still using transcoder B\n");
1562 }
1563
1564 static void assert_pch_hdmi_disabled(struct drm_i915_private *dev_priv,
1565                                      enum pipe pipe, i915_reg_t reg)
1566 {
1567         u32 val = I915_READ(reg);
1568         I915_STATE_WARN(hdmi_pipe_enabled(dev_priv, pipe, val),
1569              "PCH HDMI (0x%08x) enabled on transcoder %c, should be disabled\n",
1570              i915_mmio_reg_offset(reg), pipe_name(pipe));
1571
1572         I915_STATE_WARN(HAS_PCH_IBX(dev_priv->dev) && (val & SDVO_ENABLE) == 0
1573              && (val & SDVO_PIPE_B_SELECT),
1574              "IBX PCH hdmi port still using transcoder B\n");
1575 }
1576
1577 static void assert_pch_ports_disabled(struct drm_i915_private *dev_priv,
1578                                       enum pipe pipe)
1579 {
1580         u32 val;
1581
1582         assert_pch_dp_disabled(dev_priv, pipe, PCH_DP_B, TRANS_DP_PORT_SEL_B);
1583         assert_pch_dp_disabled(dev_priv, pipe, PCH_DP_C, TRANS_DP_PORT_SEL_C);
1584         assert_pch_dp_disabled(dev_priv, pipe, PCH_DP_D, TRANS_DP_PORT_SEL_D);
1585
1586         val = I915_READ(PCH_ADPA);
1587         I915_STATE_WARN(adpa_pipe_enabled(dev_priv, pipe, val),
1588              "PCH VGA enabled on transcoder %c, should be disabled\n",
1589              pipe_name(pipe));
1590
1591         val = I915_READ(PCH_LVDS);
1592         I915_STATE_WARN(lvds_pipe_enabled(dev_priv, pipe, val),
1593              "PCH LVDS enabled on transcoder %c, should be disabled\n",
1594              pipe_name(pipe));
1595
1596         assert_pch_hdmi_disabled(dev_priv, pipe, PCH_HDMIB);
1597         assert_pch_hdmi_disabled(dev_priv, pipe, PCH_HDMIC);
1598         assert_pch_hdmi_disabled(dev_priv, pipe, PCH_HDMID);
1599 }
1600
1601 static void vlv_enable_pll(struct intel_crtc *crtc,
1602                            const struct intel_crtc_state *pipe_config)
1603 {
1604         struct drm_device *dev = crtc->base.dev;
1605         struct drm_i915_private *dev_priv = dev->dev_private;
1606         i915_reg_t reg = DPLL(crtc->pipe);
1607         u32 dpll = pipe_config->dpll_hw_state.dpll;
1608
1609         assert_pipe_disabled(dev_priv, crtc->pipe);
1610
1611         /* PLL is protected by panel, make sure we can write it */
1612         if (IS_MOBILE(dev_priv->dev))
1613                 assert_panel_unlocked(dev_priv, crtc->pipe);
1614
1615         I915_WRITE(reg, dpll);
1616         POSTING_READ(reg);
1617         udelay(150);
1618
1619         if (wait_for(((I915_READ(reg) & DPLL_LOCK_VLV) == DPLL_LOCK_VLV), 1))
1620                 DRM_ERROR("DPLL %d failed to lock\n", crtc->pipe);
1621
1622         I915_WRITE(DPLL_MD(crtc->pipe), pipe_config->dpll_hw_state.dpll_md);
1623         POSTING_READ(DPLL_MD(crtc->pipe));
1624
1625         /* We do this three times for luck */
1626         I915_WRITE(reg, dpll);
1627         POSTING_READ(reg);
1628         udelay(150); /* wait for warmup */
1629         I915_WRITE(reg, dpll);
1630         POSTING_READ(reg);
1631         udelay(150); /* wait for warmup */
1632         I915_WRITE(reg, dpll);
1633         POSTING_READ(reg);
1634         udelay(150); /* wait for warmup */
1635 }
1636
1637 static void chv_enable_pll(struct intel_crtc *crtc,
1638                            const struct intel_crtc_state *pipe_config)
1639 {
1640         struct drm_device *dev = crtc->base.dev;
1641         struct drm_i915_private *dev_priv = dev->dev_private;
1642         int pipe = crtc->pipe;
1643         enum dpio_channel port = vlv_pipe_to_channel(pipe);
1644         u32 tmp;
1645
1646         assert_pipe_disabled(dev_priv, crtc->pipe);
1647
1648         mutex_lock(&dev_priv->sb_lock);
1649
1650         /* Enable back the 10bit clock to display controller */
1651         tmp = vlv_dpio_read(dev_priv, pipe, CHV_CMN_DW14(port));
1652         tmp |= DPIO_DCLKP_EN;
1653         vlv_dpio_write(dev_priv, pipe, CHV_CMN_DW14(port), tmp);
1654
1655         mutex_unlock(&dev_priv->sb_lock);
1656
1657         /*
1658          * Need to wait > 100ns between dclkp clock enable bit and PLL enable.
1659          */
1660         udelay(1);
1661
1662         /* Enable PLL */
1663         I915_WRITE(DPLL(pipe), pipe_config->dpll_hw_state.dpll);
1664
1665         /* Check PLL is locked */
1666         if (wait_for(((I915_READ(DPLL(pipe)) & DPLL_LOCK_VLV) == DPLL_LOCK_VLV), 1))
1667                 DRM_ERROR("PLL %d failed to lock\n", pipe);
1668
1669         /* not sure when this should be written */
1670         I915_WRITE(DPLL_MD(pipe), pipe_config->dpll_hw_state.dpll_md);
1671         POSTING_READ(DPLL_MD(pipe));
1672 }
1673
1674 static int intel_num_dvo_pipes(struct drm_device *dev)
1675 {
1676         struct intel_crtc *crtc;
1677         int count = 0;
1678
1679         for_each_intel_crtc(dev, crtc)
1680                 count += crtc->base.state->active &&
1681                         intel_pipe_has_type(crtc, INTEL_OUTPUT_DVO);
1682
1683         return count;
1684 }
1685
1686 static void i9xx_enable_pll(struct intel_crtc *crtc)
1687 {
1688         struct drm_device *dev = crtc->base.dev;
1689         struct drm_i915_private *dev_priv = dev->dev_private;
1690         i915_reg_t reg = DPLL(crtc->pipe);
1691         u32 dpll = crtc->config->dpll_hw_state.dpll;
1692
1693         assert_pipe_disabled(dev_priv, crtc->pipe);
1694
1695         /* No really, not for ILK+ */
1696         BUG_ON(INTEL_INFO(dev)->gen >= 5);
1697
1698         /* PLL is protected by panel, make sure we can write it */
1699         if (IS_MOBILE(dev) && !IS_I830(dev))
1700                 assert_panel_unlocked(dev_priv, crtc->pipe);
1701
1702         /* Enable DVO 2x clock on both PLLs if necessary */
1703         if (IS_I830(dev) && intel_num_dvo_pipes(dev) > 0) {
1704                 /*
1705                  * It appears to be important that we don't enable this
1706                  * for the current pipe before otherwise configuring the
1707                  * PLL. No idea how this should be handled if multiple
1708                  * DVO outputs are enabled simultaneosly.
1709                  */
1710                 dpll |= DPLL_DVO_2X_MODE;
1711                 I915_WRITE(DPLL(!crtc->pipe),
1712                            I915_READ(DPLL(!crtc->pipe)) | DPLL_DVO_2X_MODE);
1713         }
1714
1715         /*
1716          * Apparently we need to have VGA mode enabled prior to changing
1717          * the P1/P2 dividers. Otherwise the DPLL will keep using the old
1718          * dividers, even though the register value does change.
1719          */
1720         I915_WRITE(reg, 0);
1721
1722         I915_WRITE(reg, dpll);
1723
1724         /* Wait for the clocks to stabilize. */
1725         POSTING_READ(reg);
1726         udelay(150);
1727
1728         if (INTEL_INFO(dev)->gen >= 4) {
1729                 I915_WRITE(DPLL_MD(crtc->pipe),
1730                            crtc->config->dpll_hw_state.dpll_md);
1731         } else {
1732                 /* The pixel multiplier can only be updated once the
1733                  * DPLL is enabled and the clocks are stable.
1734                  *
1735                  * So write it again.
1736                  */
1737                 I915_WRITE(reg, dpll);
1738         }
1739
1740         /* We do this three times for luck */
1741         I915_WRITE(reg, dpll);
1742         POSTING_READ(reg);
1743         udelay(150); /* wait for warmup */
1744         I915_WRITE(reg, dpll);
1745         POSTING_READ(reg);
1746         udelay(150); /* wait for warmup */
1747         I915_WRITE(reg, dpll);
1748         POSTING_READ(reg);
1749         udelay(150); /* wait for warmup */
1750 }
1751
1752 /**
1753  * i9xx_disable_pll - disable a PLL
1754  * @dev_priv: i915 private structure
1755  * @pipe: pipe PLL to disable
1756  *
1757  * Disable the PLL for @pipe, making sure the pipe is off first.
1758  *
1759  * Note!  This is for pre-ILK only.
1760  */
1761 static void i9xx_disable_pll(struct intel_crtc *crtc)
1762 {
1763         struct drm_device *dev = crtc->base.dev;
1764         struct drm_i915_private *dev_priv = dev->dev_private;
1765         enum pipe pipe = crtc->pipe;
1766
1767         /* Disable DVO 2x clock on both PLLs if necessary */
1768         if (IS_I830(dev) &&
1769             intel_pipe_has_type(crtc, INTEL_OUTPUT_DVO) &&
1770             !intel_num_dvo_pipes(dev)) {
1771                 I915_WRITE(DPLL(PIPE_B),
1772                            I915_READ(DPLL(PIPE_B)) & ~DPLL_DVO_2X_MODE);
1773                 I915_WRITE(DPLL(PIPE_A),
1774                            I915_READ(DPLL(PIPE_A)) & ~DPLL_DVO_2X_MODE);
1775         }
1776
1777         /* Don't disable pipe or pipe PLLs if needed */
1778         if ((pipe == PIPE_A && dev_priv->quirks & QUIRK_PIPEA_FORCE) ||
1779             (pipe == PIPE_B && dev_priv->quirks & QUIRK_PIPEB_FORCE))
1780                 return;
1781
1782         /* Make sure the pipe isn't still relying on us */
1783         assert_pipe_disabled(dev_priv, pipe);
1784
1785         I915_WRITE(DPLL(pipe), DPLL_VGA_MODE_DIS);
1786         POSTING_READ(DPLL(pipe));
1787 }
1788
1789 static void vlv_disable_pll(struct drm_i915_private *dev_priv, enum pipe pipe)
1790 {
1791         u32 val;
1792
1793         /* Make sure the pipe isn't still relying on us */
1794         assert_pipe_disabled(dev_priv, pipe);
1795
1796         /*
1797          * Leave integrated clock source and reference clock enabled for pipe B.
1798          * The latter is needed for VGA hotplug / manual detection.
1799          */
1800         val = DPLL_VGA_MODE_DIS;
1801         if (pipe == PIPE_B)
1802                 val = DPLL_INTEGRATED_CRI_CLK_VLV | DPLL_REF_CLK_ENABLE_VLV;
1803         I915_WRITE(DPLL(pipe), val);
1804         POSTING_READ(DPLL(pipe));
1805
1806 }
1807
1808 static void chv_disable_pll(struct drm_i915_private *dev_priv, enum pipe pipe)
1809 {
1810         enum dpio_channel port = vlv_pipe_to_channel(pipe);
1811         u32 val;
1812
1813         /* Make sure the pipe isn't still relying on us */
1814         assert_pipe_disabled(dev_priv, pipe);
1815
1816         /* Set PLL en = 0 */
1817         val = DPLL_SSC_REF_CLK_CHV |
1818                 DPLL_REF_CLK_ENABLE_VLV | DPLL_VGA_MODE_DIS;
1819         if (pipe != PIPE_A)
1820                 val |= DPLL_INTEGRATED_CRI_CLK_VLV;
1821         I915_WRITE(DPLL(pipe), val);
1822         POSTING_READ(DPLL(pipe));
1823
1824         mutex_lock(&dev_priv->sb_lock);
1825
1826         /* Disable 10bit clock to display controller */
1827         val = vlv_dpio_read(dev_priv, pipe, CHV_CMN_DW14(port));
1828         val &= ~DPIO_DCLKP_EN;
1829         vlv_dpio_write(dev_priv, pipe, CHV_CMN_DW14(port), val);
1830
1831         mutex_unlock(&dev_priv->sb_lock);
1832 }
1833
1834 void vlv_wait_port_ready(struct drm_i915_private *dev_priv,
1835                          struct intel_digital_port *dport,
1836                          unsigned int expected_mask)
1837 {
1838         u32 port_mask;
1839         i915_reg_t dpll_reg;
1840
1841         switch (dport->port) {
1842         case PORT_B:
1843                 port_mask = DPLL_PORTB_READY_MASK;
1844                 dpll_reg = DPLL(0);
1845                 break;
1846         case PORT_C:
1847                 port_mask = DPLL_PORTC_READY_MASK;
1848                 dpll_reg = DPLL(0);
1849                 expected_mask <<= 4;
1850                 break;
1851         case PORT_D:
1852                 port_mask = DPLL_PORTD_READY_MASK;
1853                 dpll_reg = DPIO_PHY_STATUS;
1854                 break;
1855         default:
1856                 BUG();
1857         }
1858
1859         if (wait_for((I915_READ(dpll_reg) & port_mask) == expected_mask, 1000))
1860                 WARN(1, "timed out waiting for port %c ready: got 0x%x, expected 0x%x\n",
1861                      port_name(dport->port), I915_READ(dpll_reg) & port_mask, expected_mask);
1862 }
1863
1864 static void intel_prepare_shared_dpll(struct intel_crtc *crtc)
1865 {
1866         struct drm_device *dev = crtc->base.dev;
1867         struct drm_i915_private *dev_priv = dev->dev_private;
1868         struct intel_shared_dpll *pll = intel_crtc_to_shared_dpll(crtc);
1869
1870         if (WARN_ON(pll == NULL))
1871                 return;
1872
1873         WARN_ON(!pll->config.crtc_mask);
1874         if (pll->active == 0) {
1875                 DRM_DEBUG_DRIVER("setting up %s\n", pll->name);
1876                 WARN_ON(pll->on);
1877                 assert_shared_dpll_disabled(dev_priv, pll);
1878
1879                 pll->mode_set(dev_priv, pll);
1880         }
1881 }
1882
1883 /**
1884  * intel_enable_shared_dpll - enable PCH PLL
1885  * @dev_priv: i915 private structure
1886  * @pipe: pipe PLL to enable
1887  *
1888  * The PCH PLL needs to be enabled before the PCH transcoder, since it
1889  * drives the transcoder clock.
1890  */
1891 static void intel_enable_shared_dpll(struct intel_crtc *crtc)
1892 {
1893         struct drm_device *dev = crtc->base.dev;
1894         struct drm_i915_private *dev_priv = dev->dev_private;
1895         struct intel_shared_dpll *pll = intel_crtc_to_shared_dpll(crtc);
1896
1897         if (WARN_ON(pll == NULL))
1898                 return;
1899
1900         if (WARN_ON(pll->config.crtc_mask == 0))
1901                 return;
1902
1903         DRM_DEBUG_KMS("enable %s (active %d, on? %d) for crtc %d\n",
1904                       pll->name, pll->active, pll->on,
1905                       crtc->base.base.id);
1906
1907         if (pll->active++) {
1908                 WARN_ON(!pll->on);
1909                 assert_shared_dpll_enabled(dev_priv, pll);
1910                 return;
1911         }
1912         WARN_ON(pll->on);
1913
1914         intel_display_power_get(dev_priv, POWER_DOMAIN_PLLS);
1915
1916         DRM_DEBUG_KMS("enabling %s\n", pll->name);
1917         pll->enable(dev_priv, pll);
1918         pll->on = true;
1919 }
1920
1921 static void intel_disable_shared_dpll(struct intel_crtc *crtc)
1922 {
1923         struct drm_device *dev = crtc->base.dev;
1924         struct drm_i915_private *dev_priv = dev->dev_private;
1925         struct intel_shared_dpll *pll = intel_crtc_to_shared_dpll(crtc);
1926
1927         /* PCH only available on ILK+ */
1928         if (INTEL_INFO(dev)->gen < 5)
1929                 return;
1930
1931         if (pll == NULL)
1932                 return;
1933
1934         if (WARN_ON(!(pll->config.crtc_mask & (1 << drm_crtc_index(&crtc->base)))))
1935                 return;
1936
1937         DRM_DEBUG_KMS("disable %s (active %d, on? %d) for crtc %d\n",
1938                       pll->name, pll->active, pll->on,
1939                       crtc->base.base.id);
1940
1941         if (WARN_ON(pll->active == 0)) {
1942                 assert_shared_dpll_disabled(dev_priv, pll);
1943                 return;
1944         }
1945
1946         assert_shared_dpll_enabled(dev_priv, pll);
1947         WARN_ON(!pll->on);
1948         if (--pll->active)
1949                 return;
1950
1951         DRM_DEBUG_KMS("disabling %s\n", pll->name);
1952         pll->disable(dev_priv, pll);
1953         pll->on = false;
1954
1955         intel_display_power_put(dev_priv, POWER_DOMAIN_PLLS);
1956 }
1957
1958 static void ironlake_enable_pch_transcoder(struct drm_i915_private *dev_priv,
1959                                            enum pipe pipe)
1960 {
1961         struct drm_device *dev = dev_priv->dev;
1962         struct drm_crtc *crtc = dev_priv->pipe_to_crtc_mapping[pipe];
1963         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
1964         i915_reg_t reg;
1965         uint32_t val, pipeconf_val;
1966
1967         /* PCH only available on ILK+ */
1968         BUG_ON(!HAS_PCH_SPLIT(dev));
1969
1970         /* Make sure PCH DPLL is enabled */
1971         assert_shared_dpll_enabled(dev_priv,
1972                                    intel_crtc_to_shared_dpll(intel_crtc));
1973
1974         /* FDI must be feeding us bits for PCH ports */
1975         assert_fdi_tx_enabled(dev_priv, pipe);
1976         assert_fdi_rx_enabled(dev_priv, pipe);
1977
1978         if (HAS_PCH_CPT(dev)) {
1979                 /* Workaround: Set the timing override bit before enabling the
1980                  * pch transcoder. */
1981                 reg = TRANS_CHICKEN2(pipe);
1982                 val = I915_READ(reg);
1983                 val |= TRANS_CHICKEN2_TIMING_OVERRIDE;
1984                 I915_WRITE(reg, val);
1985         }
1986
1987         reg = PCH_TRANSCONF(pipe);
1988         val = I915_READ(reg);
1989         pipeconf_val = I915_READ(PIPECONF(pipe));
1990
1991         if (HAS_PCH_IBX(dev_priv->dev)) {
1992                 /*
1993                  * Make the BPC in transcoder be consistent with
1994                  * that in pipeconf reg. For HDMI we must use 8bpc
1995                  * here for both 8bpc and 12bpc.
1996                  */
1997                 val &= ~PIPECONF_BPC_MASK;
1998                 if (intel_pipe_has_type(intel_crtc, INTEL_OUTPUT_HDMI))
1999                         val |= PIPECONF_8BPC;
2000                 else
2001                         val |= pipeconf_val & PIPECONF_BPC_MASK;
2002         }
2003
2004         val &= ~TRANS_INTERLACE_MASK;
2005         if ((pipeconf_val & PIPECONF_INTERLACE_MASK) == PIPECONF_INTERLACED_ILK)
2006                 if (HAS_PCH_IBX(dev_priv->dev) &&
2007                     intel_pipe_has_type(intel_crtc, INTEL_OUTPUT_SDVO))
2008                         val |= TRANS_LEGACY_INTERLACED_ILK;
2009                 else
2010                         val |= TRANS_INTERLACED;
2011         else
2012                 val |= TRANS_PROGRESSIVE;
2013
2014         I915_WRITE(reg, val | TRANS_ENABLE);
2015         if (wait_for(I915_READ(reg) & TRANS_STATE_ENABLE, 100))
2016                 DRM_ERROR("failed to enable transcoder %c\n", pipe_name(pipe));
2017 }
2018
2019 static void lpt_enable_pch_transcoder(struct drm_i915_private *dev_priv,
2020                                       enum transcoder cpu_transcoder)
2021 {
2022         u32 val, pipeconf_val;
2023
2024         /* PCH only available on ILK+ */
2025         BUG_ON(!HAS_PCH_SPLIT(dev_priv->dev));
2026
2027         /* FDI must be feeding us bits for PCH ports */
2028         assert_fdi_tx_enabled(dev_priv, (enum pipe) cpu_transcoder);
2029         assert_fdi_rx_enabled(dev_priv, TRANSCODER_A);
2030
2031         /* Workaround: set timing override bit. */
2032         val = I915_READ(TRANS_CHICKEN2(PIPE_A));
2033         val |= TRANS_CHICKEN2_TIMING_OVERRIDE;
2034         I915_WRITE(TRANS_CHICKEN2(PIPE_A), val);
2035
2036         val = TRANS_ENABLE;
2037         pipeconf_val = I915_READ(PIPECONF(cpu_transcoder));
2038
2039         if ((pipeconf_val & PIPECONF_INTERLACE_MASK_HSW) ==
2040             PIPECONF_INTERLACED_ILK)
2041                 val |= TRANS_INTERLACED;
2042         else
2043                 val |= TRANS_PROGRESSIVE;
2044
2045         I915_WRITE(LPT_TRANSCONF, val);
2046         if (wait_for(I915_READ(LPT_TRANSCONF) & TRANS_STATE_ENABLE, 100))
2047                 DRM_ERROR("Failed to enable PCH transcoder\n");
2048 }
2049
2050 static void ironlake_disable_pch_transcoder(struct drm_i915_private *dev_priv,
2051                                             enum pipe pipe)
2052 {
2053         struct drm_device *dev = dev_priv->dev;
2054         i915_reg_t reg;
2055         uint32_t val;
2056
2057         /* FDI relies on the transcoder */
2058         assert_fdi_tx_disabled(dev_priv, pipe);
2059         assert_fdi_rx_disabled(dev_priv, pipe);
2060
2061         /* Ports must be off as well */
2062         assert_pch_ports_disabled(dev_priv, pipe);
2063
2064         reg = PCH_TRANSCONF(pipe);
2065         val = I915_READ(reg);
2066         val &= ~TRANS_ENABLE;
2067         I915_WRITE(reg, val);
2068         /* wait for PCH transcoder off, transcoder state */
2069         if (wait_for((I915_READ(reg) & TRANS_STATE_ENABLE) == 0, 50))
2070                 DRM_ERROR("failed to disable transcoder %c\n", pipe_name(pipe));
2071
2072         if (HAS_PCH_CPT(dev)) {
2073                 /* Workaround: Clear the timing override chicken bit again. */
2074                 reg = TRANS_CHICKEN2(pipe);
2075                 val = I915_READ(reg);
2076                 val &= ~TRANS_CHICKEN2_TIMING_OVERRIDE;
2077                 I915_WRITE(reg, val);
2078         }
2079 }
2080
2081 static void lpt_disable_pch_transcoder(struct drm_i915_private *dev_priv)
2082 {
2083         u32 val;
2084
2085         val = I915_READ(LPT_TRANSCONF);
2086         val &= ~TRANS_ENABLE;
2087         I915_WRITE(LPT_TRANSCONF, val);
2088         /* wait for PCH transcoder off, transcoder state */
2089         if (wait_for((I915_READ(LPT_TRANSCONF) & TRANS_STATE_ENABLE) == 0, 50))
2090                 DRM_ERROR("Failed to disable PCH transcoder\n");
2091
2092         /* Workaround: clear timing override bit. */
2093         val = I915_READ(TRANS_CHICKEN2(PIPE_A));
2094         val &= ~TRANS_CHICKEN2_TIMING_OVERRIDE;
2095         I915_WRITE(TRANS_CHICKEN2(PIPE_A), val);
2096 }
2097
2098 /**
2099  * intel_enable_pipe - enable a pipe, asserting requirements
2100  * @crtc: crtc responsible for the pipe
2101  *
2102  * Enable @crtc's pipe, making sure that various hardware specific requirements
2103  * are met, if applicable, e.g. PLL enabled, LVDS pairs enabled, etc.
2104  */
2105 static void intel_enable_pipe(struct intel_crtc *crtc)
2106 {
2107         struct drm_device *dev = crtc->base.dev;
2108         struct drm_i915_private *dev_priv = dev->dev_private;
2109         enum pipe pipe = crtc->pipe;
2110         enum transcoder cpu_transcoder = crtc->config->cpu_transcoder;
2111         enum pipe pch_transcoder;
2112         i915_reg_t reg;
2113         u32 val;
2114
2115         DRM_DEBUG_KMS("enabling pipe %c\n", pipe_name(pipe));
2116
2117         assert_planes_disabled(dev_priv, pipe);
2118         assert_cursor_disabled(dev_priv, pipe);
2119         assert_sprites_disabled(dev_priv, pipe);
2120
2121         if (HAS_PCH_LPT(dev_priv->dev))
2122                 pch_transcoder = TRANSCODER_A;
2123         else
2124                 pch_transcoder = pipe;
2125
2126         /*
2127          * A pipe without a PLL won't actually be able to drive bits from
2128          * a plane.  On ILK+ the pipe PLLs are integrated, so we don't
2129          * need the check.
2130          */
2131         if (HAS_GMCH_DISPLAY(dev_priv->dev))
2132                 if (crtc->config->has_dsi_encoder)
2133                         assert_dsi_pll_enabled(dev_priv);
2134                 else
2135                         assert_pll_enabled(dev_priv, pipe);
2136         else {
2137                 if (crtc->config->has_pch_encoder) {
2138                         /* if driving the PCH, we need FDI enabled */
2139                         assert_fdi_rx_pll_enabled(dev_priv, pch_transcoder);
2140                         assert_fdi_tx_pll_enabled(dev_priv,
2141                                                   (enum pipe) cpu_transcoder);
2142                 }
2143                 /* FIXME: assert CPU port conditions for SNB+ */
2144         }
2145
2146         reg = PIPECONF(cpu_transcoder);
2147         val = I915_READ(reg);
2148         if (val & PIPECONF_ENABLE) {
2149                 WARN_ON(!((pipe == PIPE_A && dev_priv->quirks & QUIRK_PIPEA_FORCE) ||
2150                           (pipe == PIPE_B && dev_priv->quirks & QUIRK_PIPEB_FORCE)));
2151                 return;
2152         }
2153
2154         I915_WRITE(reg, val | PIPECONF_ENABLE);
2155         POSTING_READ(reg);
2156 }
2157
2158 /**
2159  * intel_disable_pipe - disable a pipe, asserting requirements
2160  * @crtc: crtc whose pipes is to be disabled
2161  *
2162  * Disable the pipe of @crtc, making sure that various hardware
2163  * specific requirements are met, if applicable, e.g. plane
2164  * disabled, panel fitter off, etc.
2165  *
2166  * Will wait until the pipe has shut down before returning.
2167  */
2168 static void intel_disable_pipe(struct intel_crtc *crtc)
2169 {
2170         struct drm_i915_private *dev_priv = crtc->base.dev->dev_private;
2171         enum transcoder cpu_transcoder = crtc->config->cpu_transcoder;
2172         enum pipe pipe = crtc->pipe;
2173         i915_reg_t reg;
2174         u32 val;
2175
2176         DRM_DEBUG_KMS("disabling pipe %c\n", pipe_name(pipe));
2177
2178         /*
2179          * Make sure planes won't keep trying to pump pixels to us,
2180          * or we might hang the display.
2181          */
2182         assert_planes_disabled(dev_priv, pipe);
2183         assert_cursor_disabled(dev_priv, pipe);
2184         assert_sprites_disabled(dev_priv, pipe);
2185
2186         reg = PIPECONF(cpu_transcoder);
2187         val = I915_READ(reg);
2188         if ((val & PIPECONF_ENABLE) == 0)
2189                 return;
2190
2191         /*
2192          * Double wide has implications for planes
2193          * so best keep it disabled when not needed.
2194          */
2195         if (crtc->config->double_wide)
2196                 val &= ~PIPECONF_DOUBLE_WIDE;
2197
2198         /* Don't disable pipe or pipe PLLs if needed */
2199         if (!(pipe == PIPE_A && dev_priv->quirks & QUIRK_PIPEA_FORCE) &&
2200             !(pipe == PIPE_B && dev_priv->quirks & QUIRK_PIPEB_FORCE))
2201                 val &= ~PIPECONF_ENABLE;
2202
2203         I915_WRITE(reg, val);
2204         if ((val & PIPECONF_ENABLE) == 0)
2205                 intel_wait_for_pipe_off(crtc);
2206 }
2207
2208 static bool need_vtd_wa(struct drm_device *dev)
2209 {
2210 #ifdef CONFIG_INTEL_IOMMU
2211         if (INTEL_INFO(dev)->gen >= 6 && intel_iommu_gfx_mapped)
2212                 return true;
2213 #endif
2214         return false;
2215 }
2216
2217 unsigned int
2218 intel_tile_height(struct drm_device *dev, uint32_t pixel_format,
2219                   uint64_t fb_format_modifier, unsigned int plane)
2220 {
2221         unsigned int tile_height;
2222         uint32_t pixel_bytes;
2223
2224         switch (fb_format_modifier) {
2225         case DRM_FORMAT_MOD_NONE:
2226                 tile_height = 1;
2227                 break;
2228         case I915_FORMAT_MOD_X_TILED:
2229                 tile_height = IS_GEN2(dev) ? 16 : 8;
2230                 break;
2231         case I915_FORMAT_MOD_Y_TILED:
2232                 tile_height = 32;
2233                 break;
2234         case I915_FORMAT_MOD_Yf_TILED:
2235                 pixel_bytes = drm_format_plane_cpp(pixel_format, plane);
2236                 switch (pixel_bytes) {
2237                 default:
2238                 case 1:
2239                         tile_height = 64;
2240                         break;
2241                 case 2:
2242                 case 4:
2243                         tile_height = 32;
2244                         break;
2245                 case 8:
2246                         tile_height = 16;
2247                         break;
2248                 case 16:
2249                         WARN_ONCE(1,
2250                                   "128-bit pixels are not supported for display!");
2251                         tile_height = 16;
2252                         break;
2253                 }
2254                 break;
2255         default:
2256                 MISSING_CASE(fb_format_modifier);
2257                 tile_height = 1;
2258                 break;
2259         }
2260
2261         return tile_height;
2262 }
2263
2264 unsigned int
2265 intel_fb_align_height(struct drm_device *dev, unsigned int height,
2266                       uint32_t pixel_format, uint64_t fb_format_modifier)
2267 {
2268         return ALIGN(height, intel_tile_height(dev, pixel_format,
2269                                                fb_format_modifier, 0));
2270 }
2271
2272 static void
2273 intel_fill_fb_ggtt_view(struct i915_ggtt_view *view, struct drm_framebuffer *fb,
2274                         const struct drm_plane_state *plane_state)
2275 {
2276         struct intel_rotation_info *info = &view->params.rotation_info;
2277         unsigned int tile_height, tile_pitch;
2278
2279         *view = i915_ggtt_view_normal;
2280
2281         if (!plane_state)
2282                 return;
2283
2284         if (!intel_rotation_90_or_270(plane_state->rotation))
2285                 return;
2286
2287         *view = i915_ggtt_view_rotated;
2288
2289         info->height = fb->height;
2290         info->pixel_format = fb->pixel_format;
2291         info->pitch = fb->pitches[0];
2292         info->uv_offset = fb->offsets[1];
2293         info->fb_modifier = fb->modifier[0];
2294
2295         tile_height = intel_tile_height(fb->dev, fb->pixel_format,
2296                                         fb->modifier[0], 0);
2297         tile_pitch = PAGE_SIZE / tile_height;
2298         info->width_pages = DIV_ROUND_UP(fb->pitches[0], tile_pitch);
2299         info->height_pages = DIV_ROUND_UP(fb->height, tile_height);
2300         info->size = info->width_pages * info->height_pages * PAGE_SIZE;
2301
2302         if (info->pixel_format == DRM_FORMAT_NV12) {
2303                 tile_height = intel_tile_height(fb->dev, fb->pixel_format,
2304                                                 fb->modifier[0], 1);
2305                 tile_pitch = PAGE_SIZE / tile_height;
2306                 info->width_pages_uv = DIV_ROUND_UP(fb->pitches[0], tile_pitch);
2307                 info->height_pages_uv = DIV_ROUND_UP(fb->height / 2,
2308                                                      tile_height);
2309                 info->size_uv = info->width_pages_uv * info->height_pages_uv *
2310                                 PAGE_SIZE;
2311         }
2312 }
2313
2314 static unsigned int intel_linear_alignment(struct drm_i915_private *dev_priv)
2315 {
2316         if (INTEL_INFO(dev_priv)->gen >= 9)
2317                 return 256 * 1024;
2318         else if (IS_BROADWATER(dev_priv) || IS_CRESTLINE(dev_priv) ||
2319                  IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv))
2320                 return 128 * 1024;
2321         else if (INTEL_INFO(dev_priv)->gen >= 4)
2322                 return 4 * 1024;
2323         else
2324                 return 0;
2325 }
2326
2327 int
2328 intel_pin_and_fence_fb_obj(struct drm_plane *plane,
2329                            struct drm_framebuffer *fb,
2330                            const struct drm_plane_state *plane_state)
2331 {
2332         struct drm_device *dev = fb->dev;
2333         struct drm_i915_private *dev_priv = dev->dev_private;
2334         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
2335         struct i915_ggtt_view view;
2336         u32 alignment;
2337         int ret;
2338
2339         WARN_ON(!mutex_is_locked(&dev->struct_mutex));
2340
2341         switch (fb->modifier[0]) {
2342         case DRM_FORMAT_MOD_NONE:
2343                 alignment = intel_linear_alignment(dev_priv);
2344                 break;
2345         case I915_FORMAT_MOD_X_TILED:
2346                 if (INTEL_INFO(dev)->gen >= 9)
2347                         alignment = 256 * 1024;
2348                 else {
2349                         /* pin() will align the object as required by fence */
2350                         alignment = 0;
2351                 }
2352                 break;
2353         case I915_FORMAT_MOD_Y_TILED:
2354         case I915_FORMAT_MOD_Yf_TILED:
2355                 if (WARN_ONCE(INTEL_INFO(dev)->gen < 9,
2356                           "Y tiling bo slipped through, driver bug!\n"))
2357                         return -EINVAL;
2358                 alignment = 1 * 1024 * 1024;
2359                 break;
2360         default:
2361                 MISSING_CASE(fb->modifier[0]);
2362                 return -EINVAL;
2363         }
2364
2365         intel_fill_fb_ggtt_view(&view, fb, plane_state);
2366
2367         /* Note that the w/a also requires 64 PTE of padding following the
2368          * bo. We currently fill all unused PTE with the shadow page and so
2369          * we should always have valid PTE following the scanout preventing
2370          * the VT-d warning.
2371          */
2372         if (need_vtd_wa(dev) && alignment < 256 * 1024)
2373                 alignment = 256 * 1024;
2374
2375         /*
2376          * Global gtt pte registers are special registers which actually forward
2377          * writes to a chunk of system memory. Which means that there is no risk
2378          * that the register values disappear as soon as we call
2379          * intel_runtime_pm_put(), so it is correct to wrap only the
2380          * pin/unpin/fence and not more.
2381          */
2382         intel_runtime_pm_get(dev_priv);
2383
2384         ret = i915_gem_object_pin_to_display_plane(obj, alignment,
2385                                                    &view);
2386         if (ret)
2387                 goto err_pm;
2388
2389         /* Install a fence for tiled scan-out. Pre-i965 always needs a
2390          * fence, whereas 965+ only requires a fence if using
2391          * framebuffer compression.  For simplicity, we always install
2392          * a fence as the cost is not that onerous.
2393          */
2394         if (view.type == I915_GGTT_VIEW_NORMAL) {
2395                 ret = i915_gem_object_get_fence(obj);
2396                 if (ret == -EDEADLK) {
2397                         /*
2398                          * -EDEADLK means there are no free fences
2399                          * no pending flips.
2400                          *
2401                          * This is propagated to atomic, but it uses
2402                          * -EDEADLK to force a locking recovery, so
2403                          * change the returned error to -EBUSY.
2404                          */
2405                         ret = -EBUSY;
2406                         goto err_unpin;
2407                 } else if (ret)
2408                         goto err_unpin;
2409
2410                 i915_gem_object_pin_fence(obj);
2411         }
2412
2413         intel_runtime_pm_put(dev_priv);
2414         return 0;
2415
2416 err_unpin:
2417         i915_gem_object_unpin_from_display_plane(obj, &view);
2418 err_pm:
2419         intel_runtime_pm_put(dev_priv);
2420         return ret;
2421 }
2422
2423 static void intel_unpin_fb_obj(struct drm_framebuffer *fb,
2424                                const struct drm_plane_state *plane_state)
2425 {
2426         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
2427         struct i915_ggtt_view view;
2428
2429         WARN_ON(!mutex_is_locked(&obj->base.dev->struct_mutex));
2430
2431         intel_fill_fb_ggtt_view(&view, fb, plane_state);
2432
2433         if (view.type == I915_GGTT_VIEW_NORMAL)
2434                 i915_gem_object_unpin_fence(obj);
2435
2436         i915_gem_object_unpin_from_display_plane(obj, &view);
2437 }
2438
2439 /* Computes the linear offset to the base tile and adjusts x, y. bytes per pixel
2440  * is assumed to be a power-of-two. */
2441 unsigned long intel_gen4_compute_page_offset(struct drm_i915_private *dev_priv,
2442                                              int *x, int *y,
2443                                              unsigned int tiling_mode,
2444                                              unsigned int cpp,
2445                                              unsigned int pitch)
2446 {
2447         if (tiling_mode != I915_TILING_NONE) {
2448                 unsigned int tile_rows, tiles;
2449
2450                 tile_rows = *y / 8;
2451                 *y %= 8;
2452
2453                 tiles = *x / (512/cpp);
2454                 *x %= 512/cpp;
2455
2456                 return tile_rows * pitch * 8 + tiles * 4096;
2457         } else {
2458                 unsigned int alignment = intel_linear_alignment(dev_priv) - 1;
2459                 unsigned int offset;
2460
2461                 offset = *y * pitch + *x * cpp;
2462                 *y = (offset & alignment) / pitch;
2463                 *x = ((offset & alignment) - *y * pitch) / cpp;
2464                 return offset & ~alignment;
2465         }
2466 }
2467
2468 static int i9xx_format_to_fourcc(int format)
2469 {
2470         switch (format) {
2471         case DISPPLANE_8BPP:
2472                 return DRM_FORMAT_C8;
2473         case DISPPLANE_BGRX555:
2474                 return DRM_FORMAT_XRGB1555;
2475         case DISPPLANE_BGRX565:
2476                 return DRM_FORMAT_RGB565;
2477         default:
2478         case DISPPLANE_BGRX888:
2479                 return DRM_FORMAT_XRGB8888;
2480         case DISPPLANE_RGBX888:
2481                 return DRM_FORMAT_XBGR8888;
2482         case DISPPLANE_BGRX101010:
2483                 return DRM_FORMAT_XRGB2101010;
2484         case DISPPLANE_RGBX101010:
2485                 return DRM_FORMAT_XBGR2101010;
2486         }
2487 }
2488
2489 static int skl_format_to_fourcc(int format, bool rgb_order, bool alpha)
2490 {
2491         switch (format) {
2492         case PLANE_CTL_FORMAT_RGB_565:
2493                 return DRM_FORMAT_RGB565;
2494         default:
2495         case PLANE_CTL_FORMAT_XRGB_8888:
2496                 if (rgb_order) {
2497                         if (alpha)
2498                                 return DRM_FORMAT_ABGR8888;
2499                         else
2500                                 return DRM_FORMAT_XBGR8888;
2501                 } else {
2502                         if (alpha)
2503                                 return DRM_FORMAT_ARGB8888;
2504                         else
2505                                 return DRM_FORMAT_XRGB8888;
2506                 }
2507         case PLANE_CTL_FORMAT_XRGB_2101010:
2508                 if (rgb_order)
2509                         return DRM_FORMAT_XBGR2101010;
2510                 else
2511                         return DRM_FORMAT_XRGB2101010;
2512         }
2513 }
2514
2515 static bool
2516 intel_alloc_initial_plane_obj(struct intel_crtc *crtc,
2517                               struct intel_initial_plane_config *plane_config)
2518 {
2519         struct drm_device *dev = crtc->base.dev;
2520         struct drm_i915_private *dev_priv = to_i915(dev);
2521         struct drm_i915_gem_object *obj = NULL;
2522         struct drm_mode_fb_cmd2 mode_cmd = { 0 };
2523         struct drm_framebuffer *fb = &plane_config->fb->base;
2524         u32 base_aligned = round_down(plane_config->base, PAGE_SIZE);
2525         u32 size_aligned = round_up(plane_config->base + plane_config->size,
2526                                     PAGE_SIZE);
2527
2528         size_aligned -= base_aligned;
2529
2530         if (plane_config->size == 0)
2531                 return false;
2532
2533         /* If the FB is too big, just don't use it since fbdev is not very
2534          * important and we should probably use that space with FBC or other
2535          * features. */
2536         if (size_aligned * 2 > dev_priv->gtt.stolen_usable_size)
2537                 return false;
2538
2539         obj = i915_gem_object_create_stolen_for_preallocated(dev,
2540                                                              base_aligned,
2541                                                              base_aligned,
2542                                                              size_aligned);
2543         if (!obj)
2544                 return false;
2545
2546         obj->tiling_mode = plane_config->tiling;
2547         if (obj->tiling_mode == I915_TILING_X)
2548                 obj->stride = fb->pitches[0];
2549
2550         mode_cmd.pixel_format = fb->pixel_format;
2551         mode_cmd.width = fb->width;
2552         mode_cmd.height = fb->height;
2553         mode_cmd.pitches[0] = fb->pitches[0];
2554         mode_cmd.modifier[0] = fb->modifier[0];
2555         mode_cmd.flags = DRM_MODE_FB_MODIFIERS;
2556
2557         mutex_lock(&dev->struct_mutex);
2558         if (intel_framebuffer_init(dev, to_intel_framebuffer(fb),
2559                                    &mode_cmd, obj)) {
2560                 DRM_DEBUG_KMS("intel fb init failed\n");
2561                 goto out_unref_obj;
2562         }
2563         mutex_unlock(&dev->struct_mutex);
2564
2565         DRM_DEBUG_KMS("initial plane fb obj %p\n", obj);
2566         return true;
2567
2568 out_unref_obj:
2569         drm_gem_object_unreference(&obj->base);
2570         mutex_unlock(&dev->struct_mutex);
2571         return false;
2572 }
2573
2574 /* Update plane->state->fb to match plane->fb after driver-internal updates */
2575 static void
2576 update_state_fb(struct drm_plane *plane)
2577 {
2578         if (plane->fb == plane->state->fb)
2579                 return;
2580
2581         if (plane->state->fb)
2582                 drm_framebuffer_unreference(plane->state->fb);
2583         plane->state->fb = plane->fb;
2584         if (plane->state->fb)
2585                 drm_framebuffer_reference(plane->state->fb);
2586 }
2587
2588 static void
2589 intel_find_initial_plane_obj(struct intel_crtc *intel_crtc,
2590                              struct intel_initial_plane_config *plane_config)
2591 {
2592         struct drm_device *dev = intel_crtc->base.dev;
2593         struct drm_i915_private *dev_priv = dev->dev_private;
2594         struct drm_crtc *c;
2595         struct intel_crtc *i;
2596         struct drm_i915_gem_object *obj;
2597         struct drm_plane *primary = intel_crtc->base.primary;
2598         struct drm_plane_state *plane_state = primary->state;
2599         struct drm_crtc_state *crtc_state = intel_crtc->base.state;
2600         struct intel_plane *intel_plane = to_intel_plane(primary);
2601         struct drm_framebuffer *fb;
2602
2603         if (!plane_config->fb)
2604                 return;
2605
2606         if (intel_alloc_initial_plane_obj(intel_crtc, plane_config)) {
2607                 fb = &plane_config->fb->base;
2608                 goto valid_fb;
2609         }
2610
2611         kfree(plane_config->fb);
2612
2613         /*
2614          * Failed to alloc the obj, check to see if we should share
2615          * an fb with another CRTC instead
2616          */
2617         for_each_crtc(dev, c) {
2618                 i = to_intel_crtc(c);
2619
2620                 if (c == &intel_crtc->base)
2621                         continue;
2622
2623                 if (!i->active)
2624                         continue;
2625
2626                 fb = c->primary->fb;
2627                 if (!fb)
2628                         continue;
2629
2630                 obj = intel_fb_obj(fb);
2631                 if (i915_gem_obj_ggtt_offset(obj) == plane_config->base) {
2632                         drm_framebuffer_reference(fb);
2633                         goto valid_fb;
2634                 }
2635         }
2636
2637         /*
2638          * We've failed to reconstruct the BIOS FB.  Current display state
2639          * indicates that the primary plane is visible, but has a NULL FB,
2640          * which will lead to problems later if we don't fix it up.  The
2641          * simplest solution is to just disable the primary plane now and
2642          * pretend the BIOS never had it enabled.
2643          */
2644         to_intel_plane_state(plane_state)->visible = false;
2645         crtc_state->plane_mask &= ~(1 << drm_plane_index(primary));
2646         intel_pre_disable_primary(&intel_crtc->base);
2647         intel_plane->disable_plane(primary, &intel_crtc->base);
2648
2649         return;
2650
2651 valid_fb:
2652         plane_state->src_x = 0;
2653         plane_state->src_y = 0;
2654         plane_state->src_w = fb->width << 16;
2655         plane_state->src_h = fb->height << 16;
2656
2657         plane_state->crtc_x = 0;
2658         plane_state->crtc_y = 0;
2659         plane_state->crtc_w = fb->width;
2660         plane_state->crtc_h = fb->height;
2661
2662         obj = intel_fb_obj(fb);
2663         if (obj->tiling_mode != I915_TILING_NONE)
2664                 dev_priv->preserve_bios_swizzle = true;
2665
2666         drm_framebuffer_reference(fb);
2667         primary->fb = primary->state->fb = fb;
2668         primary->crtc = primary->state->crtc = &intel_crtc->base;
2669         intel_crtc->base.state->plane_mask |= (1 << drm_plane_index(primary));
2670         obj->frontbuffer_bits |= to_intel_plane(primary)->frontbuffer_bit;
2671 }
2672
2673 static void i9xx_update_primary_plane(struct drm_crtc *crtc,
2674                                       struct drm_framebuffer *fb,
2675                                       int x, int y)
2676 {
2677         struct drm_device *dev = crtc->dev;
2678         struct drm_i915_private *dev_priv = dev->dev_private;
2679         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
2680         struct drm_plane *primary = crtc->primary;
2681         bool visible = to_intel_plane_state(primary->state)->visible;
2682         struct drm_i915_gem_object *obj;
2683         int plane = intel_crtc->plane;
2684         unsigned long linear_offset;
2685         u32 dspcntr;
2686         i915_reg_t reg = DSPCNTR(plane);
2687         int pixel_size;
2688
2689         if (!visible || !fb) {
2690                 I915_WRITE(reg, 0);
2691                 if (INTEL_INFO(dev)->gen >= 4)
2692                         I915_WRITE(DSPSURF(plane), 0);
2693                 else
2694                         I915_WRITE(DSPADDR(plane), 0);
2695                 POSTING_READ(reg);
2696                 return;
2697         }
2698
2699         obj = intel_fb_obj(fb);
2700         if (WARN_ON(obj == NULL))
2701                 return;
2702
2703         pixel_size = drm_format_plane_cpp(fb->pixel_format, 0);
2704
2705         dspcntr = DISPPLANE_GAMMA_ENABLE;
2706
2707         dspcntr |= DISPLAY_PLANE_ENABLE;
2708
2709         if (INTEL_INFO(dev)->gen < 4) {
2710                 if (intel_crtc->pipe == PIPE_B)
2711                         dspcntr |= DISPPLANE_SEL_PIPE_B;
2712
2713                 /* pipesrc and dspsize control the size that is scaled from,
2714                  * which should always be the user's requested size.
2715                  */
2716                 I915_WRITE(DSPSIZE(plane),
2717                            ((intel_crtc->config->pipe_src_h - 1) << 16) |
2718                            (intel_crtc->config->pipe_src_w - 1));
2719                 I915_WRITE(DSPPOS(plane), 0);
2720         } else if (IS_CHERRYVIEW(dev) && plane == PLANE_B) {
2721                 I915_WRITE(PRIMSIZE(plane),
2722                            ((intel_crtc->config->pipe_src_h - 1) << 16) |
2723                            (intel_crtc->config->pipe_src_w - 1));
2724                 I915_WRITE(PRIMPOS(plane), 0);
2725                 I915_WRITE(PRIMCNSTALPHA(plane), 0);
2726         }
2727
2728         switch (fb->pixel_format) {
2729         case DRM_FORMAT_C8:
2730                 dspcntr |= DISPPLANE_8BPP;
2731                 break;
2732         case DRM_FORMAT_XRGB1555:
2733                 dspcntr |= DISPPLANE_BGRX555;
2734                 break;
2735         case DRM_FORMAT_RGB565:
2736                 dspcntr |= DISPPLANE_BGRX565;
2737                 break;
2738         case DRM_FORMAT_XRGB8888:
2739                 dspcntr |= DISPPLANE_BGRX888;
2740                 break;
2741         case DRM_FORMAT_XBGR8888:
2742                 dspcntr |= DISPPLANE_RGBX888;
2743                 break;
2744         case DRM_FORMAT_XRGB2101010:
2745                 dspcntr |= DISPPLANE_BGRX101010;
2746                 break;
2747         case DRM_FORMAT_XBGR2101010:
2748                 dspcntr |= DISPPLANE_RGBX101010;
2749                 break;
2750         default:
2751                 BUG();
2752         }
2753
2754         if (INTEL_INFO(dev)->gen >= 4 &&
2755             obj->tiling_mode != I915_TILING_NONE)
2756                 dspcntr |= DISPPLANE_TILED;
2757
2758         if (IS_G4X(dev))
2759                 dspcntr |= DISPPLANE_TRICKLE_FEED_DISABLE;
2760
2761         linear_offset = y * fb->pitches[0] + x * pixel_size;
2762
2763         if (INTEL_INFO(dev)->gen >= 4) {
2764                 intel_crtc->dspaddr_offset =
2765                         intel_gen4_compute_page_offset(dev_priv,
2766                                                        &x, &y, obj->tiling_mode,
2767                                                        pixel_size,
2768                                                        fb->pitches[0]);
2769                 linear_offset -= intel_crtc->dspaddr_offset;
2770         } else {
2771                 intel_crtc->dspaddr_offset = linear_offset;
2772         }
2773
2774         if (crtc->primary->state->rotation == BIT(DRM_ROTATE_180)) {
2775                 dspcntr |= DISPPLANE_ROTATE_180;
2776
2777                 x += (intel_crtc->config->pipe_src_w - 1);
2778                 y += (intel_crtc->config->pipe_src_h - 1);
2779
2780                 /* Finding the last pixel of the last line of the display
2781                 data and adding to linear_offset*/
2782                 linear_offset +=
2783                         (intel_crtc->config->pipe_src_h - 1) * fb->pitches[0] +
2784                         (intel_crtc->config->pipe_src_w - 1) * pixel_size;
2785         }
2786
2787         intel_crtc->adjusted_x = x;
2788         intel_crtc->adjusted_y = y;
2789
2790         I915_WRITE(reg, dspcntr);
2791
2792         I915_WRITE(DSPSTRIDE(plane), fb->pitches[0]);
2793         if (INTEL_INFO(dev)->gen >= 4) {
2794                 I915_WRITE(DSPSURF(plane),
2795                            i915_gem_obj_ggtt_offset(obj) + intel_crtc->dspaddr_offset);
2796                 I915_WRITE(DSPTILEOFF(plane), (y << 16) | x);
2797                 I915_WRITE(DSPLINOFF(plane), linear_offset);
2798         } else
2799                 I915_WRITE(DSPADDR(plane), i915_gem_obj_ggtt_offset(obj) + linear_offset);
2800         POSTING_READ(reg);
2801 }
2802
2803 static void ironlake_update_primary_plane(struct drm_crtc *crtc,
2804                                           struct drm_framebuffer *fb,
2805                                           int x, int y)
2806 {
2807         struct drm_device *dev = crtc->dev;
2808         struct drm_i915_private *dev_priv = dev->dev_private;
2809         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
2810         struct drm_plane *primary = crtc->primary;
2811         bool visible = to_intel_plane_state(primary->state)->visible;
2812         struct drm_i915_gem_object *obj;
2813         int plane = intel_crtc->plane;
2814         unsigned long linear_offset;
2815         u32 dspcntr;
2816         i915_reg_t reg = DSPCNTR(plane);
2817         int pixel_size;
2818
2819         if (!visible || !fb) {
2820                 I915_WRITE(reg, 0);
2821                 I915_WRITE(DSPSURF(plane), 0);
2822                 POSTING_READ(reg);
2823                 return;
2824         }
2825
2826         obj = intel_fb_obj(fb);
2827         if (WARN_ON(obj == NULL))
2828                 return;
2829
2830         pixel_size = drm_format_plane_cpp(fb->pixel_format, 0);
2831
2832         dspcntr = DISPPLANE_GAMMA_ENABLE;
2833
2834         dspcntr |= DISPLAY_PLANE_ENABLE;
2835
2836         if (IS_HASWELL(dev) || IS_BROADWELL(dev))
2837                 dspcntr |= DISPPLANE_PIPE_CSC_ENABLE;
2838
2839         switch (fb->pixel_format) {
2840         case DRM_FORMAT_C8:
2841                 dspcntr |= DISPPLANE_8BPP;
2842                 break;
2843         case DRM_FORMAT_RGB565:
2844                 dspcntr |= DISPPLANE_BGRX565;
2845                 break;
2846         case DRM_FORMAT_XRGB8888:
2847                 dspcntr |= DISPPLANE_BGRX888;
2848                 break;
2849         case DRM_FORMAT_XBGR8888:
2850                 dspcntr |= DISPPLANE_RGBX888;
2851                 break;
2852         case DRM_FORMAT_XRGB2101010:
2853                 dspcntr |= DISPPLANE_BGRX101010;
2854                 break;
2855         case DRM_FORMAT_XBGR2101010:
2856                 dspcntr |= DISPPLANE_RGBX101010;
2857                 break;
2858         default:
2859                 BUG();
2860         }
2861
2862         if (obj->tiling_mode != I915_TILING_NONE)
2863                 dspcntr |= DISPPLANE_TILED;
2864
2865         if (!IS_HASWELL(dev) && !IS_BROADWELL(dev))
2866                 dspcntr |= DISPPLANE_TRICKLE_FEED_DISABLE;
2867
2868         linear_offset = y * fb->pitches[0] + x * pixel_size;
2869         intel_crtc->dspaddr_offset =
2870                 intel_gen4_compute_page_offset(dev_priv,
2871                                                &x, &y, obj->tiling_mode,
2872                                                pixel_size,
2873                                                fb->pitches[0]);
2874         linear_offset -= intel_crtc->dspaddr_offset;
2875         if (crtc->primary->state->rotation == BIT(DRM_ROTATE_180)) {
2876                 dspcntr |= DISPPLANE_ROTATE_180;
2877
2878                 if (!IS_HASWELL(dev) && !IS_BROADWELL(dev)) {
2879                         x += (intel_crtc->config->pipe_src_w - 1);
2880                         y += (intel_crtc->config->pipe_src_h - 1);
2881
2882                         /* Finding the last pixel of the last line of the display
2883                         data and adding to linear_offset*/
2884                         linear_offset +=
2885                                 (intel_crtc->config->pipe_src_h - 1) * fb->pitches[0] +
2886                                 (intel_crtc->config->pipe_src_w - 1) * pixel_size;
2887                 }
2888         }
2889
2890         intel_crtc->adjusted_x = x;
2891         intel_crtc->adjusted_y = y;
2892
2893         I915_WRITE(reg, dspcntr);
2894
2895         I915_WRITE(DSPSTRIDE(plane), fb->pitches[0]);
2896         I915_WRITE(DSPSURF(plane),
2897                    i915_gem_obj_ggtt_offset(obj) + intel_crtc->dspaddr_offset);
2898         if (IS_HASWELL(dev) || IS_BROADWELL(dev)) {
2899                 I915_WRITE(DSPOFFSET(plane), (y << 16) | x);
2900         } else {
2901                 I915_WRITE(DSPTILEOFF(plane), (y << 16) | x);
2902                 I915_WRITE(DSPLINOFF(plane), linear_offset);
2903         }
2904         POSTING_READ(reg);
2905 }
2906
2907 u32 intel_fb_stride_alignment(struct drm_device *dev, uint64_t fb_modifier,
2908                               uint32_t pixel_format)
2909 {
2910         u32 bits_per_pixel = drm_format_plane_cpp(pixel_format, 0) * 8;
2911
2912         /*
2913          * The stride is either expressed as a multiple of 64 bytes
2914          * chunks for linear buffers or in number of tiles for tiled
2915          * buffers.
2916          */
2917         switch (fb_modifier) {
2918         case DRM_FORMAT_MOD_NONE:
2919                 return 64;
2920         case I915_FORMAT_MOD_X_TILED:
2921                 if (INTEL_INFO(dev)->gen == 2)
2922                         return 128;
2923                 return 512;
2924         case I915_FORMAT_MOD_Y_TILED:
2925                 /* No need to check for old gens and Y tiling since this is
2926                  * about the display engine and those will be blocked before
2927                  * we get here.
2928                  */
2929                 return 128;
2930         case I915_FORMAT_MOD_Yf_TILED:
2931                 if (bits_per_pixel == 8)
2932                         return 64;
2933                 else
2934                         return 128;
2935         default:
2936                 MISSING_CASE(fb_modifier);
2937                 return 64;
2938         }
2939 }
2940
2941 u32 intel_plane_obj_offset(struct intel_plane *intel_plane,
2942                            struct drm_i915_gem_object *obj,
2943                            unsigned int plane)
2944 {
2945         struct i915_ggtt_view view;
2946         struct i915_vma *vma;
2947         u64 offset;
2948
2949         intel_fill_fb_ggtt_view(&view, intel_plane->base.fb,
2950                                 intel_plane->base.state);
2951
2952         vma = i915_gem_obj_to_ggtt_view(obj, &view);
2953         if (WARN(!vma, "ggtt vma for display object not found! (view=%u)\n",
2954                 view.type))
2955                 return -1;
2956
2957         offset = vma->node.start;
2958
2959         if (plane == 1) {
2960                 offset += vma->ggtt_view.params.rotation_info.uv_start_page *
2961                           PAGE_SIZE;
2962         }
2963
2964         WARN_ON(upper_32_bits(offset));
2965
2966         return lower_32_bits(offset);
2967 }
2968
2969 static void skl_detach_scaler(struct intel_crtc *intel_crtc, int id)
2970 {
2971         struct drm_device *dev = intel_crtc->base.dev;
2972         struct drm_i915_private *dev_priv = dev->dev_private;
2973
2974         I915_WRITE(SKL_PS_CTRL(intel_crtc->pipe, id), 0);
2975         I915_WRITE(SKL_PS_WIN_POS(intel_crtc->pipe, id), 0);
2976         I915_WRITE(SKL_PS_WIN_SZ(intel_crtc->pipe, id), 0);
2977 }
2978
2979 /*
2980  * This function detaches (aka. unbinds) unused scalers in hardware
2981  */
2982 static void skl_detach_scalers(struct intel_crtc *intel_crtc)
2983 {
2984         struct intel_crtc_scaler_state *scaler_state;
2985         int i;
2986
2987         scaler_state = &intel_crtc->config->scaler_state;
2988
2989         /* loop through and disable scalers that aren't in use */
2990         for (i = 0; i < intel_crtc->num_scalers; i++) {
2991                 if (!scaler_state->scalers[i].in_use)
2992                         skl_detach_scaler(intel_crtc, i);
2993         }
2994 }
2995
2996 u32 skl_plane_ctl_format(uint32_t pixel_format)
2997 {
2998         switch (pixel_format) {
2999         case DRM_FORMAT_C8:
3000                 return PLANE_CTL_FORMAT_INDEXED;
3001         case DRM_FORMAT_RGB565:
3002                 return PLANE_CTL_FORMAT_RGB_565;
3003         case DRM_FORMAT_XBGR8888:
3004                 return PLANE_CTL_FORMAT_XRGB_8888 | PLANE_CTL_ORDER_RGBX;
3005         case DRM_FORMAT_XRGB8888:
3006                 return PLANE_CTL_FORMAT_XRGB_8888;
3007         /*
3008          * XXX: For ARBG/ABGR formats we default to expecting scanout buffers
3009          * to be already pre-multiplied. We need to add a knob (or a different
3010          * DRM_FORMAT) for user-space to configure that.
3011          */
3012         case DRM_FORMAT_ABGR8888:
3013                 return PLANE_CTL_FORMAT_XRGB_8888 | PLANE_CTL_ORDER_RGBX |
3014                         PLANE_CTL_ALPHA_SW_PREMULTIPLY;
3015         case DRM_FORMAT_ARGB8888:
3016                 return PLANE_CTL_FORMAT_XRGB_8888 |
3017                         PLANE_CTL_ALPHA_SW_PREMULTIPLY;
3018         case DRM_FORMAT_XRGB2101010:
3019                 return PLANE_CTL_FORMAT_XRGB_2101010;
3020         case DRM_FORMAT_XBGR2101010:
3021                 return PLANE_CTL_ORDER_RGBX | PLANE_CTL_FORMAT_XRGB_2101010;
3022         case DRM_FORMAT_YUYV:
3023                 return PLANE_CTL_FORMAT_YUV422 | PLANE_CTL_YUV422_YUYV;
3024         case DRM_FORMAT_YVYU:
3025                 return PLANE_CTL_FORMAT_YUV422 | PLANE_CTL_YUV422_YVYU;
3026         case DRM_FORMAT_UYVY:
3027                 return PLANE_CTL_FORMAT_YUV422 | PLANE_CTL_YUV422_UYVY;
3028         case DRM_FORMAT_VYUY:
3029                 return PLANE_CTL_FORMAT_YUV422 | PLANE_CTL_YUV422_VYUY;
3030         default:
3031                 MISSING_CASE(pixel_format);
3032         }
3033
3034         return 0;
3035 }
3036
3037 u32 skl_plane_ctl_tiling(uint64_t fb_modifier)
3038 {
3039         switch (fb_modifier) {
3040         case DRM_FORMAT_MOD_NONE:
3041                 break;
3042         case I915_FORMAT_MOD_X_TILED:
3043                 return PLANE_CTL_TILED_X;
3044         case I915_FORMAT_MOD_Y_TILED:
3045                 return PLANE_CTL_TILED_Y;
3046         case I915_FORMAT_MOD_Yf_TILED:
3047                 return PLANE_CTL_TILED_YF;
3048         default:
3049                 MISSING_CASE(fb_modifier);
3050         }
3051
3052         return 0;
3053 }
3054
3055 u32 skl_plane_ctl_rotation(unsigned int rotation)
3056 {
3057         switch (rotation) {
3058         case BIT(DRM_ROTATE_0):
3059                 break;
3060         /*
3061          * DRM_ROTATE_ is counter clockwise to stay compatible with Xrandr
3062          * while i915 HW rotation is clockwise, thats why this swapping.
3063          */
3064         case BIT(DRM_ROTATE_90):
3065                 return PLANE_CTL_ROTATE_270;
3066         case BIT(DRM_ROTATE_180):
3067                 return PLANE_CTL_ROTATE_180;
3068         case BIT(DRM_ROTATE_270):
3069                 return PLANE_CTL_ROTATE_90;
3070         default:
3071                 MISSING_CASE(rotation);
3072         }
3073
3074         return 0;
3075 }
3076
3077 static void skylake_update_primary_plane(struct drm_crtc *crtc,
3078                                          struct drm_framebuffer *fb,
3079                                          int x, int y)
3080 {
3081         struct drm_device *dev = crtc->dev;
3082         struct drm_i915_private *dev_priv = dev->dev_private;
3083         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
3084         struct drm_plane *plane = crtc->primary;
3085         bool visible = to_intel_plane_state(plane->state)->visible;
3086         struct drm_i915_gem_object *obj;
3087         int pipe = intel_crtc->pipe;
3088         u32 plane_ctl, stride_div, stride;
3089         u32 tile_height, plane_offset, plane_size;
3090         unsigned int rotation;
3091         int x_offset, y_offset;
3092         u32 surf_addr;
3093         struct intel_crtc_state *crtc_state = intel_crtc->config;
3094         struct intel_plane_state *plane_state;
3095         int src_x = 0, src_y = 0, src_w = 0, src_h = 0;
3096         int dst_x = 0, dst_y = 0, dst_w = 0, dst_h = 0;
3097         int scaler_id = -1;
3098
3099         plane_state = to_intel_plane_state(plane->state);
3100
3101         if (!visible || !fb) {
3102                 I915_WRITE(PLANE_CTL(pipe, 0), 0);
3103                 I915_WRITE(PLANE_SURF(pipe, 0), 0);
3104                 POSTING_READ(PLANE_CTL(pipe, 0));
3105                 return;
3106         }
3107
3108         plane_ctl = PLANE_CTL_ENABLE |
3109                     PLANE_CTL_PIPE_GAMMA_ENABLE |
3110                     PLANE_CTL_PIPE_CSC_ENABLE;
3111
3112         plane_ctl |= skl_plane_ctl_format(fb->pixel_format);
3113         plane_ctl |= skl_plane_ctl_tiling(fb->modifier[0]);
3114         plane_ctl |= PLANE_CTL_PLANE_GAMMA_DISABLE;
3115
3116         rotation = plane->state->rotation;
3117         plane_ctl |= skl_plane_ctl_rotation(rotation);
3118
3119         obj = intel_fb_obj(fb);
3120         stride_div = intel_fb_stride_alignment(dev, fb->modifier[0],
3121                                                fb->pixel_format);
3122         surf_addr = intel_plane_obj_offset(to_intel_plane(plane), obj, 0);
3123
3124         WARN_ON(drm_rect_width(&plane_state->src) == 0);
3125
3126         scaler_id = plane_state->scaler_id;
3127         src_x = plane_state->src.x1 >> 16;
3128         src_y = plane_state->src.y1 >> 16;
3129         src_w = drm_rect_width(&plane_state->src) >> 16;
3130         src_h = drm_rect_height(&plane_state->src) >> 16;
3131         dst_x = plane_state->dst.x1;
3132         dst_y = plane_state->dst.y1;
3133         dst_w = drm_rect_width(&plane_state->dst);
3134         dst_h = drm_rect_height(&plane_state->dst);
3135
3136         WARN_ON(x != src_x || y != src_y);
3137
3138         if (intel_rotation_90_or_270(rotation)) {
3139                 /* stride = Surface height in tiles */
3140                 tile_height = intel_tile_height(dev, fb->pixel_format,
3141                                                 fb->modifier[0], 0);
3142                 stride = DIV_ROUND_UP(fb->height, tile_height);
3143                 x_offset = stride * tile_height - y - src_h;
3144                 y_offset = x;
3145                 plane_size = (src_w - 1) << 16 | (src_h - 1);
3146         } else {
3147                 stride = fb->pitches[0] / stride_div;
3148                 x_offset = x;
3149                 y_offset = y;
3150                 plane_size = (src_h - 1) << 16 | (src_w - 1);
3151         }
3152         plane_offset = y_offset << 16 | x_offset;
3153
3154         intel_crtc->adjusted_x = x_offset;
3155         intel_crtc->adjusted_y = y_offset;
3156
3157         I915_WRITE(PLANE_CTL(pipe, 0), plane_ctl);
3158         I915_WRITE(PLANE_OFFSET(pipe, 0), plane_offset);
3159         I915_WRITE(PLANE_SIZE(pipe, 0), plane_size);
3160         I915_WRITE(PLANE_STRIDE(pipe, 0), stride);
3161
3162         if (scaler_id >= 0) {
3163                 uint32_t ps_ctrl = 0;
3164
3165                 WARN_ON(!dst_w || !dst_h);
3166                 ps_ctrl = PS_SCALER_EN | PS_PLANE_SEL(0) |
3167                         crtc_state->scaler_state.scalers[scaler_id].mode;
3168                 I915_WRITE(SKL_PS_CTRL(pipe, scaler_id), ps_ctrl);
3169                 I915_WRITE(SKL_PS_PWR_GATE(pipe, scaler_id), 0);
3170                 I915_WRITE(SKL_PS_WIN_POS(pipe, scaler_id), (dst_x << 16) | dst_y);
3171                 I915_WRITE(SKL_PS_WIN_SZ(pipe, scaler_id), (dst_w << 16) | dst_h);
3172                 I915_WRITE(PLANE_POS(pipe, 0), 0);
3173         } else {
3174                 I915_WRITE(PLANE_POS(pipe, 0), (dst_y << 16) | dst_x);
3175         }
3176
3177         I915_WRITE(PLANE_SURF(pipe, 0), surf_addr);
3178
3179         POSTING_READ(PLANE_SURF(pipe, 0));
3180 }
3181
3182 /* Assume fb object is pinned & idle & fenced and just update base pointers */
3183 static int
3184 intel_pipe_set_base_atomic(struct drm_crtc *crtc, struct drm_framebuffer *fb,
3185                            int x, int y, enum mode_set_atomic state)
3186 {
3187         struct drm_device *dev = crtc->dev;
3188         struct drm_i915_private *dev_priv = dev->dev_private;
3189
3190         if (dev_priv->fbc.deactivate)
3191                 dev_priv->fbc.deactivate(dev_priv);
3192
3193         dev_priv->display.update_primary_plane(crtc, fb, x, y);
3194
3195         return 0;
3196 }
3197
3198 static void intel_complete_page_flips(struct drm_device *dev)
3199 {
3200         struct drm_crtc *crtc;
3201
3202         for_each_crtc(dev, crtc) {
3203                 struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
3204                 enum plane plane = intel_crtc->plane;
3205
3206                 intel_prepare_page_flip(dev, plane);
3207                 intel_finish_page_flip_plane(dev, plane);
3208         }
3209 }
3210
3211 static void intel_update_primary_planes(struct drm_device *dev)
3212 {
3213         struct drm_crtc *crtc;
3214
3215         for_each_crtc(dev, crtc) {
3216                 struct intel_plane *plane = to_intel_plane(crtc->primary);
3217                 struct intel_plane_state *plane_state;
3218
3219                 drm_modeset_lock_crtc(crtc, &plane->base);
3220                 plane_state = to_intel_plane_state(plane->base.state);
3221
3222                 if (crtc->state->active && plane_state->base.fb)
3223                         plane->commit_plane(&plane->base, plane_state);
3224
3225                 drm_modeset_unlock_crtc(crtc);
3226         }
3227 }
3228
3229 void intel_prepare_reset(struct drm_device *dev)
3230 {
3231         /* no reset support for gen2 */
3232         if (IS_GEN2(dev))
3233                 return;
3234
3235         /* reset doesn't touch the display */
3236         if (INTEL_INFO(dev)->gen >= 5 || IS_G4X(dev))
3237                 return;
3238
3239         drm_modeset_lock_all(dev);
3240         /*
3241          * Disabling the crtcs gracefully seems nicer. Also the
3242          * g33 docs say we should at least disable all the planes.
3243          */
3244         intel_display_suspend(dev);
3245 }
3246
3247 void intel_finish_reset(struct drm_device *dev)
3248 {
3249         struct drm_i915_private *dev_priv = to_i915(dev);
3250
3251         /*
3252          * Flips in the rings will be nuked by the reset,
3253          * so complete all pending flips so that user space
3254          * will get its events and not get stuck.
3255          */
3256         intel_complete_page_flips(dev);
3257
3258         /* no reset support for gen2 */
3259         if (IS_GEN2(dev))
3260                 return;
3261
3262         /* reset doesn't touch the display */
3263         if (INTEL_INFO(dev)->gen >= 5 || IS_G4X(dev)) {
3264                 /*
3265                  * Flips in the rings have been nuked by the reset,
3266                  * so update the base address of all primary
3267                  * planes to the the last fb to make sure we're
3268                  * showing the correct fb after a reset.
3269                  *
3270                  * FIXME: Atomic will make this obsolete since we won't schedule
3271                  * CS-based flips (which might get lost in gpu resets) any more.
3272                  */
3273                 intel_update_primary_planes(dev);
3274                 return;
3275         }
3276
3277         /*
3278          * The display has been reset as well,
3279          * so need a full re-initialization.
3280          */
3281         intel_runtime_pm_disable_interrupts(dev_priv);
3282         intel_runtime_pm_enable_interrupts(dev_priv);
3283
3284         intel_modeset_init_hw(dev);
3285
3286         spin_lock_irq(&dev_priv->irq_lock);
3287         if (dev_priv->display.hpd_irq_setup)
3288                 dev_priv->display.hpd_irq_setup(dev);
3289         spin_unlock_irq(&dev_priv->irq_lock);
3290
3291         intel_display_resume(dev);
3292
3293         intel_hpd_init(dev_priv);
3294
3295         drm_modeset_unlock_all(dev);
3296 }
3297
3298 static bool intel_crtc_has_pending_flip(struct drm_crtc *crtc)
3299 {
3300         struct drm_device *dev = crtc->dev;
3301         struct drm_i915_private *dev_priv = dev->dev_private;
3302         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
3303         bool pending;
3304
3305         if (i915_reset_in_progress(&dev_priv->gpu_error) ||
3306             intel_crtc->reset_counter != atomic_read(&dev_priv->gpu_error.reset_counter))
3307                 return false;
3308
3309         spin_lock_irq(&dev->event_lock);
3310         pending = to_intel_crtc(crtc)->unpin_work != NULL;
3311         spin_unlock_irq(&dev->event_lock);
3312
3313         return pending;
3314 }
3315
3316 static void intel_update_pipe_config(struct intel_crtc *crtc,
3317                                      struct intel_crtc_state *old_crtc_state)
3318 {
3319         struct drm_device *dev = crtc->base.dev;
3320         struct drm_i915_private *dev_priv = dev->dev_private;
3321         struct intel_crtc_state *pipe_config =
3322                 to_intel_crtc_state(crtc->base.state);
3323
3324         /* drm_atomic_helper_update_legacy_modeset_state might not be called. */
3325         crtc->base.mode = crtc->base.state->mode;
3326
3327         DRM_DEBUG_KMS("Updating pipe size %ix%i -> %ix%i\n",
3328                       old_crtc_state->pipe_src_w, old_crtc_state->pipe_src_h,
3329                       pipe_config->pipe_src_w, pipe_config->pipe_src_h);
3330
3331         if (HAS_DDI(dev))
3332                 intel_set_pipe_csc(&crtc->base);
3333
3334         /*
3335          * Update pipe size and adjust fitter if needed: the reason for this is
3336          * that in compute_mode_changes we check the native mode (not the pfit
3337          * mode) to see if we can flip rather than do a full mode set. In the
3338          * fastboot case, we'll flip, but if we don't update the pipesrc and
3339          * pfit state, we'll end up with a big fb scanned out into the wrong
3340          * sized surface.
3341          */
3342
3343         I915_WRITE(PIPESRC(crtc->pipe),
3344                    ((pipe_config->pipe_src_w - 1) << 16) |
3345                    (pipe_config->pipe_src_h - 1));
3346
3347         /* on skylake this is done by detaching scalers */
3348         if (INTEL_INFO(dev)->gen >= 9) {
3349                 skl_detach_scalers(crtc);
3350
3351                 if (pipe_config->pch_pfit.enabled)
3352                         skylake_pfit_enable(crtc);
3353         } else if (HAS_PCH_SPLIT(dev)) {
3354                 if (pipe_config->pch_pfit.enabled)
3355                         ironlake_pfit_enable(crtc);
3356                 else if (old_crtc_state->pch_pfit.enabled)
3357                         ironlake_pfit_disable(crtc, true);
3358         }
3359 }
3360
3361 static void intel_fdi_normal_train(struct drm_crtc *crtc)
3362 {
3363         struct drm_device *dev = crtc->dev;
3364         struct drm_i915_private *dev_priv = dev->dev_private;
3365         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
3366         int pipe = intel_crtc->pipe;
3367         i915_reg_t reg;
3368         u32 temp;
3369
3370         /* enable normal train */
3371         reg = FDI_TX_CTL(pipe);
3372         temp = I915_READ(reg);
3373         if (IS_IVYBRIDGE(dev)) {
3374                 temp &= ~FDI_LINK_TRAIN_NONE_IVB;
3375                 temp |= FDI_LINK_TRAIN_NONE_IVB | FDI_TX_ENHANCE_FRAME_ENABLE;
3376         } else {
3377                 temp &= ~FDI_LINK_TRAIN_NONE;
3378                 temp |= FDI_LINK_TRAIN_NONE | FDI_TX_ENHANCE_FRAME_ENABLE;
3379         }
3380         I915_WRITE(reg, temp);
3381
3382         reg = FDI_RX_CTL(pipe);
3383         temp = I915_READ(reg);
3384         if (HAS_PCH_CPT(dev)) {
3385                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
3386                 temp |= FDI_LINK_TRAIN_NORMAL_CPT;
3387         } else {
3388                 temp &= ~FDI_LINK_TRAIN_NONE;
3389                 temp |= FDI_LINK_TRAIN_NONE;
3390         }
3391         I915_WRITE(reg, temp | FDI_RX_ENHANCE_FRAME_ENABLE);
3392
3393         /* wait one idle pattern time */
3394         POSTING_READ(reg);
3395         udelay(1000);
3396
3397         /* IVB wants error correction enabled */
3398         if (IS_IVYBRIDGE(dev))
3399                 I915_WRITE(reg, I915_READ(reg) | FDI_FS_ERRC_ENABLE |
3400                            FDI_FE_ERRC_ENABLE);
3401 }
3402
3403 /* The FDI link training functions for ILK/Ibexpeak. */
3404 static void ironlake_fdi_link_train(struct drm_crtc *crtc)
3405 {
3406         struct drm_device *dev = crtc->dev;
3407         struct drm_i915_private *dev_priv = dev->dev_private;
3408         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
3409         int pipe = intel_crtc->pipe;
3410         i915_reg_t reg;
3411         u32 temp, tries;
3412
3413         /* FDI needs bits from pipe first */
3414         assert_pipe_enabled(dev_priv, pipe);
3415
3416         /* Train 1: umask FDI RX Interrupt symbol_lock and bit_lock bit
3417            for train result */
3418         reg = FDI_RX_IMR(pipe);
3419         temp = I915_READ(reg);
3420         temp &= ~FDI_RX_SYMBOL_LOCK;
3421         temp &= ~FDI_RX_BIT_LOCK;
3422         I915_WRITE(reg, temp);
3423         I915_READ(reg);
3424         udelay(150);
3425
3426         /* enable CPU FDI TX and PCH FDI RX */
3427         reg = FDI_TX_CTL(pipe);
3428         temp = I915_READ(reg);
3429         temp &= ~FDI_DP_PORT_WIDTH_MASK;
3430         temp |= FDI_DP_PORT_WIDTH(intel_crtc->config->fdi_lanes);
3431         temp &= ~FDI_LINK_TRAIN_NONE;
3432         temp |= FDI_LINK_TRAIN_PATTERN_1;
3433         I915_WRITE(reg, temp | FDI_TX_ENABLE);
3434
3435         reg = FDI_RX_CTL(pipe);
3436         temp = I915_READ(reg);
3437         temp &= ~FDI_LINK_TRAIN_NONE;
3438         temp |= FDI_LINK_TRAIN_PATTERN_1;
3439         I915_WRITE(reg, temp | FDI_RX_ENABLE);
3440
3441         POSTING_READ(reg);
3442         udelay(150);
3443
3444         /* Ironlake workaround, enable clock pointer after FDI enable*/
3445         I915_WRITE(FDI_RX_CHICKEN(pipe), FDI_RX_PHASE_SYNC_POINTER_OVR);
3446         I915_WRITE(FDI_RX_CHICKEN(pipe), FDI_RX_PHASE_SYNC_POINTER_OVR |
3447                    FDI_RX_PHASE_SYNC_POINTER_EN);
3448
3449         reg = FDI_RX_IIR(pipe);
3450         for (tries = 0; tries < 5; tries++) {
3451                 temp = I915_READ(reg);
3452                 DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
3453
3454                 if ((temp & FDI_RX_BIT_LOCK)) {
3455                         DRM_DEBUG_KMS("FDI train 1 done.\n");
3456                         I915_WRITE(reg, temp | FDI_RX_BIT_LOCK);
3457                         break;
3458                 }
3459         }
3460         if (tries == 5)
3461                 DRM_ERROR("FDI train 1 fail!\n");
3462
3463         /* Train 2 */
3464         reg = FDI_TX_CTL(pipe);
3465         temp = I915_READ(reg);
3466         temp &= ~FDI_LINK_TRAIN_NONE;
3467         temp |= FDI_LINK_TRAIN_PATTERN_2;
3468         I915_WRITE(reg, temp);
3469
3470         reg = FDI_RX_CTL(pipe);
3471         temp = I915_READ(reg);
3472         temp &= ~FDI_LINK_TRAIN_NONE;
3473         temp |= FDI_LINK_TRAIN_PATTERN_2;
3474         I915_WRITE(reg, temp);
3475
3476         POSTING_READ(reg);
3477         udelay(150);
3478
3479         reg = FDI_RX_IIR(pipe);
3480         for (tries = 0; tries < 5; tries++) {
3481                 temp = I915_READ(reg);
3482                 DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
3483
3484                 if (temp & FDI_RX_SYMBOL_LOCK) {
3485                         I915_WRITE(reg, temp | FDI_RX_SYMBOL_LOCK);
3486                         DRM_DEBUG_KMS("FDI train 2 done.\n");
3487                         break;
3488                 }
3489         }
3490         if (tries == 5)
3491                 DRM_ERROR("FDI train 2 fail!\n");
3492
3493         DRM_DEBUG_KMS("FDI train done\n");
3494
3495 }
3496
3497 static const int snb_b_fdi_train_param[] = {
3498         FDI_LINK_TRAIN_400MV_0DB_SNB_B,
3499         FDI_LINK_TRAIN_400MV_6DB_SNB_B,
3500         FDI_LINK_TRAIN_600MV_3_5DB_SNB_B,
3501         FDI_LINK_TRAIN_800MV_0DB_SNB_B,
3502 };
3503
3504 /* The FDI link training functions for SNB/Cougarpoint. */
3505 static void gen6_fdi_link_train(struct drm_crtc *crtc)
3506 {
3507         struct drm_device *dev = crtc->dev;
3508         struct drm_i915_private *dev_priv = dev->dev_private;
3509         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
3510         int pipe = intel_crtc->pipe;
3511         i915_reg_t reg;
3512         u32 temp, i, retry;
3513
3514         /* Train 1: umask FDI RX Interrupt symbol_lock and bit_lock bit
3515            for train result */
3516         reg = FDI_RX_IMR(pipe);
3517         temp = I915_READ(reg);
3518         temp &= ~FDI_RX_SYMBOL_LOCK;
3519         temp &= ~FDI_RX_BIT_LOCK;
3520         I915_WRITE(reg, temp);
3521
3522         POSTING_READ(reg);
3523         udelay(150);
3524
3525         /* enable CPU FDI TX and PCH FDI RX */
3526         reg = FDI_TX_CTL(pipe);
3527         temp = I915_READ(reg);
3528         temp &= ~FDI_DP_PORT_WIDTH_MASK;
3529         temp |= FDI_DP_PORT_WIDTH(intel_crtc->config->fdi_lanes);
3530         temp &= ~FDI_LINK_TRAIN_NONE;
3531         temp |= FDI_LINK_TRAIN_PATTERN_1;
3532         temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
3533         /* SNB-B */
3534         temp |= FDI_LINK_TRAIN_400MV_0DB_SNB_B;
3535         I915_WRITE(reg, temp | FDI_TX_ENABLE);
3536
3537         I915_WRITE(FDI_RX_MISC(pipe),
3538                    FDI_RX_TP1_TO_TP2_48 | FDI_RX_FDI_DELAY_90);
3539
3540         reg = FDI_RX_CTL(pipe);
3541         temp = I915_READ(reg);
3542         if (HAS_PCH_CPT(dev)) {
3543                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
3544                 temp |= FDI_LINK_TRAIN_PATTERN_1_CPT;
3545         } else {
3546                 temp &= ~FDI_LINK_TRAIN_NONE;
3547                 temp |= FDI_LINK_TRAIN_PATTERN_1;
3548         }
3549         I915_WRITE(reg, temp | FDI_RX_ENABLE);
3550
3551         POSTING_READ(reg);
3552         udelay(150);
3553
3554         for (i = 0; i < 4; i++) {
3555                 reg = FDI_TX_CTL(pipe);
3556                 temp = I915_READ(reg);
3557                 temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
3558                 temp |= snb_b_fdi_train_param[i];
3559                 I915_WRITE(reg, temp);
3560
3561                 POSTING_READ(reg);
3562                 udelay(500);
3563
3564                 for (retry = 0; retry < 5; retry++) {
3565                         reg = FDI_RX_IIR(pipe);
3566                         temp = I915_READ(reg);
3567                         DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
3568                         if (temp & FDI_RX_BIT_LOCK) {
3569                                 I915_WRITE(reg, temp | FDI_RX_BIT_LOCK);
3570                                 DRM_DEBUG_KMS("FDI train 1 done.\n");
3571                                 break;
3572                         }
3573                         udelay(50);
3574                 }
3575                 if (retry < 5)
3576                         break;
3577         }
3578         if (i == 4)
3579                 DRM_ERROR("FDI train 1 fail!\n");
3580
3581         /* Train 2 */
3582         reg = FDI_TX_CTL(pipe);
3583         temp = I915_READ(reg);
3584         temp &= ~FDI_LINK_TRAIN_NONE;
3585         temp |= FDI_LINK_TRAIN_PATTERN_2;
3586         if (IS_GEN6(dev)) {
3587                 temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
3588                 /* SNB-B */
3589                 temp |= FDI_LINK_TRAIN_400MV_0DB_SNB_B;
3590         }
3591         I915_WRITE(reg, temp);
3592
3593         reg = FDI_RX_CTL(pipe);
3594         temp = I915_READ(reg);
3595         if (HAS_PCH_CPT(dev)) {
3596                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
3597                 temp |= FDI_LINK_TRAIN_PATTERN_2_CPT;
3598         } else {
3599                 temp &= ~FDI_LINK_TRAIN_NONE;
3600                 temp |= FDI_LINK_TRAIN_PATTERN_2;
3601         }
3602         I915_WRITE(reg, temp);
3603
3604         POSTING_READ(reg);
3605         udelay(150);
3606
3607         for (i = 0; i < 4; i++) {
3608                 reg = FDI_TX_CTL(pipe);
3609                 temp = I915_READ(reg);
3610                 temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
3611                 temp |= snb_b_fdi_train_param[i];
3612                 I915_WRITE(reg, temp);
3613
3614                 POSTING_READ(reg);
3615                 udelay(500);
3616
3617                 for (retry = 0; retry < 5; retry++) {
3618                         reg = FDI_RX_IIR(pipe);
3619                         temp = I915_READ(reg);
3620                         DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
3621                         if (temp & FDI_RX_SYMBOL_LOCK) {
3622                                 I915_WRITE(reg, temp | FDI_RX_SYMBOL_LOCK);
3623                                 DRM_DEBUG_KMS("FDI train 2 done.\n");
3624                                 break;
3625                         }
3626                         udelay(50);
3627                 }
3628                 if (retry < 5)
3629                         break;
3630         }
3631         if (i == 4)
3632                 DRM_ERROR("FDI train 2 fail!\n");
3633
3634         DRM_DEBUG_KMS("FDI train done.\n");
3635 }
3636
3637 /* Manual link training for Ivy Bridge A0 parts */
3638 static void ivb_manual_fdi_link_train(struct drm_crtc *crtc)
3639 {
3640         struct drm_device *dev = crtc->dev;
3641         struct drm_i915_private *dev_priv = dev->dev_private;
3642         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
3643         int pipe = intel_crtc->pipe;
3644         i915_reg_t reg;
3645         u32 temp, i, j;
3646
3647         /* Train 1: umask FDI RX Interrupt symbol_lock and bit_lock bit
3648            for train result */
3649         reg = FDI_RX_IMR(pipe);
3650         temp = I915_READ(reg);
3651         temp &= ~FDI_RX_SYMBOL_LOCK;
3652         temp &= ~FDI_RX_BIT_LOCK;
3653         I915_WRITE(reg, temp);
3654
3655         POSTING_READ(reg);
3656         udelay(150);
3657
3658         DRM_DEBUG_KMS("FDI_RX_IIR before link train 0x%x\n",
3659                       I915_READ(FDI_RX_IIR(pipe)));
3660
3661         /* Try each vswing and preemphasis setting twice before moving on */
3662         for (j = 0; j < ARRAY_SIZE(snb_b_fdi_train_param) * 2; j++) {
3663                 /* disable first in case we need to retry */
3664                 reg = FDI_TX_CTL(pipe);
3665                 temp = I915_READ(reg);
3666                 temp &= ~(FDI_LINK_TRAIN_AUTO | FDI_LINK_TRAIN_NONE_IVB);
3667                 temp &= ~FDI_TX_ENABLE;
3668                 I915_WRITE(reg, temp);
3669
3670                 reg = FDI_RX_CTL(pipe);
3671                 temp = I915_READ(reg);
3672                 temp &= ~FDI_LINK_TRAIN_AUTO;
3673                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
3674                 temp &= ~FDI_RX_ENABLE;
3675                 I915_WRITE(reg, temp);
3676
3677                 /* enable CPU FDI TX and PCH FDI RX */
3678                 reg = FDI_TX_CTL(pipe);
3679                 temp = I915_READ(reg);
3680                 temp &= ~FDI_DP_PORT_WIDTH_MASK;
3681                 temp |= FDI_DP_PORT_WIDTH(intel_crtc->config->fdi_lanes);
3682                 temp |= FDI_LINK_TRAIN_PATTERN_1_IVB;
3683                 temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
3684                 temp |= snb_b_fdi_train_param[j/2];
3685                 temp |= FDI_COMPOSITE_SYNC;
3686                 I915_WRITE(reg, temp | FDI_TX_ENABLE);
3687
3688                 I915_WRITE(FDI_RX_MISC(pipe),
3689                            FDI_RX_TP1_TO_TP2_48 | FDI_RX_FDI_DELAY_90);
3690
3691                 reg = FDI_RX_CTL(pipe);
3692                 temp = I915_READ(reg);
3693                 temp |= FDI_LINK_TRAIN_PATTERN_1_CPT;
3694                 temp |= FDI_COMPOSITE_SYNC;
3695                 I915_WRITE(reg, temp | FDI_RX_ENABLE);
3696
3697                 POSTING_READ(reg);
3698                 udelay(1); /* should be 0.5us */
3699
3700                 for (i = 0; i < 4; i++) {
3701                         reg = FDI_RX_IIR(pipe);
3702                         temp = I915_READ(reg);
3703                         DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
3704
3705                         if (temp & FDI_RX_BIT_LOCK ||
3706                             (I915_READ(reg) & FDI_RX_BIT_LOCK)) {
3707                                 I915_WRITE(reg, temp | FDI_RX_BIT_LOCK);
3708                                 DRM_DEBUG_KMS("FDI train 1 done, level %i.\n",
3709                                               i);
3710                                 break;
3711                         }
3712                         udelay(1); /* should be 0.5us */
3713                 }
3714                 if (i == 4) {
3715                         DRM_DEBUG_KMS("FDI train 1 fail on vswing %d\n", j / 2);
3716                         continue;
3717                 }
3718
3719                 /* Train 2 */
3720                 reg = FDI_TX_CTL(pipe);
3721                 temp = I915_READ(reg);
3722                 temp &= ~FDI_LINK_TRAIN_NONE_IVB;
3723                 temp |= FDI_LINK_TRAIN_PATTERN_2_IVB;
3724                 I915_WRITE(reg, temp);
3725
3726                 reg = FDI_RX_CTL(pipe);
3727                 temp = I915_READ(reg);
3728                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
3729                 temp |= FDI_LINK_TRAIN_PATTERN_2_CPT;
3730                 I915_WRITE(reg, temp);
3731
3732                 POSTING_READ(reg);
3733                 udelay(2); /* should be 1.5us */
3734
3735                 for (i = 0; i < 4; i++) {
3736                         reg = FDI_RX_IIR(pipe);
3737                         temp = I915_READ(reg);
3738                         DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
3739
3740                         if (temp & FDI_RX_SYMBOL_LOCK ||
3741                             (I915_READ(reg) & FDI_RX_SYMBOL_LOCK)) {
3742                                 I915_WRITE(reg, temp | FDI_RX_SYMBOL_LOCK);
3743                                 DRM_DEBUG_KMS("FDI train 2 done, level %i.\n",
3744                                               i);
3745                                 goto train_done;
3746                         }
3747                         udelay(2); /* should be 1.5us */
3748                 }
3749                 if (i == 4)
3750                         DRM_DEBUG_KMS("FDI train 2 fail on vswing %d\n", j / 2);
3751         }
3752
3753 train_done:
3754         DRM_DEBUG_KMS("FDI train done.\n");
3755 }
3756
3757 static void ironlake_fdi_pll_enable(struct intel_crtc *intel_crtc)
3758 {
3759         struct drm_device *dev = intel_crtc->base.dev;
3760         struct drm_i915_private *dev_priv = dev->dev_private;
3761         int pipe = intel_crtc->pipe;
3762         i915_reg_t reg;
3763         u32 temp;
3764
3765         /* enable PCH FDI RX PLL, wait warmup plus DMI latency */
3766         reg = FDI_RX_CTL(pipe);
3767         temp = I915_READ(reg);
3768         temp &= ~(FDI_DP_PORT_WIDTH_MASK | (0x7 << 16));
3769         temp |= FDI_DP_PORT_WIDTH(intel_crtc->config->fdi_lanes);
3770         temp |= (I915_READ(PIPECONF(pipe)) & PIPECONF_BPC_MASK) << 11;
3771         I915_WRITE(reg, temp | FDI_RX_PLL_ENABLE);
3772
3773         POSTING_READ(reg);
3774         udelay(200);
3775
3776         /* Switch from Rawclk to PCDclk */
3777         temp = I915_READ(reg);
3778         I915_WRITE(reg, temp | FDI_PCDCLK);
3779
3780         POSTING_READ(reg);
3781         udelay(200);
3782
3783         /* Enable CPU FDI TX PLL, always on for Ironlake */
3784         reg = FDI_TX_CTL(pipe);
3785         temp = I915_READ(reg);
3786         if ((temp & FDI_TX_PLL_ENABLE) == 0) {
3787                 I915_WRITE(reg, temp | FDI_TX_PLL_ENABLE);
3788
3789                 POSTING_READ(reg);
3790                 udelay(100);
3791         }
3792 }
3793
3794 static void ironlake_fdi_pll_disable(struct intel_crtc *intel_crtc)
3795 {
3796         struct drm_device *dev = intel_crtc->base.dev;
3797         struct drm_i915_private *dev_priv = dev->dev_private;
3798         int pipe = intel_crtc->pipe;
3799         i915_reg_t reg;
3800         u32 temp;
3801
3802         /* Switch from PCDclk to Rawclk */
3803         reg = FDI_RX_CTL(pipe);
3804         temp = I915_READ(reg);
3805         I915_WRITE(reg, temp & ~FDI_PCDCLK);
3806
3807         /* Disable CPU FDI TX PLL */
3808         reg = FDI_TX_CTL(pipe);
3809         temp = I915_READ(reg);
3810         I915_WRITE(reg, temp & ~FDI_TX_PLL_ENABLE);
3811
3812         POSTING_READ(reg);
3813         udelay(100);
3814
3815         reg = FDI_RX_CTL(pipe);
3816         temp = I915_READ(reg);
3817         I915_WRITE(reg, temp & ~FDI_RX_PLL_ENABLE);
3818
3819         /* Wait for the clocks to turn off. */
3820         POSTING_READ(reg);
3821         udelay(100);
3822 }
3823
3824 static void ironlake_fdi_disable(struct drm_crtc *crtc)
3825 {
3826         struct drm_device *dev = crtc->dev;
3827         struct drm_i915_private *dev_priv = dev->dev_private;
3828         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
3829         int pipe = intel_crtc->pipe;
3830         i915_reg_t reg;
3831         u32 temp;
3832
3833         /* disable CPU FDI tx and PCH FDI rx */
3834         reg = FDI_TX_CTL(pipe);
3835         temp = I915_READ(reg);
3836         I915_WRITE(reg, temp & ~FDI_TX_ENABLE);
3837         POSTING_READ(reg);
3838
3839         reg = FDI_RX_CTL(pipe);
3840         temp = I915_READ(reg);
3841         temp &= ~(0x7 << 16);
3842         temp |= (I915_READ(PIPECONF(pipe)) & PIPECONF_BPC_MASK) << 11;
3843         I915_WRITE(reg, temp & ~FDI_RX_ENABLE);
3844
3845         POSTING_READ(reg);
3846         udelay(100);
3847
3848         /* Ironlake workaround, disable clock pointer after downing FDI */
3849         if (HAS_PCH_IBX(dev))
3850                 I915_WRITE(FDI_RX_CHICKEN(pipe), FDI_RX_PHASE_SYNC_POINTER_OVR);
3851
3852         /* still set train pattern 1 */
3853         reg = FDI_TX_CTL(pipe);
3854         temp = I915_READ(reg);
3855         temp &= ~FDI_LINK_TRAIN_NONE;
3856         temp |= FDI_LINK_TRAIN_PATTERN_1;
3857         I915_WRITE(reg, temp);
3858
3859         reg = FDI_RX_CTL(pipe);
3860         temp = I915_READ(reg);
3861         if (HAS_PCH_CPT(dev)) {
3862                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
3863                 temp |= FDI_LINK_TRAIN_PATTERN_1_CPT;
3864         } else {
3865                 temp &= ~FDI_LINK_TRAIN_NONE;
3866                 temp |= FDI_LINK_TRAIN_PATTERN_1;
3867         }
3868         /* BPC in FDI rx is consistent with that in PIPECONF */
3869         temp &= ~(0x07 << 16);
3870         temp |= (I915_READ(PIPECONF(pipe)) & PIPECONF_BPC_MASK) << 11;
3871         I915_WRITE(reg, temp);
3872
3873         POSTING_READ(reg);
3874         udelay(100);
3875 }
3876
3877 bool intel_has_pending_fb_unpin(struct drm_device *dev)
3878 {
3879         struct intel_crtc *crtc;
3880
3881         /* Note that we don't need to be called with mode_config.lock here
3882          * as our list of CRTC objects is static for the lifetime of the
3883          * device and so cannot disappear as we iterate. Similarly, we can
3884          * happily treat the predicates as racy, atomic checks as userspace
3885          * cannot claim and pin a new fb without at least acquring the
3886          * struct_mutex and so serialising with us.
3887          */
3888         for_each_intel_crtc(dev, crtc) {
3889                 if (atomic_read(&crtc->unpin_work_count) == 0)
3890                         continue;
3891
3892                 if (crtc->unpin_work)
3893                         intel_wait_for_vblank(dev, crtc->pipe);
3894
3895                 return true;
3896         }
3897
3898         return false;
3899 }
3900
3901 static void page_flip_completed(struct intel_crtc *intel_crtc)
3902 {
3903         struct drm_i915_private *dev_priv = to_i915(intel_crtc->base.dev);
3904         struct intel_unpin_work *work = intel_crtc->unpin_work;
3905
3906         /* ensure that the unpin work is consistent wrt ->pending. */
3907         smp_rmb();
3908         intel_crtc->unpin_work = NULL;
3909
3910         if (work->event)
3911                 drm_send_vblank_event(intel_crtc->base.dev,
3912                                       intel_crtc->pipe,
3913                                       work->event);
3914
3915         drm_crtc_vblank_put(&intel_crtc->base);
3916
3917         wake_up_all(&dev_priv->pending_flip_queue);
3918         queue_work(dev_priv->wq, &work->work);
3919
3920         trace_i915_flip_complete(intel_crtc->plane,
3921                                  work->pending_flip_obj);
3922 }
3923
3924 static int intel_crtc_wait_for_pending_flips(struct drm_crtc *crtc)
3925 {
3926         struct drm_device *dev = crtc->dev;
3927         struct drm_i915_private *dev_priv = dev->dev_private;
3928         long ret;
3929
3930         WARN_ON(waitqueue_active(&dev_priv->pending_flip_queue));
3931
3932         ret = wait_event_interruptible_timeout(
3933                                         dev_priv->pending_flip_queue,
3934                                         !intel_crtc_has_pending_flip(crtc),
3935                                         60*HZ);
3936
3937         if (ret < 0)
3938                 return ret;
3939
3940         if (ret == 0) {
3941                 struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
3942
3943                 spin_lock_irq(&dev->event_lock);
3944                 if (intel_crtc->unpin_work) {
3945                         WARN_ONCE(1, "Removing stuck page flip\n");
3946                         page_flip_completed(intel_crtc);
3947                 }
3948                 spin_unlock_irq(&dev->event_lock);
3949         }
3950
3951         return 0;
3952 }
3953
3954 static void lpt_disable_iclkip(struct drm_i915_private *dev_priv)
3955 {
3956         u32 temp;
3957
3958         I915_WRITE(PIXCLK_GATE, PIXCLK_GATE_GATE);
3959
3960         mutex_lock(&dev_priv->sb_lock);
3961
3962         temp = intel_sbi_read(dev_priv, SBI_SSCCTL6, SBI_ICLK);
3963         temp |= SBI_SSCCTL_DISABLE;
3964         intel_sbi_write(dev_priv, SBI_SSCCTL6, temp, SBI_ICLK);
3965
3966         mutex_unlock(&dev_priv->sb_lock);
3967 }
3968
3969 /* Program iCLKIP clock to the desired frequency */
3970 static void lpt_program_iclkip(struct drm_crtc *crtc)
3971 {
3972         struct drm_device *dev = crtc->dev;
3973         struct drm_i915_private *dev_priv = dev->dev_private;
3974         int clock = to_intel_crtc(crtc)->config->base.adjusted_mode.crtc_clock;
3975         u32 divsel, phaseinc, auxdiv, phasedir = 0;
3976         u32 temp;
3977
3978         lpt_disable_iclkip(dev_priv);
3979
3980         /* 20MHz is a corner case which is out of range for the 7-bit divisor */
3981         if (clock == 20000) {
3982                 auxdiv = 1;
3983                 divsel = 0x41;
3984                 phaseinc = 0x20;
3985         } else {
3986                 /* The iCLK virtual clock root frequency is in MHz,
3987                  * but the adjusted_mode->crtc_clock in in KHz. To get the
3988                  * divisors, it is necessary to divide one by another, so we
3989                  * convert the virtual clock precision to KHz here for higher
3990                  * precision.
3991                  */
3992                 u32 iclk_virtual_root_freq = 172800 * 1000;
3993                 u32 iclk_pi_range = 64;
3994                 u32 desired_divisor, msb_divisor_value, pi_value;
3995
3996                 desired_divisor = DIV_ROUND_CLOSEST(iclk_virtual_root_freq, clock);
3997                 msb_divisor_value = desired_divisor / iclk_pi_range;
3998                 pi_value = desired_divisor % iclk_pi_range;
3999
4000                 auxdiv = 0;
4001                 divsel = msb_divisor_value - 2;
4002                 phaseinc = pi_value;
4003         }
4004
4005         /* This should not happen with any sane values */
4006         WARN_ON(SBI_SSCDIVINTPHASE_DIVSEL(divsel) &
4007                 ~SBI_SSCDIVINTPHASE_DIVSEL_MASK);
4008         WARN_ON(SBI_SSCDIVINTPHASE_DIR(phasedir) &
4009                 ~SBI_SSCDIVINTPHASE_INCVAL_MASK);
4010
4011         DRM_DEBUG_KMS("iCLKIP clock: found settings for %dKHz refresh rate: auxdiv=%x, divsel=%x, phasedir=%x, phaseinc=%x\n",
4012                         clock,
4013                         auxdiv,
4014                         divsel,
4015                         phasedir,
4016                         phaseinc);
4017
4018         mutex_lock(&dev_priv->sb_lock);
4019
4020         /* Program SSCDIVINTPHASE6 */
4021         temp = intel_sbi_read(dev_priv, SBI_SSCDIVINTPHASE6, SBI_ICLK);
4022         temp &= ~SBI_SSCDIVINTPHASE_DIVSEL_MASK;
4023         temp |= SBI_SSCDIVINTPHASE_DIVSEL(divsel);
4024         temp &= ~SBI_SSCDIVINTPHASE_INCVAL_MASK;
4025         temp |= SBI_SSCDIVINTPHASE_INCVAL(phaseinc);
4026         temp |= SBI_SSCDIVINTPHASE_DIR(phasedir);
4027         temp |= SBI_SSCDIVINTPHASE_PROPAGATE;
4028         intel_sbi_write(dev_priv, SBI_SSCDIVINTPHASE6, temp, SBI_ICLK);
4029
4030         /* Program SSCAUXDIV */
4031         temp = intel_sbi_read(dev_priv, SBI_SSCAUXDIV6, SBI_ICLK);
4032         temp &= ~SBI_SSCAUXDIV_FINALDIV2SEL(1);
4033         temp |= SBI_SSCAUXDIV_FINALDIV2SEL(auxdiv);
4034         intel_sbi_write(dev_priv, SBI_SSCAUXDIV6, temp, SBI_ICLK);
4035
4036         /* Enable modulator and associated divider */
4037         temp = intel_sbi_read(dev_priv, SBI_SSCCTL6, SBI_ICLK);
4038         temp &= ~SBI_SSCCTL_DISABLE;
4039         intel_sbi_write(dev_priv, SBI_SSCCTL6, temp, SBI_ICLK);
4040
4041         mutex_unlock(&dev_priv->sb_lock);
4042
4043         /* Wait for initialization time */
4044         udelay(24);
4045
4046         I915_WRITE(PIXCLK_GATE, PIXCLK_GATE_UNGATE);
4047 }
4048
4049 static void ironlake_pch_transcoder_set_timings(struct intel_crtc *crtc,
4050                                                 enum pipe pch_transcoder)
4051 {
4052         struct drm_device *dev = crtc->base.dev;
4053         struct drm_i915_private *dev_priv = dev->dev_private;
4054         enum transcoder cpu_transcoder = crtc->config->cpu_transcoder;
4055
4056         I915_WRITE(PCH_TRANS_HTOTAL(pch_transcoder),
4057                    I915_READ(HTOTAL(cpu_transcoder)));
4058         I915_WRITE(PCH_TRANS_HBLANK(pch_transcoder),
4059                    I915_READ(HBLANK(cpu_transcoder)));
4060         I915_WRITE(PCH_TRANS_HSYNC(pch_transcoder),
4061                    I915_READ(HSYNC(cpu_transcoder)));
4062
4063         I915_WRITE(PCH_TRANS_VTOTAL(pch_transcoder),
4064                    I915_READ(VTOTAL(cpu_transcoder)));
4065         I915_WRITE(PCH_TRANS_VBLANK(pch_transcoder),
4066                    I915_READ(VBLANK(cpu_transcoder)));
4067         I915_WRITE(PCH_TRANS_VSYNC(pch_transcoder),
4068                    I915_READ(VSYNC(cpu_transcoder)));
4069         I915_WRITE(PCH_TRANS_VSYNCSHIFT(pch_transcoder),
4070                    I915_READ(VSYNCSHIFT(cpu_transcoder)));
4071 }
4072
4073 static void cpt_set_fdi_bc_bifurcation(struct drm_device *dev, bool enable)
4074 {
4075         struct drm_i915_private *dev_priv = dev->dev_private;
4076         uint32_t temp;
4077
4078         temp = I915_READ(SOUTH_CHICKEN1);
4079         if (!!(temp & FDI_BC_BIFURCATION_SELECT) == enable)
4080                 return;
4081
4082         WARN_ON(I915_READ(FDI_RX_CTL(PIPE_B)) & FDI_RX_ENABLE);
4083         WARN_ON(I915_READ(FDI_RX_CTL(PIPE_C)) & FDI_RX_ENABLE);
4084
4085         temp &= ~FDI_BC_BIFURCATION_SELECT;
4086         if (enable)
4087                 temp |= FDI_BC_BIFURCATION_SELECT;
4088
4089         DRM_DEBUG_KMS("%sabling fdi C rx\n", enable ? "en" : "dis");
4090         I915_WRITE(SOUTH_CHICKEN1, temp);
4091         POSTING_READ(SOUTH_CHICKEN1);
4092 }
4093
4094 static void ivybridge_update_fdi_bc_bifurcation(struct intel_crtc *intel_crtc)
4095 {
4096         struct drm_device *dev = intel_crtc->base.dev;
4097
4098         switch (intel_crtc->pipe) {
4099         case PIPE_A:
4100                 break;
4101         case PIPE_B:
4102                 if (intel_crtc->config->fdi_lanes > 2)
4103                         cpt_set_fdi_bc_bifurcation(dev, false);
4104                 else
4105                         cpt_set_fdi_bc_bifurcation(dev, true);
4106
4107                 break;
4108         case PIPE_C:
4109                 cpt_set_fdi_bc_bifurcation(dev, true);
4110
4111                 break;
4112         default:
4113                 BUG();
4114         }
4115 }
4116
4117 /* Return which DP Port should be selected for Transcoder DP control */
4118 static enum port
4119 intel_trans_dp_port_sel(struct drm_crtc *crtc)
4120 {
4121         struct drm_device *dev = crtc->dev;
4122         struct intel_encoder *encoder;
4123
4124         for_each_encoder_on_crtc(dev, crtc, encoder) {
4125                 if (encoder->type == INTEL_OUTPUT_DISPLAYPORT ||
4126                     encoder->type == INTEL_OUTPUT_EDP)
4127                         return enc_to_dig_port(&encoder->base)->port;
4128         }
4129
4130         return -1;
4131 }
4132
4133 /*
4134  * Enable PCH resources required for PCH ports:
4135  *   - PCH PLLs
4136  *   - FDI training & RX/TX
4137  *   - update transcoder timings
4138  *   - DP transcoding bits
4139  *   - transcoder
4140  */
4141 static void ironlake_pch_enable(struct drm_crtc *crtc)
4142 {
4143         struct drm_device *dev = crtc->dev;
4144         struct drm_i915_private *dev_priv = dev->dev_private;
4145         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4146         int pipe = intel_crtc->pipe;
4147         u32 temp;
4148
4149         assert_pch_transcoder_disabled(dev_priv, pipe);
4150
4151         if (IS_IVYBRIDGE(dev))
4152                 ivybridge_update_fdi_bc_bifurcation(intel_crtc);
4153
4154         /* Write the TU size bits before fdi link training, so that error
4155          * detection works. */
4156         I915_WRITE(FDI_RX_TUSIZE1(pipe),
4157                    I915_READ(PIPE_DATA_M1(pipe)) & TU_SIZE_MASK);
4158
4159         /*
4160          * Sometimes spurious CPU pipe underruns happen during FDI
4161          * training, at least with VGA+HDMI cloning. Suppress them.
4162          */
4163         intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, false);
4164
4165         /* For PCH output, training FDI link */
4166         dev_priv->display.fdi_link_train(crtc);
4167
4168         /* We need to program the right clock selection before writing the pixel
4169          * mutliplier into the DPLL. */
4170         if (HAS_PCH_CPT(dev)) {
4171                 u32 sel;
4172
4173                 temp = I915_READ(PCH_DPLL_SEL);
4174                 temp |= TRANS_DPLL_ENABLE(pipe);
4175                 sel = TRANS_DPLLB_SEL(pipe);
4176                 if (intel_crtc->config->shared_dpll == DPLL_ID_PCH_PLL_B)
4177                         temp |= sel;
4178                 else
4179                         temp &= ~sel;
4180                 I915_WRITE(PCH_DPLL_SEL, temp);
4181         }
4182
4183         /* XXX: pch pll's can be enabled any time before we enable the PCH
4184          * transcoder, and we actually should do this to not upset any PCH
4185          * transcoder that already use the clock when we share it.
4186          *
4187          * Note that enable_shared_dpll tries to do the right thing, but
4188          * get_shared_dpll unconditionally resets the pll - we need that to have
4189          * the right LVDS enable sequence. */
4190         intel_enable_shared_dpll(intel_crtc);
4191
4192         /* set transcoder timing, panel must allow it */
4193         assert_panel_unlocked(dev_priv, pipe);
4194         ironlake_pch_transcoder_set_timings(intel_crtc, pipe);
4195
4196         intel_fdi_normal_train(crtc);
4197
4198         intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
4199
4200         /* For PCH DP, enable TRANS_DP_CTL */
4201         if (HAS_PCH_CPT(dev) && intel_crtc->config->has_dp_encoder) {
4202                 const struct drm_display_mode *adjusted_mode =
4203                         &intel_crtc->config->base.adjusted_mode;
4204                 u32 bpc = (I915_READ(PIPECONF(pipe)) & PIPECONF_BPC_MASK) >> 5;
4205                 i915_reg_t reg = TRANS_DP_CTL(pipe);
4206                 temp = I915_READ(reg);
4207                 temp &= ~(TRANS_DP_PORT_SEL_MASK |
4208                           TRANS_DP_SYNC_MASK |
4209                           TRANS_DP_BPC_MASK);
4210                 temp |= TRANS_DP_OUTPUT_ENABLE;
4211                 temp |= bpc << 9; /* same format but at 11:9 */
4212
4213                 if (adjusted_mode->flags & DRM_MODE_FLAG_PHSYNC)
4214                         temp |= TRANS_DP_HSYNC_ACTIVE_HIGH;
4215                 if (adjusted_mode->flags & DRM_MODE_FLAG_PVSYNC)
4216                         temp |= TRANS_DP_VSYNC_ACTIVE_HIGH;
4217
4218                 switch (intel_trans_dp_port_sel(crtc)) {
4219                 case PORT_B:
4220                         temp |= TRANS_DP_PORT_SEL_B;
4221                         break;
4222                 case PORT_C:
4223                         temp |= TRANS_DP_PORT_SEL_C;
4224                         break;
4225                 case PORT_D:
4226                         temp |= TRANS_DP_PORT_SEL_D;
4227                         break;
4228                 default:
4229                         BUG();
4230                 }
4231
4232                 I915_WRITE(reg, temp);
4233         }
4234
4235         ironlake_enable_pch_transcoder(dev_priv, pipe);
4236 }
4237
4238 static void lpt_pch_enable(struct drm_crtc *crtc)
4239 {
4240         struct drm_device *dev = crtc->dev;
4241         struct drm_i915_private *dev_priv = dev->dev_private;
4242         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4243         enum transcoder cpu_transcoder = intel_crtc->config->cpu_transcoder;
4244
4245         assert_pch_transcoder_disabled(dev_priv, TRANSCODER_A);
4246
4247         lpt_program_iclkip(crtc);
4248
4249         /* Set transcoder timing. */
4250         ironlake_pch_transcoder_set_timings(intel_crtc, PIPE_A);
4251
4252         lpt_enable_pch_transcoder(dev_priv, cpu_transcoder);
4253 }
4254
4255 struct intel_shared_dpll *intel_get_shared_dpll(struct intel_crtc *crtc,
4256                                                 struct intel_crtc_state *crtc_state)
4257 {
4258         struct drm_i915_private *dev_priv = crtc->base.dev->dev_private;
4259         struct intel_shared_dpll *pll;
4260         struct intel_shared_dpll_config *shared_dpll;
4261         enum intel_dpll_id i;
4262         int max = dev_priv->num_shared_dpll;
4263
4264         shared_dpll = intel_atomic_get_shared_dpll_state(crtc_state->base.state);
4265
4266         if (HAS_PCH_IBX(dev_priv->dev)) {
4267                 /* Ironlake PCH has a fixed PLL->PCH pipe mapping. */
4268                 i = (enum intel_dpll_id) crtc->pipe;
4269                 pll = &dev_priv->shared_dplls[i];
4270
4271                 DRM_DEBUG_KMS("CRTC:%d using pre-allocated %s\n",
4272                               crtc->base.base.id, pll->name);
4273
4274                 WARN_ON(shared_dpll[i].crtc_mask);
4275
4276                 goto found;
4277         }
4278
4279         if (IS_BROXTON(dev_priv->dev)) {
4280                 /* PLL is attached to port in bxt */
4281                 struct intel_encoder *encoder;
4282                 struct intel_digital_port *intel_dig_port;
4283
4284                 encoder = intel_ddi_get_crtc_new_encoder(crtc_state);
4285                 if (WARN_ON(!encoder))
4286                         return NULL;
4287
4288                 intel_dig_port = enc_to_dig_port(&encoder->base);
4289                 /* 1:1 mapping between ports and PLLs */
4290                 i = (enum intel_dpll_id)intel_dig_port->port;
4291                 pll = &dev_priv->shared_dplls[i];
4292                 DRM_DEBUG_KMS("CRTC:%d using pre-allocated %s\n",
4293                         crtc->base.base.id, pll->name);
4294                 WARN_ON(shared_dpll[i].crtc_mask);
4295
4296                 goto found;
4297         } else if (INTEL_INFO(dev_priv)->gen < 9 && HAS_DDI(dev_priv))
4298                 /* Do not consider SPLL */
4299                 max = 2;
4300
4301         for (i = 0; i < max; i++) {
4302                 pll = &dev_priv->shared_dplls[i];
4303
4304                 /* Only want to check enabled timings first */
4305                 if (shared_dpll[i].crtc_mask == 0)
4306                         continue;
4307
4308                 if (memcmp(&crtc_state->dpll_hw_state,
4309                            &shared_dpll[i].hw_state,
4310                            sizeof(crtc_state->dpll_hw_state)) == 0) {
4311                         DRM_DEBUG_KMS("CRTC:%d sharing existing %s (crtc mask 0x%08x, ative %d)\n",
4312                                       crtc->base.base.id, pll->name,
4313                                       shared_dpll[i].crtc_mask,
4314                                       pll->active);
4315                         goto found;
4316                 }
4317         }
4318
4319         /* Ok no matching timings, maybe there's a free one? */
4320         for (i = 0; i < dev_priv->num_shared_dpll; i++) {
4321                 pll = &dev_priv->shared_dplls[i];
4322                 if (shared_dpll[i].crtc_mask == 0) {
4323                         DRM_DEBUG_KMS("CRTC:%d allocated %s\n",
4324                                       crtc->base.base.id, pll->name);
4325                         goto found;
4326                 }
4327         }
4328
4329         return NULL;
4330
4331 found:
4332         if (shared_dpll[i].crtc_mask == 0)
4333                 shared_dpll[i].hw_state =
4334                         crtc_state->dpll_hw_state;
4335
4336         crtc_state->shared_dpll = i;
4337         DRM_DEBUG_DRIVER("using %s for pipe %c\n", pll->name,
4338                          pipe_name(crtc->pipe));
4339
4340         shared_dpll[i].crtc_mask |= 1 << crtc->pipe;
4341
4342         return pll;
4343 }
4344
4345 static void intel_shared_dpll_commit(struct drm_atomic_state *state)
4346 {
4347         struct drm_i915_private *dev_priv = to_i915(state->dev);
4348         struct intel_shared_dpll_config *shared_dpll;
4349         struct intel_shared_dpll *pll;
4350         enum intel_dpll_id i;
4351
4352         if (!to_intel_atomic_state(state)->dpll_set)
4353                 return;
4354
4355         shared_dpll = to_intel_atomic_state(state)->shared_dpll;
4356         for (i = 0; i < dev_priv->num_shared_dpll; i++) {
4357                 pll = &dev_priv->shared_dplls[i];
4358                 pll->config = shared_dpll[i];
4359         }
4360 }
4361
4362 static void cpt_verify_modeset(struct drm_device *dev, int pipe)
4363 {
4364         struct drm_i915_private *dev_priv = dev->dev_private;
4365         i915_reg_t dslreg = PIPEDSL(pipe);
4366         u32 temp;
4367
4368         temp = I915_READ(dslreg);
4369         udelay(500);
4370         if (wait_for(I915_READ(dslreg) != temp, 5)) {
4371                 if (wait_for(I915_READ(dslreg) != temp, 5))
4372                         DRM_ERROR("mode set failed: pipe %c stuck\n", pipe_name(pipe));
4373         }
4374 }
4375
4376 static int
4377 skl_update_scaler(struct intel_crtc_state *crtc_state, bool force_detach,
4378                   unsigned scaler_user, int *scaler_id, unsigned int rotation,
4379                   int src_w, int src_h, int dst_w, int dst_h)
4380 {
4381         struct intel_crtc_scaler_state *scaler_state =
4382                 &crtc_state->scaler_state;
4383         struct intel_crtc *intel_crtc =
4384                 to_intel_crtc(crtc_state->base.crtc);
4385         int need_scaling;
4386
4387         need_scaling = intel_rotation_90_or_270(rotation) ?
4388                 (src_h != dst_w || src_w != dst_h):
4389                 (src_w != dst_w || src_h != dst_h);
4390
4391         /*
4392          * if plane is being disabled or scaler is no more required or force detach
4393          *  - free scaler binded to this plane/crtc
4394          *  - in order to do this, update crtc->scaler_usage
4395          *
4396          * Here scaler state in crtc_state is set free so that
4397          * scaler can be assigned to other user. Actual register
4398          * update to free the scaler is done in plane/panel-fit programming.
4399          * For this purpose crtc/plane_state->scaler_id isn't reset here.
4400          */
4401         if (force_detach || !need_scaling) {
4402                 if (*scaler_id >= 0) {
4403                         scaler_state->scaler_users &= ~(1 << scaler_user);
4404                         scaler_state->scalers[*scaler_id].in_use = 0;
4405
4406                         DRM_DEBUG_KMS("scaler_user index %u.%u: "
4407                                 "Staged freeing scaler id %d scaler_users = 0x%x\n",
4408                                 intel_crtc->pipe, scaler_user, *scaler_id,
4409                                 scaler_state->scaler_users);
4410                         *scaler_id = -1;
4411                 }
4412                 return 0;
4413         }
4414
4415         /* range checks */
4416         if (src_w < SKL_MIN_SRC_W || src_h < SKL_MIN_SRC_H ||
4417                 dst_w < SKL_MIN_DST_W || dst_h < SKL_MIN_DST_H ||
4418
4419                 src_w > SKL_MAX_SRC_W || src_h > SKL_MAX_SRC_H ||
4420                 dst_w > SKL_MAX_DST_W || dst_h > SKL_MAX_DST_H) {
4421                 DRM_DEBUG_KMS("scaler_user index %u.%u: src %ux%u dst %ux%u "
4422                         "size is out of scaler range\n",
4423                         intel_crtc->pipe, scaler_user, src_w, src_h, dst_w, dst_h);
4424                 return -EINVAL;
4425         }
4426
4427         /* mark this plane as a scaler user in crtc_state */
4428         scaler_state->scaler_users |= (1 << scaler_user);
4429         DRM_DEBUG_KMS("scaler_user index %u.%u: "
4430                 "staged scaling request for %ux%u->%ux%u scaler_users = 0x%x\n",
4431                 intel_crtc->pipe, scaler_user, src_w, src_h, dst_w, dst_h,
4432                 scaler_state->scaler_users);
4433
4434         return 0;
4435 }
4436
4437 /**
4438  * skl_update_scaler_crtc - Stages update to scaler state for a given crtc.
4439  *
4440  * @state: crtc's scaler state
4441  *
4442  * Return
4443  *     0 - scaler_usage updated successfully
4444  *    error - requested scaling cannot be supported or other error condition
4445  */
4446 int skl_update_scaler_crtc(struct intel_crtc_state *state)
4447 {
4448         struct intel_crtc *intel_crtc = to_intel_crtc(state->base.crtc);
4449         const struct drm_display_mode *adjusted_mode = &state->base.adjusted_mode;
4450
4451         DRM_DEBUG_KMS("Updating scaler for [CRTC:%i] scaler_user index %u.%u\n",
4452                       intel_crtc->base.base.id, intel_crtc->pipe, SKL_CRTC_INDEX);
4453
4454         return skl_update_scaler(state, !state->base.active, SKL_CRTC_INDEX,
4455                 &state->scaler_state.scaler_id, DRM_ROTATE_0,
4456                 state->pipe_src_w, state->pipe_src_h,
4457                 adjusted_mode->crtc_hdisplay, adjusted_mode->crtc_vdisplay);
4458 }
4459
4460 /**
4461  * skl_update_scaler_plane - Stages update to scaler state for a given plane.
4462  *
4463  * @state: crtc's scaler state
4464  * @plane_state: atomic plane state to update
4465  *
4466  * Return
4467  *     0 - scaler_usage updated successfully
4468  *    error - requested scaling cannot be supported or other error condition
4469  */
4470 static int skl_update_scaler_plane(struct intel_crtc_state *crtc_state,
4471                                    struct intel_plane_state *plane_state)
4472 {
4473
4474         struct intel_crtc *intel_crtc = to_intel_crtc(crtc_state->base.crtc);
4475         struct intel_plane *intel_plane =
4476                 to_intel_plane(plane_state->base.plane);
4477         struct drm_framebuffer *fb = plane_state->base.fb;
4478         int ret;
4479
4480         bool force_detach = !fb || !plane_state->visible;
4481
4482         DRM_DEBUG_KMS("Updating scaler for [PLANE:%d] scaler_user index %u.%u\n",
4483                       intel_plane->base.base.id, intel_crtc->pipe,
4484                       drm_plane_index(&intel_plane->base));
4485
4486         ret = skl_update_scaler(crtc_state, force_detach,
4487                                 drm_plane_index(&intel_plane->base),
4488                                 &plane_state->scaler_id,
4489                                 plane_state->base.rotation,
4490                                 drm_rect_width(&plane_state->src) >> 16,
4491                                 drm_rect_height(&plane_state->src) >> 16,
4492                                 drm_rect_width(&plane_state->dst),
4493                                 drm_rect_height(&plane_state->dst));
4494
4495         if (ret || plane_state->scaler_id < 0)
4496                 return ret;
4497
4498         /* check colorkey */
4499         if (plane_state->ckey.flags != I915_SET_COLORKEY_NONE) {
4500                 DRM_DEBUG_KMS("[PLANE:%d] scaling with color key not allowed",
4501                               intel_plane->base.base.id);
4502                 return -EINVAL;
4503         }
4504
4505         /* Check src format */
4506         switch (fb->pixel_format) {
4507         case DRM_FORMAT_RGB565:
4508         case DRM_FORMAT_XBGR8888:
4509         case DRM_FORMAT_XRGB8888:
4510         case DRM_FORMAT_ABGR8888:
4511         case DRM_FORMAT_ARGB8888:
4512         case DRM_FORMAT_XRGB2101010:
4513         case DRM_FORMAT_XBGR2101010:
4514         case DRM_FORMAT_YUYV:
4515         case DRM_FORMAT_YVYU:
4516         case DRM_FORMAT_UYVY:
4517         case DRM_FORMAT_VYUY:
4518                 break;
4519         default:
4520                 DRM_DEBUG_KMS("[PLANE:%d] FB:%d unsupported scaling format 0x%x\n",
4521                         intel_plane->base.base.id, fb->base.id, fb->pixel_format);
4522                 return -EINVAL;
4523         }
4524
4525         return 0;
4526 }
4527
4528 static void skylake_scaler_disable(struct intel_crtc *crtc)
4529 {
4530         int i;
4531
4532         for (i = 0; i < crtc->num_scalers; i++)
4533                 skl_detach_scaler(crtc, i);
4534 }
4535
4536 static void skylake_pfit_enable(struct intel_crtc *crtc)
4537 {
4538         struct drm_device *dev = crtc->base.dev;
4539         struct drm_i915_private *dev_priv = dev->dev_private;
4540         int pipe = crtc->pipe;
4541         struct intel_crtc_scaler_state *scaler_state =
4542                 &crtc->config->scaler_state;
4543
4544         DRM_DEBUG_KMS("for crtc_state = %p\n", crtc->config);
4545
4546         if (crtc->config->pch_pfit.enabled) {
4547                 int id;
4548
4549                 if (WARN_ON(crtc->config->scaler_state.scaler_id < 0)) {
4550                         DRM_ERROR("Requesting pfit without getting a scaler first\n");
4551                         return;
4552                 }
4553
4554                 id = scaler_state->scaler_id;
4555                 I915_WRITE(SKL_PS_CTRL(pipe, id), PS_SCALER_EN |
4556                         PS_FILTER_MEDIUM | scaler_state->scalers[id].mode);
4557                 I915_WRITE(SKL_PS_WIN_POS(pipe, id), crtc->config->pch_pfit.pos);
4558                 I915_WRITE(SKL_PS_WIN_SZ(pipe, id), crtc->config->pch_pfit.size);
4559
4560                 DRM_DEBUG_KMS("for crtc_state = %p scaler_id = %d\n", crtc->config, id);
4561         }
4562 }
4563
4564 static void ironlake_pfit_enable(struct intel_crtc *crtc)
4565 {
4566         struct drm_device *dev = crtc->base.dev;
4567         struct drm_i915_private *dev_priv = dev->dev_private;
4568         int pipe = crtc->pipe;
4569
4570         if (crtc->config->pch_pfit.enabled) {
4571                 /* Force use of hard-coded filter coefficients
4572                  * as some pre-programmed values are broken,
4573                  * e.g. x201.
4574                  */
4575                 if (IS_IVYBRIDGE(dev) || IS_HASWELL(dev))
4576                         I915_WRITE(PF_CTL(pipe), PF_ENABLE | PF_FILTER_MED_3x3 |
4577                                                  PF_PIPE_SEL_IVB(pipe));
4578                 else
4579                         I915_WRITE(PF_CTL(pipe), PF_ENABLE | PF_FILTER_MED_3x3);
4580                 I915_WRITE(PF_WIN_POS(pipe), crtc->config->pch_pfit.pos);
4581                 I915_WRITE(PF_WIN_SZ(pipe), crtc->config->pch_pfit.size);
4582         }
4583 }
4584
4585 void hsw_enable_ips(struct intel_crtc *crtc)
4586 {
4587         struct drm_device *dev = crtc->base.dev;
4588         struct drm_i915_private *dev_priv = dev->dev_private;
4589
4590         if (!crtc->config->ips_enabled)
4591                 return;
4592
4593         /* We can only enable IPS after we enable a plane and wait for a vblank */
4594         intel_wait_for_vblank(dev, crtc->pipe);
4595
4596         assert_plane_enabled(dev_priv, crtc->plane);
4597         if (IS_BROADWELL(dev)) {
4598                 mutex_lock(&dev_priv->rps.hw_lock);
4599                 WARN_ON(sandybridge_pcode_write(dev_priv, DISPLAY_IPS_CONTROL, 0xc0000000));
4600                 mutex_unlock(&dev_priv->rps.hw_lock);
4601                 /* Quoting Art Runyan: "its not safe to expect any particular
4602                  * value in IPS_CTL bit 31 after enabling IPS through the
4603                  * mailbox." Moreover, the mailbox may return a bogus state,
4604                  * so we need to just enable it and continue on.
4605                  */
4606         } else {
4607                 I915_WRITE(IPS_CTL, IPS_ENABLE);
4608                 /* The bit only becomes 1 in the next vblank, so this wait here
4609                  * is essentially intel_wait_for_vblank. If we don't have this
4610                  * and don't wait for vblanks until the end of crtc_enable, then
4611                  * the HW state readout code will complain that the expected
4612                  * IPS_CTL value is not the one we read. */
4613                 if (wait_for(I915_READ_NOTRACE(IPS_CTL) & IPS_ENABLE, 50))
4614                         DRM_ERROR("Timed out waiting for IPS enable\n");
4615         }
4616 }
4617
4618 void hsw_disable_ips(struct intel_crtc *crtc)
4619 {
4620         struct drm_device *dev = crtc->base.dev;
4621         struct drm_i915_private *dev_priv = dev->dev_private;
4622
4623         if (!crtc->config->ips_enabled)
4624                 return;
4625
4626         assert_plane_enabled(dev_priv, crtc->plane);
4627         if (IS_BROADWELL(dev)) {
4628                 mutex_lock(&dev_priv->rps.hw_lock);
4629                 WARN_ON(sandybridge_pcode_write(dev_priv, DISPLAY_IPS_CONTROL, 0));
4630                 mutex_unlock(&dev_priv->rps.hw_lock);
4631                 /* wait for pcode to finish disabling IPS, which may take up to 42ms */
4632                 if (wait_for((I915_READ(IPS_CTL) & IPS_ENABLE) == 0, 42))
4633                         DRM_ERROR("Timed out waiting for IPS disable\n");
4634         } else {
4635                 I915_WRITE(IPS_CTL, 0);
4636                 POSTING_READ(IPS_CTL);
4637         }
4638
4639         /* We need to wait for a vblank before we can disable the plane. */
4640         intel_wait_for_vblank(dev, crtc->pipe);
4641 }
4642
4643 /** Loads the palette/gamma unit for the CRTC with the prepared values */
4644 static void intel_crtc_load_lut(struct drm_crtc *crtc)
4645 {
4646         struct drm_device *dev = crtc->dev;
4647         struct drm_i915_private *dev_priv = dev->dev_private;
4648         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4649         enum pipe pipe = intel_crtc->pipe;
4650         int i;
4651         bool reenable_ips = false;
4652
4653         /* The clocks have to be on to load the palette. */
4654         if (!crtc->state->active)
4655                 return;
4656
4657         if (HAS_GMCH_DISPLAY(dev_priv->dev)) {
4658                 if (intel_crtc->config->has_dsi_encoder)
4659                         assert_dsi_pll_enabled(dev_priv);
4660                 else
4661                         assert_pll_enabled(dev_priv, pipe);
4662         }
4663
4664         /* Workaround : Do not read or write the pipe palette/gamma data while
4665          * GAMMA_MODE is configured for split gamma and IPS_CTL has IPS enabled.
4666          */
4667         if (IS_HASWELL(dev) && intel_crtc->config->ips_enabled &&
4668             ((I915_READ(GAMMA_MODE(pipe)) & GAMMA_MODE_MODE_MASK) ==
4669              GAMMA_MODE_MODE_SPLIT)) {
4670                 hsw_disable_ips(intel_crtc);
4671                 reenable_ips = true;
4672         }
4673
4674         for (i = 0; i < 256; i++) {
4675                 i915_reg_t palreg;
4676
4677                 if (HAS_GMCH_DISPLAY(dev))
4678                         palreg = PALETTE(pipe, i);
4679                 else
4680                         palreg = LGC_PALETTE(pipe, i);
4681
4682                 I915_WRITE(palreg,
4683                            (intel_crtc->lut_r[i] << 16) |
4684                            (intel_crtc->lut_g[i] << 8) |
4685                            intel_crtc->lut_b[i]);
4686         }
4687
4688         if (reenable_ips)
4689                 hsw_enable_ips(intel_crtc);
4690 }
4691
4692 static void intel_crtc_dpms_overlay_disable(struct intel_crtc *intel_crtc)
4693 {
4694         if (intel_crtc->overlay) {
4695                 struct drm_device *dev = intel_crtc->base.dev;
4696                 struct drm_i915_private *dev_priv = dev->dev_private;
4697
4698                 mutex_lock(&dev->struct_mutex);
4699                 dev_priv->mm.interruptible = false;
4700                 (void) intel_overlay_switch_off(intel_crtc->overlay);
4701                 dev_priv->mm.interruptible = true;
4702                 mutex_unlock(&dev->struct_mutex);
4703         }
4704
4705         /* Let userspace switch the overlay on again. In most cases userspace
4706          * has to recompute where to put it anyway.
4707          */
4708 }
4709
4710 /**
4711  * intel_post_enable_primary - Perform operations after enabling primary plane
4712  * @crtc: the CRTC whose primary plane was just enabled
4713  *
4714  * Performs potentially sleeping operations that must be done after the primary
4715  * plane is enabled, such as updating FBC and IPS.  Note that this may be
4716  * called due to an explicit primary plane update, or due to an implicit
4717  * re-enable that is caused when a sprite plane is updated to no longer
4718  * completely hide the primary plane.
4719  */
4720 static void
4721 intel_post_enable_primary(struct drm_crtc *crtc)
4722 {
4723         struct drm_device *dev = crtc->dev;
4724         struct drm_i915_private *dev_priv = dev->dev_private;
4725         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4726         int pipe = intel_crtc->pipe;
4727
4728         /*
4729          * FIXME IPS should be fine as long as one plane is
4730          * enabled, but in practice it seems to have problems
4731          * when going from primary only to sprite only and vice
4732          * versa.
4733          */
4734         hsw_enable_ips(intel_crtc);
4735
4736         /*
4737          * Gen2 reports pipe underruns whenever all planes are disabled.
4738          * So don't enable underrun reporting before at least some planes
4739          * are enabled.
4740          * FIXME: Need to fix the logic to work when we turn off all planes
4741          * but leave the pipe running.
4742          */
4743         if (IS_GEN2(dev))
4744                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
4745
4746         /* Underruns don't always raise interrupts, so check manually. */
4747         intel_check_cpu_fifo_underruns(dev_priv);
4748         intel_check_pch_fifo_underruns(dev_priv);
4749 }
4750
4751 /**
4752  * intel_pre_disable_primary - Perform operations before disabling primary plane
4753  * @crtc: the CRTC whose primary plane is to be disabled
4754  *
4755  * Performs potentially sleeping operations that must be done before the
4756  * primary plane is disabled, such as updating FBC and IPS.  Note that this may
4757  * be called due to an explicit primary plane update, or due to an implicit
4758  * disable that is caused when a sprite plane completely hides the primary
4759  * plane.
4760  */
4761 static void
4762 intel_pre_disable_primary(struct drm_crtc *crtc)
4763 {
4764         struct drm_device *dev = crtc->dev;
4765         struct drm_i915_private *dev_priv = dev->dev_private;
4766         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4767         int pipe = intel_crtc->pipe;
4768
4769         /*
4770          * Gen2 reports pipe underruns whenever all planes are disabled.
4771          * So diasble underrun reporting before all the planes get disabled.
4772          * FIXME: Need to fix the logic to work when we turn off all planes
4773          * but leave the pipe running.
4774          */
4775         if (IS_GEN2(dev))
4776                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, false);
4777
4778         /*
4779          * Vblank time updates from the shadow to live plane control register
4780          * are blocked if the memory self-refresh mode is active at that
4781          * moment. So to make sure the plane gets truly disabled, disable
4782          * first the self-refresh mode. The self-refresh enable bit in turn
4783          * will be checked/applied by the HW only at the next frame start
4784          * event which is after the vblank start event, so we need to have a
4785          * wait-for-vblank between disabling the plane and the pipe.
4786          */
4787         if (HAS_GMCH_DISPLAY(dev)) {
4788                 intel_set_memory_cxsr(dev_priv, false);
4789                 dev_priv->wm.vlv.cxsr = false;
4790                 intel_wait_for_vblank(dev, pipe);
4791         }
4792
4793         /*
4794          * FIXME IPS should be fine as long as one plane is
4795          * enabled, but in practice it seems to have problems
4796          * when going from primary only to sprite only and vice
4797          * versa.
4798          */
4799         hsw_disable_ips(intel_crtc);
4800 }
4801
4802 static void intel_post_plane_update(struct intel_crtc *crtc)
4803 {
4804         struct intel_crtc_atomic_commit *atomic = &crtc->atomic;
4805         struct intel_crtc_state *pipe_config =
4806                 to_intel_crtc_state(crtc->base.state);
4807         struct drm_device *dev = crtc->base.dev;
4808
4809         if (atomic->wait_vblank)
4810                 intel_wait_for_vblank(dev, crtc->pipe);
4811
4812         intel_frontbuffer_flip(dev, atomic->fb_bits);
4813
4814         crtc->wm.cxsr_allowed = true;
4815
4816         if (pipe_config->wm_changed && pipe_config->base.active)
4817                 intel_update_watermarks(&crtc->base);
4818
4819         if (atomic->update_fbc)
4820                 intel_fbc_update(crtc);
4821
4822         if (atomic->post_enable_primary)
4823                 intel_post_enable_primary(&crtc->base);
4824
4825         memset(atomic, 0, sizeof(*atomic));
4826 }
4827
4828 static void intel_pre_plane_update(struct intel_crtc *crtc)
4829 {
4830         struct drm_device *dev = crtc->base.dev;
4831         struct drm_i915_private *dev_priv = dev->dev_private;
4832         struct intel_crtc_atomic_commit *atomic = &crtc->atomic;
4833         struct intel_crtc_state *pipe_config =
4834                 to_intel_crtc_state(crtc->base.state);
4835
4836         if (atomic->disable_fbc)
4837                 intel_fbc_deactivate(crtc);
4838
4839         if (crtc->atomic.disable_ips)
4840                 hsw_disable_ips(crtc);
4841
4842         if (atomic->pre_disable_primary)
4843                 intel_pre_disable_primary(&crtc->base);
4844
4845         if (pipe_config->disable_cxsr) {
4846                 crtc->wm.cxsr_allowed = false;
4847                 intel_set_memory_cxsr(dev_priv, false);
4848         }
4849
4850         if (!needs_modeset(&pipe_config->base) && pipe_config->wm_changed)
4851                 intel_update_watermarks(&crtc->base);
4852 }
4853
4854 static void intel_crtc_disable_planes(struct drm_crtc *crtc, unsigned plane_mask)
4855 {
4856         struct drm_device *dev = crtc->dev;
4857         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4858         struct drm_plane *p;
4859         int pipe = intel_crtc->pipe;
4860
4861         intel_crtc_dpms_overlay_disable(intel_crtc);
4862
4863         drm_for_each_plane_mask(p, dev, plane_mask)
4864                 to_intel_plane(p)->disable_plane(p, crtc);
4865
4866         /*
4867          * FIXME: Once we grow proper nuclear flip support out of this we need
4868          * to compute the mask of flip planes precisely. For the time being
4869          * consider this a flip to a NULL plane.
4870          */
4871         intel_frontbuffer_flip(dev, INTEL_FRONTBUFFER_ALL_MASK(pipe));
4872 }
4873
4874 static void ironlake_crtc_enable(struct drm_crtc *crtc)
4875 {
4876         struct drm_device *dev = crtc->dev;
4877         struct drm_i915_private *dev_priv = dev->dev_private;
4878         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4879         struct intel_encoder *encoder;
4880         int pipe = intel_crtc->pipe;
4881
4882         if (WARN_ON(intel_crtc->active))
4883                 return;
4884
4885         if (intel_crtc->config->has_pch_encoder)
4886                 intel_set_pch_fifo_underrun_reporting(dev_priv, pipe, false);
4887
4888         if (intel_crtc->config->has_pch_encoder)
4889                 intel_prepare_shared_dpll(intel_crtc);
4890
4891         if (intel_crtc->config->has_dp_encoder)
4892                 intel_dp_set_m_n(intel_crtc, M1_N1);
4893
4894         intel_set_pipe_timings(intel_crtc);
4895
4896         if (intel_crtc->config->has_pch_encoder) {
4897                 intel_cpu_transcoder_set_m_n(intel_crtc,
4898                                      &intel_crtc->config->fdi_m_n, NULL);
4899         }
4900
4901         ironlake_set_pipeconf(crtc);
4902
4903         intel_crtc->active = true;
4904
4905         intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
4906
4907         for_each_encoder_on_crtc(dev, crtc, encoder)
4908                 if (encoder->pre_enable)
4909                         encoder->pre_enable(encoder);
4910
4911         if (intel_crtc->config->has_pch_encoder) {
4912                 /* Note: FDI PLL enabling _must_ be done before we enable the
4913                  * cpu pipes, hence this is separate from all the other fdi/pch
4914                  * enabling. */
4915                 ironlake_fdi_pll_enable(intel_crtc);
4916         } else {
4917                 assert_fdi_tx_disabled(dev_priv, pipe);
4918                 assert_fdi_rx_disabled(dev_priv, pipe);
4919         }
4920
4921         ironlake_pfit_enable(intel_crtc);
4922
4923         /*
4924          * On ILK+ LUT must be loaded before the pipe is running but with
4925          * clocks enabled
4926          */
4927         intel_crtc_load_lut(crtc);
4928
4929         intel_update_watermarks(crtc);
4930         intel_enable_pipe(intel_crtc);
4931
4932         if (intel_crtc->config->has_pch_encoder)
4933                 ironlake_pch_enable(crtc);
4934
4935         assert_vblank_disabled(crtc);
4936         drm_crtc_vblank_on(crtc);
4937
4938         for_each_encoder_on_crtc(dev, crtc, encoder)
4939                 encoder->enable(encoder);
4940
4941         if (HAS_PCH_CPT(dev))
4942                 cpt_verify_modeset(dev, intel_crtc->pipe);
4943
4944         /* Must wait for vblank to avoid spurious PCH FIFO underruns */
4945         if (intel_crtc->config->has_pch_encoder)
4946                 intel_wait_for_vblank(dev, pipe);
4947         intel_set_pch_fifo_underrun_reporting(dev_priv, pipe, true);
4948
4949         intel_fbc_enable(intel_crtc);
4950 }
4951
4952 /* IPS only exists on ULT machines and is tied to pipe A. */
4953 static bool hsw_crtc_supports_ips(struct intel_crtc *crtc)
4954 {
4955         return HAS_IPS(crtc->base.dev) && crtc->pipe == PIPE_A;
4956 }
4957
4958 static void haswell_crtc_enable(struct drm_crtc *crtc)
4959 {
4960         struct drm_device *dev = crtc->dev;
4961         struct drm_i915_private *dev_priv = dev->dev_private;
4962         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4963         struct intel_encoder *encoder;
4964         int pipe = intel_crtc->pipe, hsw_workaround_pipe;
4965         struct intel_crtc_state *pipe_config =
4966                 to_intel_crtc_state(crtc->state);
4967
4968         if (WARN_ON(intel_crtc->active))
4969                 return;
4970
4971         if (intel_crtc->config->has_pch_encoder)
4972                 intel_set_pch_fifo_underrun_reporting(dev_priv, TRANSCODER_A,
4973                                                       false);
4974
4975         if (intel_crtc_to_shared_dpll(intel_crtc))
4976                 intel_enable_shared_dpll(intel_crtc);
4977
4978         if (intel_crtc->config->has_dp_encoder)
4979                 intel_dp_set_m_n(intel_crtc, M1_N1);
4980
4981         intel_set_pipe_timings(intel_crtc);
4982
4983         if (intel_crtc->config->cpu_transcoder != TRANSCODER_EDP) {
4984                 I915_WRITE(PIPE_MULT(intel_crtc->config->cpu_transcoder),
4985                            intel_crtc->config->pixel_multiplier - 1);
4986         }
4987
4988         if (intel_crtc->config->has_pch_encoder) {
4989                 intel_cpu_transcoder_set_m_n(intel_crtc,
4990                                      &intel_crtc->config->fdi_m_n, NULL);
4991         }
4992
4993         haswell_set_pipeconf(crtc);
4994
4995         intel_set_pipe_csc(crtc);
4996
4997         intel_crtc->active = true;
4998
4999         if (intel_crtc->config->has_pch_encoder)
5000                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, false);
5001         else
5002                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
5003
5004         for_each_encoder_on_crtc(dev, crtc, encoder) {
5005                 if (encoder->pre_enable)
5006                         encoder->pre_enable(encoder);
5007         }
5008
5009         if (intel_crtc->config->has_pch_encoder)
5010                 dev_priv->display.fdi_link_train(crtc);
5011
5012         if (!intel_crtc->config->has_dsi_encoder)
5013                 intel_ddi_enable_pipe_clock(intel_crtc);
5014
5015         if (INTEL_INFO(dev)->gen >= 9)
5016                 skylake_pfit_enable(intel_crtc);
5017         else
5018                 ironlake_pfit_enable(intel_crtc);
5019
5020         /*
5021          * On ILK+ LUT must be loaded before the pipe is running but with
5022          * clocks enabled
5023          */
5024         intel_crtc_load_lut(crtc);
5025
5026         intel_ddi_set_pipe_settings(crtc);
5027         if (!intel_crtc->config->has_dsi_encoder)
5028                 intel_ddi_enable_transcoder_func(crtc);
5029
5030         intel_update_watermarks(crtc);
5031         intel_enable_pipe(intel_crtc);
5032
5033         if (intel_crtc->config->has_pch_encoder)
5034                 lpt_pch_enable(crtc);
5035
5036         if (intel_crtc->config->dp_encoder_is_mst)
5037                 intel_ddi_set_vc_payload_alloc(crtc, true);
5038
5039         assert_vblank_disabled(crtc);
5040         drm_crtc_vblank_on(crtc);
5041
5042         for_each_encoder_on_crtc(dev, crtc, encoder) {
5043                 encoder->enable(encoder);
5044                 intel_opregion_notify_encoder(encoder, true);
5045         }
5046
5047         if (intel_crtc->config->has_pch_encoder) {
5048                 intel_wait_for_vblank(dev, pipe);
5049                 intel_wait_for_vblank(dev, pipe);
5050                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
5051                 intel_set_pch_fifo_underrun_reporting(dev_priv, TRANSCODER_A,
5052                                                       true);
5053         }
5054
5055         /* If we change the relative order between pipe/planes enabling, we need
5056          * to change the workaround. */
5057         hsw_workaround_pipe = pipe_config->hsw_workaround_pipe;
5058         if (IS_HASWELL(dev) && hsw_workaround_pipe != INVALID_PIPE) {
5059                 intel_wait_for_vblank(dev, hsw_workaround_pipe);
5060                 intel_wait_for_vblank(dev, hsw_workaround_pipe);
5061         }
5062
5063         intel_fbc_enable(intel_crtc);
5064 }
5065
5066 static void ironlake_pfit_disable(struct intel_crtc *crtc, bool force)
5067 {
5068         struct drm_device *dev = crtc->base.dev;
5069         struct drm_i915_private *dev_priv = dev->dev_private;
5070         int pipe = crtc->pipe;
5071
5072         /* To avoid upsetting the power well on haswell only disable the pfit if
5073          * it's in use. The hw state code will make sure we get this right. */
5074         if (force || crtc->config->pch_pfit.enabled) {
5075                 I915_WRITE(PF_CTL(pipe), 0);
5076                 I915_WRITE(PF_WIN_POS(pipe), 0);
5077                 I915_WRITE(PF_WIN_SZ(pipe), 0);
5078         }
5079 }
5080
5081 static void ironlake_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         int pipe = intel_crtc->pipe;
5088
5089         if (intel_crtc->config->has_pch_encoder)
5090                 intel_set_pch_fifo_underrun_reporting(dev_priv, pipe, false);
5091
5092         for_each_encoder_on_crtc(dev, crtc, encoder)
5093                 encoder->disable(encoder);
5094
5095         drm_crtc_vblank_off(crtc);
5096         assert_vblank_disabled(crtc);
5097
5098         /*
5099          * Sometimes spurious CPU pipe underruns happen when the
5100          * pipe is already disabled, but FDI RX/TX is still enabled.
5101          * Happens at least with VGA+HDMI cloning. Suppress them.
5102          */
5103         if (intel_crtc->config->has_pch_encoder)
5104                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, false);
5105
5106         intel_disable_pipe(intel_crtc);
5107
5108         ironlake_pfit_disable(intel_crtc, false);
5109
5110         if (intel_crtc->config->has_pch_encoder) {
5111                 ironlake_fdi_disable(crtc);
5112                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
5113         }
5114
5115         for_each_encoder_on_crtc(dev, crtc, encoder)
5116                 if (encoder->post_disable)
5117                         encoder->post_disable(encoder);
5118
5119         if (intel_crtc->config->has_pch_encoder) {
5120                 ironlake_disable_pch_transcoder(dev_priv, pipe);
5121
5122                 if (HAS_PCH_CPT(dev)) {
5123                         i915_reg_t reg;
5124                         u32 temp;
5125
5126                         /* disable TRANS_DP_CTL */
5127                         reg = TRANS_DP_CTL(pipe);
5128                         temp = I915_READ(reg);
5129                         temp &= ~(TRANS_DP_OUTPUT_ENABLE |
5130                                   TRANS_DP_PORT_SEL_MASK);
5131                         temp |= TRANS_DP_PORT_SEL_NONE;
5132                         I915_WRITE(reg, temp);
5133
5134                         /* disable DPLL_SEL */
5135                         temp = I915_READ(PCH_DPLL_SEL);
5136                         temp &= ~(TRANS_DPLL_ENABLE(pipe) | TRANS_DPLLB_SEL(pipe));
5137                         I915_WRITE(PCH_DPLL_SEL, temp);
5138                 }
5139
5140                 ironlake_fdi_pll_disable(intel_crtc);
5141         }
5142
5143         intel_set_pch_fifo_underrun_reporting(dev_priv, pipe, true);
5144
5145         intel_fbc_disable_crtc(intel_crtc);
5146 }
5147
5148 static void haswell_crtc_disable(struct drm_crtc *crtc)
5149 {
5150         struct drm_device *dev = crtc->dev;
5151         struct drm_i915_private *dev_priv = dev->dev_private;
5152         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5153         struct intel_encoder *encoder;
5154         enum transcoder cpu_transcoder = intel_crtc->config->cpu_transcoder;
5155
5156         if (intel_crtc->config->has_pch_encoder)
5157                 intel_set_pch_fifo_underrun_reporting(dev_priv, TRANSCODER_A,
5158                                                       false);
5159
5160         for_each_encoder_on_crtc(dev, crtc, encoder) {
5161                 intel_opregion_notify_encoder(encoder, false);
5162                 encoder->disable(encoder);
5163         }
5164
5165         drm_crtc_vblank_off(crtc);
5166         assert_vblank_disabled(crtc);
5167
5168         intel_disable_pipe(intel_crtc);
5169
5170         if (intel_crtc->config->dp_encoder_is_mst)
5171                 intel_ddi_set_vc_payload_alloc(crtc, false);
5172
5173         if (!intel_crtc->config->has_dsi_encoder)
5174                 intel_ddi_disable_transcoder_func(dev_priv, cpu_transcoder);
5175
5176         if (INTEL_INFO(dev)->gen >= 9)
5177                 skylake_scaler_disable(intel_crtc);
5178         else
5179                 ironlake_pfit_disable(intel_crtc, false);
5180
5181         if (!intel_crtc->config->has_dsi_encoder)
5182                 intel_ddi_disable_pipe_clock(intel_crtc);
5183
5184         for_each_encoder_on_crtc(dev, crtc, encoder)
5185                 if (encoder->post_disable)
5186                         encoder->post_disable(encoder);
5187
5188         if (intel_crtc->config->has_pch_encoder) {
5189                 lpt_disable_pch_transcoder(dev_priv);
5190                 lpt_disable_iclkip(dev_priv);
5191                 intel_ddi_fdi_disable(crtc);
5192
5193                 intel_set_pch_fifo_underrun_reporting(dev_priv, TRANSCODER_A,
5194                                                       true);
5195         }
5196
5197         intel_fbc_disable_crtc(intel_crtc);
5198 }
5199
5200 static void i9xx_pfit_enable(struct intel_crtc *crtc)
5201 {
5202         struct drm_device *dev = crtc->base.dev;
5203         struct drm_i915_private *dev_priv = dev->dev_private;
5204         struct intel_crtc_state *pipe_config = crtc->config;
5205
5206         if (!pipe_config->gmch_pfit.control)
5207                 return;
5208
5209         /*
5210          * The panel fitter should only be adjusted whilst the pipe is disabled,
5211          * according to register description and PRM.
5212          */
5213         WARN_ON(I915_READ(PFIT_CONTROL) & PFIT_ENABLE);
5214         assert_pipe_disabled(dev_priv, crtc->pipe);
5215
5216         I915_WRITE(PFIT_PGM_RATIOS, pipe_config->gmch_pfit.pgm_ratios);
5217         I915_WRITE(PFIT_CONTROL, pipe_config->gmch_pfit.control);
5218
5219         /* Border color in case we don't scale up to the full screen. Black by
5220          * default, change to something else for debugging. */
5221         I915_WRITE(BCLRPAT(crtc->pipe), 0);
5222 }
5223
5224 static enum intel_display_power_domain port_to_power_domain(enum port port)
5225 {
5226         switch (port) {
5227         case PORT_A:
5228                 return POWER_DOMAIN_PORT_DDI_A_LANES;
5229         case PORT_B:
5230                 return POWER_DOMAIN_PORT_DDI_B_LANES;
5231         case PORT_C:
5232                 return POWER_DOMAIN_PORT_DDI_C_LANES;
5233         case PORT_D:
5234                 return POWER_DOMAIN_PORT_DDI_D_LANES;
5235         case PORT_E:
5236                 return POWER_DOMAIN_PORT_DDI_E_LANES;
5237         default:
5238                 MISSING_CASE(port);
5239                 return POWER_DOMAIN_PORT_OTHER;
5240         }
5241 }
5242
5243 static enum intel_display_power_domain port_to_aux_power_domain(enum port port)
5244 {
5245         switch (port) {
5246         case PORT_A:
5247                 return POWER_DOMAIN_AUX_A;
5248         case PORT_B:
5249                 return POWER_DOMAIN_AUX_B;
5250         case PORT_C:
5251                 return POWER_DOMAIN_AUX_C;
5252         case PORT_D:
5253                 return POWER_DOMAIN_AUX_D;
5254         case PORT_E:
5255                 /* FIXME: Check VBT for actual wiring of PORT E */
5256                 return POWER_DOMAIN_AUX_D;
5257         default:
5258                 MISSING_CASE(port);
5259                 return POWER_DOMAIN_AUX_A;
5260         }
5261 }
5262
5263 enum intel_display_power_domain
5264 intel_display_port_power_domain(struct intel_encoder *intel_encoder)
5265 {
5266         struct drm_device *dev = intel_encoder->base.dev;
5267         struct intel_digital_port *intel_dig_port;
5268
5269         switch (intel_encoder->type) {
5270         case INTEL_OUTPUT_UNKNOWN:
5271                 /* Only DDI platforms should ever use this output type */
5272                 WARN_ON_ONCE(!HAS_DDI(dev));
5273         case INTEL_OUTPUT_DISPLAYPORT:
5274         case INTEL_OUTPUT_HDMI:
5275         case INTEL_OUTPUT_EDP:
5276                 intel_dig_port = enc_to_dig_port(&intel_encoder->base);
5277                 return port_to_power_domain(intel_dig_port->port);
5278         case INTEL_OUTPUT_DP_MST:
5279                 intel_dig_port = enc_to_mst(&intel_encoder->base)->primary;
5280                 return port_to_power_domain(intel_dig_port->port);
5281         case INTEL_OUTPUT_ANALOG:
5282                 return POWER_DOMAIN_PORT_CRT;
5283         case INTEL_OUTPUT_DSI:
5284                 return POWER_DOMAIN_PORT_DSI;
5285         default:
5286                 return POWER_DOMAIN_PORT_OTHER;
5287         }
5288 }
5289
5290 enum intel_display_power_domain
5291 intel_display_port_aux_power_domain(struct intel_encoder *intel_encoder)
5292 {
5293         struct drm_device *dev = intel_encoder->base.dev;
5294         struct intel_digital_port *intel_dig_port;
5295
5296         switch (intel_encoder->type) {
5297         case INTEL_OUTPUT_UNKNOWN:
5298         case INTEL_OUTPUT_HDMI:
5299                 /*
5300                  * Only DDI platforms should ever use these output types.
5301                  * We can get here after the HDMI detect code has already set
5302                  * the type of the shared encoder. Since we can't be sure
5303                  * what's the status of the given connectors, play safe and
5304                  * run the DP detection too.
5305                  */
5306                 WARN_ON_ONCE(!HAS_DDI(dev));
5307         case INTEL_OUTPUT_DISPLAYPORT:
5308         case INTEL_OUTPUT_EDP:
5309                 intel_dig_port = enc_to_dig_port(&intel_encoder->base);
5310                 return port_to_aux_power_domain(intel_dig_port->port);
5311         case INTEL_OUTPUT_DP_MST:
5312                 intel_dig_port = enc_to_mst(&intel_encoder->base)->primary;
5313                 return port_to_aux_power_domain(intel_dig_port->port);
5314         default:
5315                 MISSING_CASE(intel_encoder->type);
5316                 return POWER_DOMAIN_AUX_A;
5317         }
5318 }
5319
5320 static unsigned long get_crtc_power_domains(struct drm_crtc *crtc)
5321 {
5322         struct drm_device *dev = crtc->dev;
5323         struct intel_encoder *intel_encoder;
5324         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5325         enum pipe pipe = intel_crtc->pipe;
5326         unsigned long mask;
5327         enum transcoder transcoder = intel_crtc->config->cpu_transcoder;
5328
5329         if (!crtc->state->active)
5330                 return 0;
5331
5332         mask = BIT(POWER_DOMAIN_PIPE(pipe));
5333         mask |= BIT(POWER_DOMAIN_TRANSCODER(transcoder));
5334         if (intel_crtc->config->pch_pfit.enabled ||
5335             intel_crtc->config->pch_pfit.force_thru)
5336                 mask |= BIT(POWER_DOMAIN_PIPE_PANEL_FITTER(pipe));
5337
5338         for_each_encoder_on_crtc(dev, crtc, intel_encoder)
5339                 mask |= BIT(intel_display_port_power_domain(intel_encoder));
5340
5341         return mask;
5342 }
5343
5344 static unsigned long modeset_get_crtc_power_domains(struct drm_crtc *crtc)
5345 {
5346         struct drm_i915_private *dev_priv = crtc->dev->dev_private;
5347         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5348         enum intel_display_power_domain domain;
5349         unsigned long domains, new_domains, old_domains;
5350
5351         old_domains = intel_crtc->enabled_power_domains;
5352         intel_crtc->enabled_power_domains = new_domains = get_crtc_power_domains(crtc);
5353
5354         domains = new_domains & ~old_domains;
5355
5356         for_each_power_domain(domain, domains)
5357                 intel_display_power_get(dev_priv, domain);
5358
5359         return old_domains & ~new_domains;
5360 }
5361
5362 static void modeset_put_power_domains(struct drm_i915_private *dev_priv,
5363                                       unsigned long domains)
5364 {
5365         enum intel_display_power_domain domain;
5366
5367         for_each_power_domain(domain, domains)
5368                 intel_display_power_put(dev_priv, domain);
5369 }
5370
5371 static void modeset_update_crtc_power_domains(struct drm_atomic_state *state)
5372 {
5373         struct drm_device *dev = state->dev;
5374         struct drm_i915_private *dev_priv = dev->dev_private;
5375         unsigned long put_domains[I915_MAX_PIPES] = {};
5376         struct drm_crtc_state *crtc_state;
5377         struct drm_crtc *crtc;
5378         int i;
5379
5380         for_each_crtc_in_state(state, crtc, crtc_state, i) {
5381                 if (needs_modeset(crtc->state))
5382                         put_domains[to_intel_crtc(crtc)->pipe] =
5383                                 modeset_get_crtc_power_domains(crtc);
5384         }
5385
5386         if (dev_priv->display.modeset_commit_cdclk) {
5387                 unsigned int cdclk = to_intel_atomic_state(state)->cdclk;
5388
5389                 if (cdclk != dev_priv->cdclk_freq &&
5390                     !WARN_ON(!state->allow_modeset))
5391                         dev_priv->display.modeset_commit_cdclk(state);
5392         }
5393
5394         for (i = 0; i < I915_MAX_PIPES; i++)
5395                 if (put_domains[i])
5396                         modeset_put_power_domains(dev_priv, put_domains[i]);
5397 }
5398
5399 static int intel_compute_max_dotclk(struct drm_i915_private *dev_priv)
5400 {
5401         int max_cdclk_freq = dev_priv->max_cdclk_freq;
5402
5403         if (INTEL_INFO(dev_priv)->gen >= 9 ||
5404             IS_HASWELL(dev_priv) || IS_BROADWELL(dev_priv))
5405                 return max_cdclk_freq;
5406         else if (IS_CHERRYVIEW(dev_priv))
5407                 return max_cdclk_freq*95/100;
5408         else if (INTEL_INFO(dev_priv)->gen < 4)
5409                 return 2*max_cdclk_freq*90/100;
5410         else
5411                 return max_cdclk_freq*90/100;
5412 }
5413
5414 static void intel_update_max_cdclk(struct drm_device *dev)
5415 {
5416         struct drm_i915_private *dev_priv = dev->dev_private;
5417
5418         if (IS_SKYLAKE(dev) || IS_KABYLAKE(dev)) {
5419                 u32 limit = I915_READ(SKL_DFSM) & SKL_DFSM_CDCLK_LIMIT_MASK;
5420
5421                 if (limit == SKL_DFSM_CDCLK_LIMIT_675)
5422                         dev_priv->max_cdclk_freq = 675000;
5423                 else if (limit == SKL_DFSM_CDCLK_LIMIT_540)
5424                         dev_priv->max_cdclk_freq = 540000;
5425                 else if (limit == SKL_DFSM_CDCLK_LIMIT_450)
5426                         dev_priv->max_cdclk_freq = 450000;
5427                 else
5428                         dev_priv->max_cdclk_freq = 337500;
5429         } else if (IS_BROADWELL(dev))  {
5430                 /*
5431                  * FIXME with extra cooling we can allow
5432                  * 540 MHz for ULX and 675 Mhz for ULT.
5433                  * How can we know if extra cooling is
5434                  * available? PCI ID, VTB, something else?
5435                  */
5436                 if (I915_READ(FUSE_STRAP) & HSW_CDCLK_LIMIT)
5437                         dev_priv->max_cdclk_freq = 450000;
5438                 else if (IS_BDW_ULX(dev))
5439                         dev_priv->max_cdclk_freq = 450000;
5440                 else if (IS_BDW_ULT(dev))
5441                         dev_priv->max_cdclk_freq = 540000;
5442                 else
5443                         dev_priv->max_cdclk_freq = 675000;
5444         } else if (IS_CHERRYVIEW(dev)) {
5445                 dev_priv->max_cdclk_freq = 320000;
5446         } else if (IS_VALLEYVIEW(dev)) {
5447                 dev_priv->max_cdclk_freq = 400000;
5448         } else {
5449                 /* otherwise assume cdclk is fixed */
5450                 dev_priv->max_cdclk_freq = dev_priv->cdclk_freq;
5451         }
5452
5453         dev_priv->max_dotclk_freq = intel_compute_max_dotclk(dev_priv);
5454
5455         DRM_DEBUG_DRIVER("Max CD clock rate: %d kHz\n",
5456                          dev_priv->max_cdclk_freq);
5457
5458         DRM_DEBUG_DRIVER("Max dotclock rate: %d kHz\n",
5459                          dev_priv->max_dotclk_freq);
5460 }
5461
5462 static void intel_update_cdclk(struct drm_device *dev)
5463 {
5464         struct drm_i915_private *dev_priv = dev->dev_private;
5465
5466         dev_priv->cdclk_freq = dev_priv->display.get_display_clock_speed(dev);
5467         DRM_DEBUG_DRIVER("Current CD clock rate: %d kHz\n",
5468                          dev_priv->cdclk_freq);
5469
5470         /*
5471          * Program the gmbus_freq based on the cdclk frequency.
5472          * BSpec erroneously claims we should aim for 4MHz, but
5473          * in fact 1MHz is the correct frequency.
5474          */
5475         if (IS_VALLEYVIEW(dev) || IS_CHERRYVIEW(dev)) {
5476                 /*
5477                  * Program the gmbus_freq based on the cdclk frequency.
5478                  * BSpec erroneously claims we should aim for 4MHz, but
5479                  * in fact 1MHz is the correct frequency.
5480                  */
5481                 I915_WRITE(GMBUSFREQ_VLV, DIV_ROUND_UP(dev_priv->cdclk_freq, 1000));
5482         }
5483
5484         if (dev_priv->max_cdclk_freq == 0)
5485                 intel_update_max_cdclk(dev);
5486 }
5487
5488 static void broxton_set_cdclk(struct drm_device *dev, int frequency)
5489 {
5490         struct drm_i915_private *dev_priv = dev->dev_private;
5491         uint32_t divider;
5492         uint32_t ratio;
5493         uint32_t current_freq;
5494         int ret;
5495
5496         /* frequency = 19.2MHz * ratio / 2 / div{1,1.5,2,4} */
5497         switch (frequency) {
5498         case 144000:
5499                 divider = BXT_CDCLK_CD2X_DIV_SEL_4;
5500                 ratio = BXT_DE_PLL_RATIO(60);
5501                 break;
5502         case 288000:
5503                 divider = BXT_CDCLK_CD2X_DIV_SEL_2;
5504                 ratio = BXT_DE_PLL_RATIO(60);
5505                 break;
5506         case 384000:
5507                 divider = BXT_CDCLK_CD2X_DIV_SEL_1_5;
5508                 ratio = BXT_DE_PLL_RATIO(60);
5509                 break;
5510         case 576000:
5511                 divider = BXT_CDCLK_CD2X_DIV_SEL_1;
5512                 ratio = BXT_DE_PLL_RATIO(60);
5513                 break;
5514         case 624000:
5515                 divider = BXT_CDCLK_CD2X_DIV_SEL_1;
5516                 ratio = BXT_DE_PLL_RATIO(65);
5517                 break;
5518         case 19200:
5519                 /*
5520                  * Bypass frequency with DE PLL disabled. Init ratio, divider
5521                  * to suppress GCC warning.
5522                  */
5523                 ratio = 0;
5524                 divider = 0;
5525                 break;
5526         default:
5527                 DRM_ERROR("unsupported CDCLK freq %d", frequency);
5528
5529                 return;
5530         }
5531
5532         mutex_lock(&dev_priv->rps.hw_lock);
5533         /* Inform power controller of upcoming frequency change */
5534         ret = sandybridge_pcode_write(dev_priv, HSW_PCODE_DE_WRITE_FREQ_REQ,
5535                                       0x80000000);
5536         mutex_unlock(&dev_priv->rps.hw_lock);
5537
5538         if (ret) {
5539                 DRM_ERROR("PCode CDCLK freq change notify failed (err %d, freq %d)\n",
5540                           ret, frequency);
5541                 return;
5542         }
5543
5544         current_freq = I915_READ(CDCLK_CTL) & CDCLK_FREQ_DECIMAL_MASK;
5545         /* convert from .1 fixpoint MHz with -1MHz offset to kHz */
5546         current_freq = current_freq * 500 + 1000;
5547
5548         /*
5549          * DE PLL has to be disabled when
5550          * - setting to 19.2MHz (bypass, PLL isn't used)
5551          * - before setting to 624MHz (PLL needs toggling)
5552          * - before setting to any frequency from 624MHz (PLL needs toggling)
5553          */
5554         if (frequency == 19200 || frequency == 624000 ||
5555             current_freq == 624000) {
5556                 I915_WRITE(BXT_DE_PLL_ENABLE, ~BXT_DE_PLL_PLL_ENABLE);
5557                 /* Timeout 200us */
5558                 if (wait_for(!(I915_READ(BXT_DE_PLL_ENABLE) & BXT_DE_PLL_LOCK),
5559                              1))
5560                         DRM_ERROR("timout waiting for DE PLL unlock\n");
5561         }
5562
5563         if (frequency != 19200) {
5564                 uint32_t val;
5565
5566                 val = I915_READ(BXT_DE_PLL_CTL);
5567                 val &= ~BXT_DE_PLL_RATIO_MASK;
5568                 val |= ratio;
5569                 I915_WRITE(BXT_DE_PLL_CTL, val);
5570
5571                 I915_WRITE(BXT_DE_PLL_ENABLE, BXT_DE_PLL_PLL_ENABLE);
5572                 /* Timeout 200us */
5573                 if (wait_for(I915_READ(BXT_DE_PLL_ENABLE) & BXT_DE_PLL_LOCK, 1))
5574                         DRM_ERROR("timeout waiting for DE PLL lock\n");
5575
5576                 val = I915_READ(CDCLK_CTL);
5577                 val &= ~BXT_CDCLK_CD2X_DIV_SEL_MASK;
5578                 val |= divider;
5579                 /*
5580                  * Disable SSA Precharge when CD clock frequency < 500 MHz,
5581                  * enable otherwise.
5582                  */
5583                 val &= ~BXT_CDCLK_SSA_PRECHARGE_ENABLE;
5584                 if (frequency >= 500000)
5585                         val |= BXT_CDCLK_SSA_PRECHARGE_ENABLE;
5586
5587                 val &= ~CDCLK_FREQ_DECIMAL_MASK;
5588                 /* convert from kHz to .1 fixpoint MHz with -1MHz offset */
5589                 val |= (frequency - 1000) / 500;
5590                 I915_WRITE(CDCLK_CTL, val);
5591         }
5592
5593         mutex_lock(&dev_priv->rps.hw_lock);
5594         ret = sandybridge_pcode_write(dev_priv, HSW_PCODE_DE_WRITE_FREQ_REQ,
5595                                       DIV_ROUND_UP(frequency, 25000));
5596         mutex_unlock(&dev_priv->rps.hw_lock);
5597
5598         if (ret) {
5599                 DRM_ERROR("PCode CDCLK freq set failed, (err %d, freq %d)\n",
5600                           ret, frequency);
5601                 return;
5602         }
5603
5604         intel_update_cdclk(dev);
5605 }
5606
5607 void broxton_init_cdclk(struct drm_device *dev)
5608 {
5609         struct drm_i915_private *dev_priv = dev->dev_private;
5610         uint32_t val;
5611
5612         /*
5613          * NDE_RSTWRN_OPT RST PCH Handshake En must always be 0b on BXT
5614          * or else the reset will hang because there is no PCH to respond.
5615          * Move the handshake programming to initialization sequence.
5616          * Previously was left up to BIOS.
5617          */
5618         val = I915_READ(HSW_NDE_RSTWRN_OPT);
5619         val &= ~RESET_PCH_HANDSHAKE_ENABLE;
5620         I915_WRITE(HSW_NDE_RSTWRN_OPT, val);
5621
5622         /* Enable PG1 for cdclk */
5623         intel_display_power_get(dev_priv, POWER_DOMAIN_PLLS);
5624
5625         /* check if cd clock is enabled */
5626         if (I915_READ(BXT_DE_PLL_ENABLE) & BXT_DE_PLL_PLL_ENABLE) {
5627                 DRM_DEBUG_KMS("Display already initialized\n");
5628                 return;
5629         }
5630
5631         /*
5632          * FIXME:
5633          * - The initial CDCLK needs to be read from VBT.
5634          *   Need to make this change after VBT has changes for BXT.
5635          * - check if setting the max (or any) cdclk freq is really necessary
5636          *   here, it belongs to modeset time
5637          */
5638         broxton_set_cdclk(dev, 624000);
5639
5640         I915_WRITE(DBUF_CTL, I915_READ(DBUF_CTL) | DBUF_POWER_REQUEST);
5641         POSTING_READ(DBUF_CTL);
5642
5643         udelay(10);
5644
5645         if (!(I915_READ(DBUF_CTL) & DBUF_POWER_STATE))
5646                 DRM_ERROR("DBuf power enable timeout!\n");
5647 }
5648
5649 void broxton_uninit_cdclk(struct drm_device *dev)
5650 {
5651         struct drm_i915_private *dev_priv = dev->dev_private;
5652
5653         I915_WRITE(DBUF_CTL, I915_READ(DBUF_CTL) & ~DBUF_POWER_REQUEST);
5654         POSTING_READ(DBUF_CTL);
5655
5656         udelay(10);
5657
5658         if (I915_READ(DBUF_CTL) & DBUF_POWER_STATE)
5659                 DRM_ERROR("DBuf power disable timeout!\n");
5660
5661         /* Set minimum (bypass) frequency, in effect turning off the DE PLL */
5662         broxton_set_cdclk(dev, 19200);
5663
5664         intel_display_power_put(dev_priv, POWER_DOMAIN_PLLS);
5665 }
5666
5667 static const struct skl_cdclk_entry {
5668         unsigned int freq;
5669         unsigned int vco;
5670 } skl_cdclk_frequencies[] = {
5671         { .freq = 308570, .vco = 8640 },
5672         { .freq = 337500, .vco = 8100 },
5673         { .freq = 432000, .vco = 8640 },
5674         { .freq = 450000, .vco = 8100 },
5675         { .freq = 540000, .vco = 8100 },
5676         { .freq = 617140, .vco = 8640 },
5677         { .freq = 675000, .vco = 8100 },
5678 };
5679
5680 static unsigned int skl_cdclk_decimal(unsigned int freq)
5681 {
5682         return (freq - 1000) / 500;
5683 }
5684
5685 static unsigned int skl_cdclk_get_vco(unsigned int freq)
5686 {
5687         unsigned int i;
5688
5689         for (i = 0; i < ARRAY_SIZE(skl_cdclk_frequencies); i++) {
5690                 const struct skl_cdclk_entry *e = &skl_cdclk_frequencies[i];
5691
5692                 if (e->freq == freq)
5693                         return e->vco;
5694         }
5695
5696         return 8100;
5697 }
5698
5699 static void
5700 skl_dpll0_enable(struct drm_i915_private *dev_priv, unsigned int required_vco)
5701 {
5702         unsigned int min_freq;
5703         u32 val;
5704
5705         /* select the minimum CDCLK before enabling DPLL 0 */
5706         val = I915_READ(CDCLK_CTL);
5707         val &= ~CDCLK_FREQ_SEL_MASK | ~CDCLK_FREQ_DECIMAL_MASK;
5708         val |= CDCLK_FREQ_337_308;
5709
5710         if (required_vco == 8640)
5711                 min_freq = 308570;
5712         else
5713                 min_freq = 337500;
5714
5715         val = CDCLK_FREQ_337_308 | skl_cdclk_decimal(min_freq);
5716
5717         I915_WRITE(CDCLK_CTL, val);
5718         POSTING_READ(CDCLK_CTL);
5719
5720         /*
5721          * We always enable DPLL0 with the lowest link rate possible, but still
5722          * taking into account the VCO required to operate the eDP panel at the
5723          * desired frequency. The usual DP link rates operate with a VCO of
5724          * 8100 while the eDP 1.4 alternate link rates need a VCO of 8640.
5725          * The modeset code is responsible for the selection of the exact link
5726          * rate later on, with the constraint of choosing a frequency that
5727          * works with required_vco.
5728          */
5729         val = I915_READ(DPLL_CTRL1);
5730
5731         val &= ~(DPLL_CTRL1_HDMI_MODE(SKL_DPLL0) | DPLL_CTRL1_SSC(SKL_DPLL0) |
5732                  DPLL_CTRL1_LINK_RATE_MASK(SKL_DPLL0));
5733         val |= DPLL_CTRL1_OVERRIDE(SKL_DPLL0);
5734         if (required_vco == 8640)
5735                 val |= DPLL_CTRL1_LINK_RATE(DPLL_CTRL1_LINK_RATE_1080,
5736                                             SKL_DPLL0);
5737         else
5738                 val |= DPLL_CTRL1_LINK_RATE(DPLL_CTRL1_LINK_RATE_810,
5739                                             SKL_DPLL0);
5740
5741         I915_WRITE(DPLL_CTRL1, val);
5742         POSTING_READ(DPLL_CTRL1);
5743
5744         I915_WRITE(LCPLL1_CTL, I915_READ(LCPLL1_CTL) | LCPLL_PLL_ENABLE);
5745
5746         if (wait_for(I915_READ(LCPLL1_CTL) & LCPLL_PLL_LOCK, 5))
5747                 DRM_ERROR("DPLL0 not locked\n");
5748 }
5749
5750 static bool skl_cdclk_pcu_ready(struct drm_i915_private *dev_priv)
5751 {
5752         int ret;
5753         u32 val;
5754
5755         /* inform PCU we want to change CDCLK */
5756         val = SKL_CDCLK_PREPARE_FOR_CHANGE;
5757         mutex_lock(&dev_priv->rps.hw_lock);
5758         ret = sandybridge_pcode_read(dev_priv, SKL_PCODE_CDCLK_CONTROL, &val);
5759         mutex_unlock(&dev_priv->rps.hw_lock);
5760
5761         return ret == 0 && (val & SKL_CDCLK_READY_FOR_CHANGE);
5762 }
5763
5764 static bool skl_cdclk_wait_for_pcu_ready(struct drm_i915_private *dev_priv)
5765 {
5766         unsigned int i;
5767
5768         for (i = 0; i < 15; i++) {
5769                 if (skl_cdclk_pcu_ready(dev_priv))
5770                         return true;
5771                 udelay(10);
5772         }
5773
5774         return false;
5775 }
5776
5777 static void skl_set_cdclk(struct drm_i915_private *dev_priv, unsigned int freq)
5778 {
5779         struct drm_device *dev = dev_priv->dev;
5780         u32 freq_select, pcu_ack;
5781
5782         DRM_DEBUG_DRIVER("Changing CDCLK to %dKHz\n", freq);
5783
5784         if (!skl_cdclk_wait_for_pcu_ready(dev_priv)) {
5785                 DRM_ERROR("failed to inform PCU about cdclk change\n");
5786                 return;
5787         }
5788
5789         /* set CDCLK_CTL */
5790         switch(freq) {
5791         case 450000:
5792         case 432000:
5793                 freq_select = CDCLK_FREQ_450_432;
5794                 pcu_ack = 1;
5795                 break;
5796         case 540000:
5797                 freq_select = CDCLK_FREQ_540;
5798                 pcu_ack = 2;
5799                 break;
5800         case 308570:
5801         case 337500:
5802         default:
5803                 freq_select = CDCLK_FREQ_337_308;
5804                 pcu_ack = 0;
5805                 break;
5806         case 617140:
5807         case 675000:
5808                 freq_select = CDCLK_FREQ_675_617;
5809                 pcu_ack = 3;
5810                 break;
5811         }
5812
5813         I915_WRITE(CDCLK_CTL, freq_select | skl_cdclk_decimal(freq));
5814         POSTING_READ(CDCLK_CTL);
5815
5816         /* inform PCU of the change */
5817         mutex_lock(&dev_priv->rps.hw_lock);
5818         sandybridge_pcode_write(dev_priv, SKL_PCODE_CDCLK_CONTROL, pcu_ack);
5819         mutex_unlock(&dev_priv->rps.hw_lock);
5820
5821         intel_update_cdclk(dev);
5822 }
5823
5824 void skl_uninit_cdclk(struct drm_i915_private *dev_priv)
5825 {
5826         /* disable DBUF power */
5827         I915_WRITE(DBUF_CTL, I915_READ(DBUF_CTL) & ~DBUF_POWER_REQUEST);
5828         POSTING_READ(DBUF_CTL);
5829
5830         udelay(10);
5831
5832         if (I915_READ(DBUF_CTL) & DBUF_POWER_STATE)
5833                 DRM_ERROR("DBuf power disable timeout\n");
5834
5835         /* disable DPLL0 */
5836         I915_WRITE(LCPLL1_CTL, I915_READ(LCPLL1_CTL) & ~LCPLL_PLL_ENABLE);
5837         if (wait_for(!(I915_READ(LCPLL1_CTL) & LCPLL_PLL_LOCK), 1))
5838                 DRM_ERROR("Couldn't disable DPLL0\n");
5839 }
5840
5841 void skl_init_cdclk(struct drm_i915_private *dev_priv)
5842 {
5843         unsigned int required_vco;
5844
5845         /* DPLL0 not enabled (happens on early BIOS versions) */
5846         if (!(I915_READ(LCPLL1_CTL) & LCPLL_PLL_ENABLE)) {
5847                 /* enable DPLL0 */
5848                 required_vco = skl_cdclk_get_vco(dev_priv->skl_boot_cdclk);
5849                 skl_dpll0_enable(dev_priv, required_vco);
5850         }
5851
5852         /* set CDCLK to the frequency the BIOS chose */
5853         skl_set_cdclk(dev_priv, dev_priv->skl_boot_cdclk);
5854
5855         /* enable DBUF power */
5856         I915_WRITE(DBUF_CTL, I915_READ(DBUF_CTL) | DBUF_POWER_REQUEST);
5857         POSTING_READ(DBUF_CTL);
5858
5859         udelay(10);
5860
5861         if (!(I915_READ(DBUF_CTL) & DBUF_POWER_STATE))
5862                 DRM_ERROR("DBuf power enable timeout\n");
5863 }
5864
5865 int skl_sanitize_cdclk(struct drm_i915_private *dev_priv)
5866 {
5867         uint32_t lcpll1 = I915_READ(LCPLL1_CTL);
5868         uint32_t cdctl = I915_READ(CDCLK_CTL);
5869         int freq = dev_priv->skl_boot_cdclk;
5870
5871         /*
5872          * check if the pre-os intialized the display
5873          * There is SWF18 scratchpad register defined which is set by the
5874          * pre-os which can be used by the OS drivers to check the status
5875          */
5876         if ((I915_READ(SWF_ILK(0x18)) & 0x00FFFFFF) == 0)
5877                 goto sanitize;
5878
5879         /* Is PLL enabled and locked ? */
5880         if (!((lcpll1 & LCPLL_PLL_ENABLE) && (lcpll1 & LCPLL_PLL_LOCK)))
5881                 goto sanitize;
5882
5883         /* DPLL okay; verify the cdclock
5884          *
5885          * Noticed in some instances that the freq selection is correct but
5886          * decimal part is programmed wrong from BIOS where pre-os does not
5887          * enable display. Verify the same as well.
5888          */
5889         if (cdctl == ((cdctl & CDCLK_FREQ_SEL_MASK) | skl_cdclk_decimal(freq)))
5890                 /* All well; nothing to sanitize */
5891                 return false;
5892 sanitize:
5893         /*
5894          * As of now initialize with max cdclk till
5895          * we get dynamic cdclk support
5896          * */
5897         dev_priv->skl_boot_cdclk = dev_priv->max_cdclk_freq;
5898         skl_init_cdclk(dev_priv);
5899
5900         /* we did have to sanitize */
5901         return true;
5902 }
5903
5904 /* Adjust CDclk dividers to allow high res or save power if possible */
5905 static void valleyview_set_cdclk(struct drm_device *dev, int cdclk)
5906 {
5907         struct drm_i915_private *dev_priv = dev->dev_private;
5908         u32 val, cmd;
5909
5910         WARN_ON(dev_priv->display.get_display_clock_speed(dev)
5911                                         != dev_priv->cdclk_freq);
5912
5913         if (cdclk >= 320000) /* jump to highest voltage for 400MHz too */
5914                 cmd = 2;
5915         else if (cdclk == 266667)
5916                 cmd = 1;
5917         else
5918                 cmd = 0;
5919
5920         mutex_lock(&dev_priv->rps.hw_lock);
5921         val = vlv_punit_read(dev_priv, PUNIT_REG_DSPFREQ);
5922         val &= ~DSPFREQGUAR_MASK;
5923         val |= (cmd << DSPFREQGUAR_SHIFT);
5924         vlv_punit_write(dev_priv, PUNIT_REG_DSPFREQ, val);
5925         if (wait_for((vlv_punit_read(dev_priv, PUNIT_REG_DSPFREQ) &
5926                       DSPFREQSTAT_MASK) == (cmd << DSPFREQSTAT_SHIFT),
5927                      50)) {
5928                 DRM_ERROR("timed out waiting for CDclk change\n");
5929         }
5930         mutex_unlock(&dev_priv->rps.hw_lock);
5931
5932         mutex_lock(&dev_priv->sb_lock);
5933
5934         if (cdclk == 400000) {
5935                 u32 divider;
5936
5937                 divider = DIV_ROUND_CLOSEST(dev_priv->hpll_freq << 1, cdclk) - 1;
5938
5939                 /* adjust cdclk divider */
5940                 val = vlv_cck_read(dev_priv, CCK_DISPLAY_CLOCK_CONTROL);
5941                 val &= ~CCK_FREQUENCY_VALUES;
5942                 val |= divider;
5943                 vlv_cck_write(dev_priv, CCK_DISPLAY_CLOCK_CONTROL, val);
5944
5945                 if (wait_for((vlv_cck_read(dev_priv, CCK_DISPLAY_CLOCK_CONTROL) &
5946                               CCK_FREQUENCY_STATUS) == (divider << CCK_FREQUENCY_STATUS_SHIFT),
5947                              50))
5948                         DRM_ERROR("timed out waiting for CDclk change\n");
5949         }
5950
5951         /* adjust self-refresh exit latency value */
5952         val = vlv_bunit_read(dev_priv, BUNIT_REG_BISOC);
5953         val &= ~0x7f;
5954
5955         /*
5956          * For high bandwidth configs, we set a higher latency in the bunit
5957          * so that the core display fetch happens in time to avoid underruns.
5958          */
5959         if (cdclk == 400000)
5960                 val |= 4500 / 250; /* 4.5 usec */
5961         else
5962                 val |= 3000 / 250; /* 3.0 usec */
5963         vlv_bunit_write(dev_priv, BUNIT_REG_BISOC, val);
5964
5965         mutex_unlock(&dev_priv->sb_lock);
5966
5967         intel_update_cdclk(dev);
5968 }
5969
5970 static void cherryview_set_cdclk(struct drm_device *dev, int cdclk)
5971 {
5972         struct drm_i915_private *dev_priv = dev->dev_private;
5973         u32 val, cmd;
5974
5975         WARN_ON(dev_priv->display.get_display_clock_speed(dev)
5976                                                 != dev_priv->cdclk_freq);
5977
5978         switch (cdclk) {
5979         case 333333:
5980         case 320000:
5981         case 266667:
5982         case 200000:
5983                 break;
5984         default:
5985                 MISSING_CASE(cdclk);
5986                 return;
5987         }
5988
5989         /*
5990          * Specs are full of misinformation, but testing on actual
5991          * hardware has shown that we just need to write the desired
5992          * CCK divider into the Punit register.
5993          */
5994         cmd = DIV_ROUND_CLOSEST(dev_priv->hpll_freq << 1, cdclk) - 1;
5995
5996         mutex_lock(&dev_priv->rps.hw_lock);
5997         val = vlv_punit_read(dev_priv, PUNIT_REG_DSPFREQ);
5998         val &= ~DSPFREQGUAR_MASK_CHV;
5999         val |= (cmd << DSPFREQGUAR_SHIFT_CHV);
6000         vlv_punit_write(dev_priv, PUNIT_REG_DSPFREQ, val);
6001         if (wait_for((vlv_punit_read(dev_priv, PUNIT_REG_DSPFREQ) &
6002                       DSPFREQSTAT_MASK_CHV) == (cmd << DSPFREQSTAT_SHIFT_CHV),
6003                      50)) {
6004                 DRM_ERROR("timed out waiting for CDclk change\n");
6005         }
6006         mutex_unlock(&dev_priv->rps.hw_lock);
6007
6008         intel_update_cdclk(dev);
6009 }
6010
6011 static int valleyview_calc_cdclk(struct drm_i915_private *dev_priv,
6012                                  int max_pixclk)
6013 {
6014         int freq_320 = (dev_priv->hpll_freq <<  1) % 320000 != 0 ? 333333 : 320000;
6015         int limit = IS_CHERRYVIEW(dev_priv) ? 95 : 90;
6016
6017         /*
6018          * Really only a few cases to deal with, as only 4 CDclks are supported:
6019          *   200MHz
6020          *   267MHz
6021          *   320/333MHz (depends on HPLL freq)
6022          *   400MHz (VLV only)
6023          * So we check to see whether we're above 90% (VLV) or 95% (CHV)
6024          * of the lower bin and adjust if needed.
6025          *
6026          * We seem to get an unstable or solid color picture at 200MHz.
6027          * Not sure what's wrong. For now use 200MHz only when all pipes
6028          * are off.
6029          */
6030         if (!IS_CHERRYVIEW(dev_priv) &&
6031             max_pixclk > freq_320*limit/100)
6032                 return 400000;
6033         else if (max_pixclk > 266667*limit/100)
6034                 return freq_320;
6035         else if (max_pixclk > 0)
6036                 return 266667;
6037         else
6038                 return 200000;
6039 }
6040
6041 static int broxton_calc_cdclk(struct drm_i915_private *dev_priv,
6042                               int max_pixclk)
6043 {
6044         /*
6045          * FIXME:
6046          * - remove the guardband, it's not needed on BXT
6047          * - set 19.2MHz bypass frequency if there are no active pipes
6048          */
6049         if (max_pixclk > 576000*9/10)
6050                 return 624000;
6051         else if (max_pixclk > 384000*9/10)
6052                 return 576000;
6053         else if (max_pixclk > 288000*9/10)
6054                 return 384000;
6055         else if (max_pixclk > 144000*9/10)
6056                 return 288000;
6057         else
6058                 return 144000;
6059 }
6060
6061 /* Compute the max pixel clock for new configuration. Uses atomic state if
6062  * that's non-NULL, look at current state otherwise. */
6063 static int intel_mode_max_pixclk(struct drm_device *dev,
6064                                  struct drm_atomic_state *state)
6065 {
6066         struct intel_crtc *intel_crtc;
6067         struct intel_crtc_state *crtc_state;
6068         int max_pixclk = 0;
6069
6070         for_each_intel_crtc(dev, intel_crtc) {
6071                 crtc_state = intel_atomic_get_crtc_state(state, intel_crtc);
6072                 if (IS_ERR(crtc_state))
6073                         return PTR_ERR(crtc_state);
6074
6075                 if (!crtc_state->base.enable)
6076                         continue;
6077
6078                 max_pixclk = max(max_pixclk,
6079                                  crtc_state->base.adjusted_mode.crtc_clock);
6080         }
6081
6082         return max_pixclk;
6083 }
6084
6085 static int valleyview_modeset_calc_cdclk(struct drm_atomic_state *state)
6086 {
6087         struct drm_device *dev = state->dev;
6088         struct drm_i915_private *dev_priv = dev->dev_private;
6089         int max_pixclk = intel_mode_max_pixclk(dev, state);
6090
6091         if (max_pixclk < 0)
6092                 return max_pixclk;
6093
6094         to_intel_atomic_state(state)->cdclk =
6095                 valleyview_calc_cdclk(dev_priv, max_pixclk);
6096
6097         return 0;
6098 }
6099
6100 static int broxton_modeset_calc_cdclk(struct drm_atomic_state *state)
6101 {
6102         struct drm_device *dev = state->dev;
6103         struct drm_i915_private *dev_priv = dev->dev_private;
6104         int max_pixclk = intel_mode_max_pixclk(dev, state);
6105
6106         if (max_pixclk < 0)
6107                 return max_pixclk;
6108
6109         to_intel_atomic_state(state)->cdclk =
6110                 broxton_calc_cdclk(dev_priv, max_pixclk);
6111
6112         return 0;
6113 }
6114
6115 static void vlv_program_pfi_credits(struct drm_i915_private *dev_priv)
6116 {
6117         unsigned int credits, default_credits;
6118
6119         if (IS_CHERRYVIEW(dev_priv))
6120                 default_credits = PFI_CREDIT(12);
6121         else
6122                 default_credits = PFI_CREDIT(8);
6123
6124         if (dev_priv->cdclk_freq >= dev_priv->czclk_freq) {
6125                 /* CHV suggested value is 31 or 63 */
6126                 if (IS_CHERRYVIEW(dev_priv))
6127                         credits = PFI_CREDIT_63;
6128                 else
6129                         credits = PFI_CREDIT(15);
6130         } else {
6131                 credits = default_credits;
6132         }
6133
6134         /*
6135          * WA - write default credits before re-programming
6136          * FIXME: should we also set the resend bit here?
6137          */
6138         I915_WRITE(GCI_CONTROL, VGA_FAST_MODE_DISABLE |
6139                    default_credits);
6140
6141         I915_WRITE(GCI_CONTROL, VGA_FAST_MODE_DISABLE |
6142                    credits | PFI_CREDIT_RESEND);
6143
6144         /*
6145          * FIXME is this guaranteed to clear
6146          * immediately or should we poll for it?
6147          */
6148         WARN_ON(I915_READ(GCI_CONTROL) & PFI_CREDIT_RESEND);
6149 }
6150
6151 static void valleyview_modeset_commit_cdclk(struct drm_atomic_state *old_state)
6152 {
6153         struct drm_device *dev = old_state->dev;
6154         unsigned int req_cdclk = to_intel_atomic_state(old_state)->cdclk;
6155         struct drm_i915_private *dev_priv = dev->dev_private;
6156
6157         /*
6158          * FIXME: We can end up here with all power domains off, yet
6159          * with a CDCLK frequency other than the minimum. To account
6160          * for this take the PIPE-A power domain, which covers the HW
6161          * blocks needed for the following programming. This can be
6162          * removed once it's guaranteed that we get here either with
6163          * the minimum CDCLK set, or the required power domains
6164          * enabled.
6165          */
6166         intel_display_power_get(dev_priv, POWER_DOMAIN_PIPE_A);
6167
6168         if (IS_CHERRYVIEW(dev))
6169                 cherryview_set_cdclk(dev, req_cdclk);
6170         else
6171                 valleyview_set_cdclk(dev, req_cdclk);
6172
6173         vlv_program_pfi_credits(dev_priv);
6174
6175         intel_display_power_put(dev_priv, POWER_DOMAIN_PIPE_A);
6176 }
6177
6178 static void valleyview_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         if (intel_crtc->config->has_dp_encoder)
6190                 intel_dp_set_m_n(intel_crtc, M1_N1);
6191
6192         intel_set_pipe_timings(intel_crtc);
6193
6194         if (IS_CHERRYVIEW(dev) && pipe == PIPE_B) {
6195                 struct drm_i915_private *dev_priv = dev->dev_private;
6196
6197                 I915_WRITE(CHV_BLEND(pipe), CHV_BLEND_LEGACY);
6198                 I915_WRITE(CHV_CANVAS(pipe), 0);
6199         }
6200
6201         i9xx_set_pipeconf(intel_crtc);
6202
6203         intel_crtc->active = true;
6204
6205         intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
6206
6207         for_each_encoder_on_crtc(dev, crtc, encoder)
6208                 if (encoder->pre_pll_enable)
6209                         encoder->pre_pll_enable(encoder);
6210
6211         if (!intel_crtc->config->has_dsi_encoder) {
6212                 if (IS_CHERRYVIEW(dev)) {
6213                         chv_prepare_pll(intel_crtc, intel_crtc->config);
6214                         chv_enable_pll(intel_crtc, intel_crtc->config);
6215                 } else {
6216                         vlv_prepare_pll(intel_crtc, intel_crtc->config);
6217                         vlv_enable_pll(intel_crtc, intel_crtc->config);
6218                 }
6219         }
6220
6221         for_each_encoder_on_crtc(dev, crtc, encoder)
6222                 if (encoder->pre_enable)
6223                         encoder->pre_enable(encoder);
6224
6225         i9xx_pfit_enable(intel_crtc);
6226
6227         intel_crtc_load_lut(crtc);
6228
6229         intel_enable_pipe(intel_crtc);
6230
6231         assert_vblank_disabled(crtc);
6232         drm_crtc_vblank_on(crtc);
6233
6234         for_each_encoder_on_crtc(dev, crtc, encoder)
6235                 encoder->enable(encoder);
6236 }
6237
6238 static void i9xx_set_pll_dividers(struct intel_crtc *crtc)
6239 {
6240         struct drm_device *dev = crtc->base.dev;
6241         struct drm_i915_private *dev_priv = dev->dev_private;
6242
6243         I915_WRITE(FP0(crtc->pipe), crtc->config->dpll_hw_state.fp0);
6244         I915_WRITE(FP1(crtc->pipe), crtc->config->dpll_hw_state.fp1);
6245 }
6246
6247 static void i9xx_crtc_enable(struct drm_crtc *crtc)
6248 {
6249         struct drm_device *dev = crtc->dev;
6250         struct drm_i915_private *dev_priv = to_i915(dev);
6251         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
6252         struct intel_encoder *encoder;
6253         int pipe = intel_crtc->pipe;
6254
6255         if (WARN_ON(intel_crtc->active))
6256                 return;
6257
6258         i9xx_set_pll_dividers(intel_crtc);
6259
6260         if (intel_crtc->config->has_dp_encoder)
6261                 intel_dp_set_m_n(intel_crtc, M1_N1);
6262
6263         intel_set_pipe_timings(intel_crtc);
6264
6265         i9xx_set_pipeconf(intel_crtc);
6266
6267         intel_crtc->active = true;
6268
6269         if (!IS_GEN2(dev))
6270                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
6271
6272         for_each_encoder_on_crtc(dev, crtc, encoder)
6273                 if (encoder->pre_enable)
6274                         encoder->pre_enable(encoder);
6275
6276         i9xx_enable_pll(intel_crtc);
6277
6278         i9xx_pfit_enable(intel_crtc);
6279
6280         intel_crtc_load_lut(crtc);
6281
6282         intel_update_watermarks(crtc);
6283         intel_enable_pipe(intel_crtc);
6284
6285         assert_vblank_disabled(crtc);
6286         drm_crtc_vblank_on(crtc);
6287
6288         for_each_encoder_on_crtc(dev, crtc, encoder)
6289                 encoder->enable(encoder);
6290
6291         intel_fbc_enable(intel_crtc);
6292 }
6293
6294 static void i9xx_pfit_disable(struct intel_crtc *crtc)
6295 {
6296         struct drm_device *dev = crtc->base.dev;
6297         struct drm_i915_private *dev_priv = dev->dev_private;
6298
6299         if (!crtc->config->gmch_pfit.control)
6300                 return;
6301
6302         assert_pipe_disabled(dev_priv, crtc->pipe);
6303
6304         DRM_DEBUG_DRIVER("disabling pfit, current: 0x%08x\n",
6305                          I915_READ(PFIT_CONTROL));
6306         I915_WRITE(PFIT_CONTROL, 0);
6307 }
6308
6309 static void i9xx_crtc_disable(struct drm_crtc *crtc)
6310 {
6311         struct drm_device *dev = crtc->dev;
6312         struct drm_i915_private *dev_priv = dev->dev_private;
6313         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
6314         struct intel_encoder *encoder;
6315         int pipe = intel_crtc->pipe;
6316
6317         /*
6318          * On gen2 planes are double buffered but the pipe isn't, so we must
6319          * wait for planes to fully turn off before disabling the pipe.
6320          * We also need to wait on all gmch platforms because of the
6321          * self-refresh mode constraint explained above.
6322          */
6323         intel_wait_for_vblank(dev, pipe);
6324
6325         for_each_encoder_on_crtc(dev, crtc, encoder)
6326                 encoder->disable(encoder);
6327
6328         drm_crtc_vblank_off(crtc);
6329         assert_vblank_disabled(crtc);
6330
6331         intel_disable_pipe(intel_crtc);
6332
6333         i9xx_pfit_disable(intel_crtc);
6334
6335         for_each_encoder_on_crtc(dev, crtc, encoder)
6336                 if (encoder->post_disable)
6337                         encoder->post_disable(encoder);
6338
6339         if (!intel_crtc->config->has_dsi_encoder) {
6340                 if (IS_CHERRYVIEW(dev))
6341                         chv_disable_pll(dev_priv, pipe);
6342                 else if (IS_VALLEYVIEW(dev))
6343                         vlv_disable_pll(dev_priv, pipe);
6344                 else
6345                         i9xx_disable_pll(intel_crtc);
6346         }
6347
6348         for_each_encoder_on_crtc(dev, crtc, encoder)
6349                 if (encoder->post_pll_disable)
6350                         encoder->post_pll_disable(encoder);
6351
6352         if (!IS_GEN2(dev))
6353                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, false);
6354
6355         intel_fbc_disable_crtc(intel_crtc);
6356 }
6357
6358 static void intel_crtc_disable_noatomic(struct drm_crtc *crtc)
6359 {
6360         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
6361         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
6362         enum intel_display_power_domain domain;
6363         unsigned long domains;
6364
6365         if (!intel_crtc->active)
6366                 return;
6367
6368         if (to_intel_plane_state(crtc->primary->state)->visible) {
6369                 WARN_ON(intel_crtc->unpin_work);
6370
6371                 intel_pre_disable_primary(crtc);
6372
6373                 intel_crtc_disable_planes(crtc, 1 << drm_plane_index(crtc->primary));
6374                 to_intel_plane_state(crtc->primary->state)->visible = false;
6375         }
6376
6377         dev_priv->display.crtc_disable(crtc);
6378         intel_crtc->active = false;
6379         intel_update_watermarks(crtc);
6380         intel_disable_shared_dpll(intel_crtc);
6381
6382         domains = intel_crtc->enabled_power_domains;
6383         for_each_power_domain(domain, domains)
6384                 intel_display_power_put(dev_priv, domain);
6385         intel_crtc->enabled_power_domains = 0;
6386 }
6387
6388 /*
6389  * turn all crtc's off, but do not adjust state
6390  * This has to be paired with a call to intel_modeset_setup_hw_state.
6391  */
6392 int intel_display_suspend(struct drm_device *dev)
6393 {
6394         struct drm_mode_config *config = &dev->mode_config;
6395         struct drm_modeset_acquire_ctx *ctx = config->acquire_ctx;
6396         struct drm_atomic_state *state;
6397         struct drm_crtc *crtc;
6398         unsigned crtc_mask = 0;
6399         int ret = 0;
6400
6401         if (WARN_ON(!ctx))
6402                 return 0;
6403
6404         lockdep_assert_held(&ctx->ww_ctx);
6405         state = drm_atomic_state_alloc(dev);
6406         if (WARN_ON(!state))
6407                 return -ENOMEM;
6408
6409         state->acquire_ctx = ctx;
6410         state->allow_modeset = true;
6411
6412         for_each_crtc(dev, crtc) {
6413                 struct drm_crtc_state *crtc_state =
6414                         drm_atomic_get_crtc_state(state, crtc);
6415
6416                 ret = PTR_ERR_OR_ZERO(crtc_state);
6417                 if (ret)
6418                         goto free;
6419
6420                 if (!crtc_state->active)
6421                         continue;
6422
6423                 crtc_state->active = false;
6424                 crtc_mask |= 1 << drm_crtc_index(crtc);
6425         }
6426
6427         if (crtc_mask) {
6428                 ret = drm_atomic_commit(state);
6429
6430                 if (!ret) {
6431                         for_each_crtc(dev, crtc)
6432                                 if (crtc_mask & (1 << drm_crtc_index(crtc)))
6433                                         crtc->state->active = true;
6434
6435                         return ret;
6436                 }
6437         }
6438
6439 free:
6440         if (ret)
6441                 DRM_ERROR("Suspending crtc's failed with %i\n", ret);
6442         drm_atomic_state_free(state);
6443         return ret;
6444 }
6445
6446 void intel_encoder_destroy(struct drm_encoder *encoder)
6447 {
6448         struct intel_encoder *intel_encoder = to_intel_encoder(encoder);
6449
6450         drm_encoder_cleanup(encoder);
6451         kfree(intel_encoder);
6452 }
6453
6454 /* Cross check the actual hw state with our own modeset state tracking (and it's
6455  * internal consistency). */
6456 static void intel_connector_check_state(struct intel_connector *connector)
6457 {
6458         struct drm_crtc *crtc = connector->base.state->crtc;
6459
6460         DRM_DEBUG_KMS("[CONNECTOR:%d:%s]\n",
6461                       connector->base.base.id,
6462                       connector->base.name);
6463
6464         if (connector->get_hw_state(connector)) {
6465                 struct intel_encoder *encoder = connector->encoder;
6466                 struct drm_connector_state *conn_state = connector->base.state;
6467
6468                 I915_STATE_WARN(!crtc,
6469                          "connector enabled without attached crtc\n");
6470
6471                 if (!crtc)
6472                         return;
6473
6474                 I915_STATE_WARN(!crtc->state->active,
6475                       "connector is active, but attached crtc isn't\n");
6476
6477                 if (!encoder || encoder->type == INTEL_OUTPUT_DP_MST)
6478                         return;
6479
6480                 I915_STATE_WARN(conn_state->best_encoder != &encoder->base,
6481                         "atomic encoder doesn't match attached encoder\n");
6482
6483                 I915_STATE_WARN(conn_state->crtc != encoder->base.crtc,
6484                         "attached encoder crtc differs from connector crtc\n");
6485         } else {
6486                 I915_STATE_WARN(crtc && crtc->state->active,
6487                         "attached crtc is active, but connector isn't\n");
6488                 I915_STATE_WARN(!crtc && connector->base.state->best_encoder,
6489                         "best encoder set without crtc!\n");
6490         }
6491 }
6492
6493 int intel_connector_init(struct intel_connector *connector)
6494 {
6495         struct drm_connector_state *connector_state;
6496
6497         connector_state = kzalloc(sizeof *connector_state, GFP_KERNEL);
6498         if (!connector_state)
6499                 return -ENOMEM;
6500
6501         connector->base.state = connector_state;
6502         return 0;
6503 }
6504
6505 struct intel_connector *intel_connector_alloc(void)
6506 {
6507         struct intel_connector *connector;
6508
6509         connector = kzalloc(sizeof *connector, GFP_KERNEL);
6510         if (!connector)
6511                 return NULL;
6512
6513         if (intel_connector_init(connector) < 0) {
6514                 kfree(connector);
6515                 return NULL;
6516         }
6517
6518         return connector;
6519 }
6520
6521 /* Simple connector->get_hw_state implementation for encoders that support only
6522  * one connector and no cloning and hence the encoder state determines the state
6523  * of the connector. */
6524 bool intel_connector_get_hw_state(struct intel_connector *connector)
6525 {
6526         enum pipe pipe = 0;
6527         struct intel_encoder *encoder = connector->encoder;
6528
6529         return encoder->get_hw_state(encoder, &pipe);
6530 }
6531
6532 static int pipe_required_fdi_lanes(struct intel_crtc_state *crtc_state)
6533 {
6534         if (crtc_state->base.enable && crtc_state->has_pch_encoder)
6535                 return crtc_state->fdi_lanes;
6536
6537         return 0;
6538 }
6539
6540 static int ironlake_check_fdi_lanes(struct drm_device *dev, enum pipe pipe,
6541                                      struct intel_crtc_state *pipe_config)
6542 {
6543         struct drm_atomic_state *state = pipe_config->base.state;
6544         struct intel_crtc *other_crtc;
6545         struct intel_crtc_state *other_crtc_state;
6546
6547         DRM_DEBUG_KMS("checking fdi config on pipe %c, lanes %i\n",
6548                       pipe_name(pipe), pipe_config->fdi_lanes);
6549         if (pipe_config->fdi_lanes > 4) {
6550                 DRM_DEBUG_KMS("invalid fdi lane config on pipe %c: %i lanes\n",
6551                               pipe_name(pipe), pipe_config->fdi_lanes);
6552                 return -EINVAL;
6553         }
6554
6555         if (IS_HASWELL(dev) || IS_BROADWELL(dev)) {
6556                 if (pipe_config->fdi_lanes > 2) {
6557                         DRM_DEBUG_KMS("only 2 lanes on haswell, required: %i lanes\n",
6558                                       pipe_config->fdi_lanes);
6559                         return -EINVAL;
6560                 } else {
6561                         return 0;
6562                 }
6563         }
6564
6565         if (INTEL_INFO(dev)->num_pipes == 2)
6566                 return 0;
6567
6568         /* Ivybridge 3 pipe is really complicated */
6569         switch (pipe) {
6570         case PIPE_A:
6571                 return 0;
6572         case PIPE_B:
6573                 if (pipe_config->fdi_lanes <= 2)
6574                         return 0;
6575
6576                 other_crtc = to_intel_crtc(intel_get_crtc_for_pipe(dev, PIPE_C));
6577                 other_crtc_state =
6578                         intel_atomic_get_crtc_state(state, other_crtc);
6579                 if (IS_ERR(other_crtc_state))
6580                         return PTR_ERR(other_crtc_state);
6581
6582                 if (pipe_required_fdi_lanes(other_crtc_state) > 0) {
6583                         DRM_DEBUG_KMS("invalid shared fdi lane config on pipe %c: %i lanes\n",
6584                                       pipe_name(pipe), pipe_config->fdi_lanes);
6585                         return -EINVAL;
6586                 }
6587                 return 0;
6588         case PIPE_C:
6589                 if (pipe_config->fdi_lanes > 2) {
6590                         DRM_DEBUG_KMS("only 2 lanes on pipe %c: required %i lanes\n",
6591                                       pipe_name(pipe), pipe_config->fdi_lanes);
6592                         return -EINVAL;
6593                 }
6594
6595                 other_crtc = to_intel_crtc(intel_get_crtc_for_pipe(dev, PIPE_B));
6596                 other_crtc_state =
6597                         intel_atomic_get_crtc_state(state, other_crtc);
6598                 if (IS_ERR(other_crtc_state))
6599                         return PTR_ERR(other_crtc_state);
6600
6601                 if (pipe_required_fdi_lanes(other_crtc_state) > 2) {
6602                         DRM_DEBUG_KMS("fdi link B uses too many lanes to enable link C\n");
6603                         return -EINVAL;
6604                 }
6605                 return 0;
6606         default:
6607                 BUG();
6608         }
6609 }
6610
6611 #define RETRY 1
6612 static int ironlake_fdi_compute_config(struct intel_crtc *intel_crtc,
6613                                        struct intel_crtc_state *pipe_config)
6614 {
6615         struct drm_device *dev = intel_crtc->base.dev;
6616         const struct drm_display_mode *adjusted_mode = &pipe_config->base.adjusted_mode;
6617         int lane, link_bw, fdi_dotclock, ret;
6618         bool needs_recompute = false;
6619
6620 retry:
6621         /* FDI is a binary signal running at ~2.7GHz, encoding
6622          * each output octet as 10 bits. The actual frequency
6623          * is stored as a divider into a 100MHz clock, and the
6624          * mode pixel clock is stored in units of 1KHz.
6625          * Hence the bw of each lane in terms of the mode signal
6626          * is:
6627          */
6628         link_bw = intel_fdi_link_freq(dev) * MHz(100)/KHz(1)/10;
6629
6630         fdi_dotclock = adjusted_mode->crtc_clock;
6631
6632         lane = ironlake_get_lanes_required(fdi_dotclock, link_bw,
6633                                            pipe_config->pipe_bpp);
6634
6635         pipe_config->fdi_lanes = lane;
6636
6637         intel_link_compute_m_n(pipe_config->pipe_bpp, lane, fdi_dotclock,
6638                                link_bw, &pipe_config->fdi_m_n);
6639
6640         ret = ironlake_check_fdi_lanes(intel_crtc->base.dev,
6641                                        intel_crtc->pipe, pipe_config);
6642         if (ret == -EINVAL && pipe_config->pipe_bpp > 6*3) {
6643                 pipe_config->pipe_bpp -= 2*3;
6644                 DRM_DEBUG_KMS("fdi link bw constraint, reducing pipe bpp to %i\n",
6645                               pipe_config->pipe_bpp);
6646                 needs_recompute = true;
6647                 pipe_config->bw_constrained = true;
6648
6649                 goto retry;
6650         }
6651
6652         if (needs_recompute)
6653                 return RETRY;
6654
6655         return ret;
6656 }
6657
6658 static bool pipe_config_supports_ips(struct drm_i915_private *dev_priv,
6659                                      struct intel_crtc_state *pipe_config)
6660 {
6661         if (pipe_config->pipe_bpp > 24)
6662                 return false;
6663
6664         /* HSW can handle pixel rate up to cdclk? */
6665         if (IS_HASWELL(dev_priv->dev))
6666                 return true;
6667
6668         /*
6669          * We compare against max which means we must take
6670          * the increased cdclk requirement into account when
6671          * calculating the new cdclk.
6672          *
6673          * Should measure whether using a lower cdclk w/o IPS
6674          */
6675         return ilk_pipe_pixel_rate(pipe_config) <=
6676                 dev_priv->max_cdclk_freq * 95 / 100;
6677 }
6678
6679 static void hsw_compute_ips_config(struct intel_crtc *crtc,
6680                                    struct intel_crtc_state *pipe_config)
6681 {
6682         struct drm_device *dev = crtc->base.dev;
6683         struct drm_i915_private *dev_priv = dev->dev_private;
6684
6685         pipe_config->ips_enabled = i915.enable_ips &&
6686                 hsw_crtc_supports_ips(crtc) &&
6687                 pipe_config_supports_ips(dev_priv, pipe_config);
6688 }
6689
6690 static bool intel_crtc_supports_double_wide(const struct intel_crtc *crtc)
6691 {
6692         const struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
6693
6694         /* GDG double wide on either pipe, otherwise pipe A only */
6695         return INTEL_INFO(dev_priv)->gen < 4 &&
6696                 (crtc->pipe == PIPE_A || IS_I915G(dev_priv));
6697 }
6698
6699 static int intel_crtc_compute_config(struct intel_crtc *crtc,
6700                                      struct intel_crtc_state *pipe_config)
6701 {
6702         struct drm_device *dev = crtc->base.dev;
6703         struct drm_i915_private *dev_priv = dev->dev_private;
6704         const struct drm_display_mode *adjusted_mode = &pipe_config->base.adjusted_mode;
6705
6706         /* FIXME should check pixel clock limits on all platforms */
6707         if (INTEL_INFO(dev)->gen < 4) {
6708                 int clock_limit = dev_priv->max_cdclk_freq * 9 / 10;
6709
6710                 /*
6711                  * Enable double wide mode when the dot clock
6712                  * is > 90% of the (display) core speed.
6713                  */
6714                 if (intel_crtc_supports_double_wide(crtc) &&
6715                     adjusted_mode->crtc_clock > clock_limit) {
6716                         clock_limit *= 2;
6717                         pipe_config->double_wide = true;
6718                 }
6719
6720                 if (adjusted_mode->crtc_clock > clock_limit) {
6721                         DRM_DEBUG_KMS("requested pixel clock (%d kHz) too high (max: %d kHz, double wide: %s)\n",
6722                                       adjusted_mode->crtc_clock, clock_limit,
6723                                       yesno(pipe_config->double_wide));
6724                         return -EINVAL;
6725                 }
6726         }
6727
6728         /*
6729          * Pipe horizontal size must be even in:
6730          * - DVO ganged mode
6731          * - LVDS dual channel mode
6732          * - Double wide pipe
6733          */
6734         if ((intel_pipe_will_have_type(pipe_config, INTEL_OUTPUT_LVDS) &&
6735              intel_is_dual_link_lvds(dev)) || pipe_config->double_wide)
6736                 pipe_config->pipe_src_w &= ~1;
6737
6738         /* Cantiga+ cannot handle modes with a hsync front porch of 0.
6739          * WaPruneModeWithIncorrectHsyncOffset:ctg,elk,ilk,snb,ivb,vlv,hsw.
6740          */
6741         if ((INTEL_INFO(dev)->gen > 4 || IS_G4X(dev)) &&
6742                 adjusted_mode->crtc_hsync_start == adjusted_mode->crtc_hdisplay)
6743                 return -EINVAL;
6744
6745         if (HAS_IPS(dev))
6746                 hsw_compute_ips_config(crtc, pipe_config);
6747
6748         if (pipe_config->has_pch_encoder)
6749                 return ironlake_fdi_compute_config(crtc, pipe_config);
6750
6751         return 0;
6752 }
6753
6754 static int skylake_get_display_clock_speed(struct drm_device *dev)
6755 {
6756         struct drm_i915_private *dev_priv = to_i915(dev);
6757         uint32_t lcpll1 = I915_READ(LCPLL1_CTL);
6758         uint32_t cdctl = I915_READ(CDCLK_CTL);
6759         uint32_t linkrate;
6760
6761         if (!(lcpll1 & LCPLL_PLL_ENABLE))
6762                 return 24000; /* 24MHz is the cd freq with NSSC ref */
6763
6764         if ((cdctl & CDCLK_FREQ_SEL_MASK) == CDCLK_FREQ_540)
6765                 return 540000;
6766
6767         linkrate = (I915_READ(DPLL_CTRL1) &
6768                     DPLL_CTRL1_LINK_RATE_MASK(SKL_DPLL0)) >> 1;
6769
6770         if (linkrate == DPLL_CTRL1_LINK_RATE_2160 ||
6771             linkrate == DPLL_CTRL1_LINK_RATE_1080) {
6772                 /* vco 8640 */
6773                 switch (cdctl & CDCLK_FREQ_SEL_MASK) {
6774                 case CDCLK_FREQ_450_432:
6775                         return 432000;
6776                 case CDCLK_FREQ_337_308:
6777                         return 308570;
6778                 case CDCLK_FREQ_675_617:
6779                         return 617140;
6780                 default:
6781                         WARN(1, "Unknown cd freq selection\n");
6782                 }
6783         } else {
6784                 /* vco 8100 */
6785                 switch (cdctl & CDCLK_FREQ_SEL_MASK) {
6786                 case CDCLK_FREQ_450_432:
6787                         return 450000;
6788                 case CDCLK_FREQ_337_308:
6789                         return 337500;
6790                 case CDCLK_FREQ_675_617:
6791                         return 675000;
6792                 default:
6793                         WARN(1, "Unknown cd freq selection\n");
6794                 }
6795         }
6796
6797         /* error case, do as if DPLL0 isn't enabled */
6798         return 24000;
6799 }
6800
6801 static int broxton_get_display_clock_speed(struct drm_device *dev)
6802 {
6803         struct drm_i915_private *dev_priv = to_i915(dev);
6804         uint32_t cdctl = I915_READ(CDCLK_CTL);
6805         uint32_t pll_ratio = I915_READ(BXT_DE_PLL_CTL) & BXT_DE_PLL_RATIO_MASK;
6806         uint32_t pll_enab = I915_READ(BXT_DE_PLL_ENABLE);
6807         int cdclk;
6808
6809         if (!(pll_enab & BXT_DE_PLL_PLL_ENABLE))
6810                 return 19200;
6811
6812         cdclk = 19200 * pll_ratio / 2;
6813
6814         switch (cdctl & BXT_CDCLK_CD2X_DIV_SEL_MASK) {
6815         case BXT_CDCLK_CD2X_DIV_SEL_1:
6816                 return cdclk;  /* 576MHz or 624MHz */
6817         case BXT_CDCLK_CD2X_DIV_SEL_1_5:
6818                 return cdclk * 2 / 3; /* 384MHz */
6819         case BXT_CDCLK_CD2X_DIV_SEL_2:
6820                 return cdclk / 2; /* 288MHz */
6821         case BXT_CDCLK_CD2X_DIV_SEL_4:
6822                 return cdclk / 4; /* 144MHz */
6823         }
6824
6825         /* error case, do as if DE PLL isn't enabled */
6826         return 19200;
6827 }
6828
6829 static int broadwell_get_display_clock_speed(struct drm_device *dev)
6830 {
6831         struct drm_i915_private *dev_priv = dev->dev_private;
6832         uint32_t lcpll = I915_READ(LCPLL_CTL);
6833         uint32_t freq = lcpll & LCPLL_CLK_FREQ_MASK;
6834
6835         if (lcpll & LCPLL_CD_SOURCE_FCLK)
6836                 return 800000;
6837         else if (I915_READ(FUSE_STRAP) & HSW_CDCLK_LIMIT)
6838                 return 450000;
6839         else if (freq == LCPLL_CLK_FREQ_450)
6840                 return 450000;
6841         else if (freq == LCPLL_CLK_FREQ_54O_BDW)
6842                 return 540000;
6843         else if (freq == LCPLL_CLK_FREQ_337_5_BDW)
6844                 return 337500;
6845         else
6846                 return 675000;
6847 }
6848
6849 static int haswell_get_display_clock_speed(struct drm_device *dev)
6850 {
6851         struct drm_i915_private *dev_priv = dev->dev_private;
6852         uint32_t lcpll = I915_READ(LCPLL_CTL);
6853         uint32_t freq = lcpll & LCPLL_CLK_FREQ_MASK;
6854
6855         if (lcpll & LCPLL_CD_SOURCE_FCLK)
6856                 return 800000;
6857         else if (I915_READ(FUSE_STRAP) & HSW_CDCLK_LIMIT)
6858                 return 450000;
6859         else if (freq == LCPLL_CLK_FREQ_450)
6860                 return 450000;
6861         else if (IS_HSW_ULT(dev))
6862                 return 337500;
6863         else
6864                 return 540000;
6865 }
6866
6867 static int valleyview_get_display_clock_speed(struct drm_device *dev)
6868 {
6869         return vlv_get_cck_clock_hpll(to_i915(dev), "cdclk",
6870                                       CCK_DISPLAY_CLOCK_CONTROL);
6871 }
6872
6873 static int ilk_get_display_clock_speed(struct drm_device *dev)
6874 {
6875         return 450000;
6876 }
6877
6878 static int i945_get_display_clock_speed(struct drm_device *dev)
6879 {
6880         return 400000;
6881 }
6882
6883 static int i915_get_display_clock_speed(struct drm_device *dev)
6884 {
6885         return 333333;
6886 }
6887
6888 static int i9xx_misc_get_display_clock_speed(struct drm_device *dev)
6889 {
6890         return 200000;
6891 }
6892
6893 static int pnv_get_display_clock_speed(struct drm_device *dev)
6894 {
6895         u16 gcfgc = 0;
6896
6897         pci_read_config_word(dev->pdev, GCFGC, &gcfgc);
6898
6899         switch (gcfgc & GC_DISPLAY_CLOCK_MASK) {
6900         case GC_DISPLAY_CLOCK_267_MHZ_PNV:
6901                 return 266667;
6902         case GC_DISPLAY_CLOCK_333_MHZ_PNV:
6903                 return 333333;
6904         case GC_DISPLAY_CLOCK_444_MHZ_PNV:
6905                 return 444444;
6906         case GC_DISPLAY_CLOCK_200_MHZ_PNV:
6907                 return 200000;
6908         default:
6909                 DRM_ERROR("Unknown pnv display core clock 0x%04x\n", gcfgc);
6910         case GC_DISPLAY_CLOCK_133_MHZ_PNV:
6911                 return 133333;
6912         case GC_DISPLAY_CLOCK_167_MHZ_PNV:
6913                 return 166667;
6914         }
6915 }
6916
6917 static int i915gm_get_display_clock_speed(struct drm_device *dev)
6918 {
6919         u16 gcfgc = 0;
6920
6921         pci_read_config_word(dev->pdev, GCFGC, &gcfgc);
6922
6923         if (gcfgc & GC_LOW_FREQUENCY_ENABLE)
6924                 return 133333;
6925         else {
6926                 switch (gcfgc & GC_DISPLAY_CLOCK_MASK) {
6927                 case GC_DISPLAY_CLOCK_333_MHZ:
6928                         return 333333;
6929                 default:
6930                 case GC_DISPLAY_CLOCK_190_200_MHZ:
6931                         return 190000;
6932                 }
6933         }
6934 }
6935
6936 static int i865_get_display_clock_speed(struct drm_device *dev)
6937 {
6938         return 266667;
6939 }
6940
6941 static int i85x_get_display_clock_speed(struct drm_device *dev)
6942 {
6943         u16 hpllcc = 0;
6944
6945         /*
6946          * 852GM/852GMV only supports 133 MHz and the HPLLCC
6947          * encoding is different :(
6948          * FIXME is this the right way to detect 852GM/852GMV?
6949          */
6950         if (dev->pdev->revision == 0x1)
6951                 return 133333;
6952
6953         pci_bus_read_config_word(dev->pdev->bus,
6954                                  PCI_DEVFN(0, 3), HPLLCC, &hpllcc);
6955
6956         /* Assume that the hardware is in the high speed state.  This
6957          * should be the default.
6958          */
6959         switch (hpllcc & GC_CLOCK_CONTROL_MASK) {
6960         case GC_CLOCK_133_200:
6961         case GC_CLOCK_133_200_2:
6962         case GC_CLOCK_100_200:
6963                 return 200000;
6964         case GC_CLOCK_166_250:
6965                 return 250000;
6966         case GC_CLOCK_100_133:
6967                 return 133333;
6968         case GC_CLOCK_133_266:
6969         case GC_CLOCK_133_266_2:
6970         case GC_CLOCK_166_266:
6971                 return 266667;
6972         }
6973
6974         /* Shouldn't happen */
6975         return 0;
6976 }
6977
6978 static int i830_get_display_clock_speed(struct drm_device *dev)
6979 {
6980         return 133333;
6981 }
6982
6983 static unsigned int intel_hpll_vco(struct drm_device *dev)
6984 {
6985         struct drm_i915_private *dev_priv = dev->dev_private;
6986         static const unsigned int blb_vco[8] = {
6987                 [0] = 3200000,
6988                 [1] = 4000000,
6989                 [2] = 5333333,
6990                 [3] = 4800000,
6991                 [4] = 6400000,
6992         };
6993         static const unsigned int pnv_vco[8] = {
6994                 [0] = 3200000,
6995                 [1] = 4000000,
6996                 [2] = 5333333,
6997                 [3] = 4800000,
6998                 [4] = 2666667,
6999         };
7000         static const unsigned int cl_vco[8] = {
7001                 [0] = 3200000,
7002                 [1] = 4000000,
7003                 [2] = 5333333,
7004                 [3] = 6400000,
7005                 [4] = 3333333,
7006                 [5] = 3566667,
7007                 [6] = 4266667,
7008         };
7009         static const unsigned int elk_vco[8] = {
7010                 [0] = 3200000,
7011                 [1] = 4000000,
7012                 [2] = 5333333,
7013                 [3] = 4800000,
7014         };
7015         static const unsigned int ctg_vco[8] = {
7016                 [0] = 3200000,
7017                 [1] = 4000000,
7018                 [2] = 5333333,
7019                 [3] = 6400000,
7020                 [4] = 2666667,
7021                 [5] = 4266667,
7022         };
7023         const unsigned int *vco_table;
7024         unsigned int vco;
7025         uint8_t tmp = 0;
7026
7027         /* FIXME other chipsets? */
7028         if (IS_GM45(dev))
7029                 vco_table = ctg_vco;
7030         else if (IS_G4X(dev))
7031                 vco_table = elk_vco;
7032         else if (IS_CRESTLINE(dev))
7033                 vco_table = cl_vco;
7034         else if (IS_PINEVIEW(dev))
7035                 vco_table = pnv_vco;
7036         else if (IS_G33(dev))
7037                 vco_table = blb_vco;
7038         else
7039                 return 0;
7040
7041         tmp = I915_READ(IS_MOBILE(dev) ? HPLLVCO_MOBILE : HPLLVCO);
7042
7043         vco = vco_table[tmp & 0x7];
7044         if (vco == 0)
7045                 DRM_ERROR("Bad HPLL VCO (HPLLVCO=0x%02x)\n", tmp);
7046         else
7047                 DRM_DEBUG_KMS("HPLL VCO %u kHz\n", vco);
7048
7049         return vco;
7050 }
7051
7052 static int gm45_get_display_clock_speed(struct drm_device *dev)
7053 {
7054         unsigned int cdclk_sel, vco = intel_hpll_vco(dev);
7055         uint16_t tmp = 0;
7056
7057         pci_read_config_word(dev->pdev, GCFGC, &tmp);
7058
7059         cdclk_sel = (tmp >> 12) & 0x1;
7060
7061         switch (vco) {
7062         case 2666667:
7063         case 4000000:
7064         case 5333333:
7065                 return cdclk_sel ? 333333 : 222222;
7066         case 3200000:
7067                 return cdclk_sel ? 320000 : 228571;
7068         default:
7069                 DRM_ERROR("Unable to determine CDCLK. HPLL VCO=%u, CFGC=0x%04x\n", vco, tmp);
7070                 return 222222;
7071         }
7072 }
7073
7074 static int i965gm_get_display_clock_speed(struct drm_device *dev)
7075 {
7076         static const uint8_t div_3200[] = { 16, 10,  8 };
7077         static const uint8_t div_4000[] = { 20, 12, 10 };
7078         static const uint8_t div_5333[] = { 24, 16, 14 };
7079         const uint8_t *div_table;
7080         unsigned int cdclk_sel, vco = intel_hpll_vco(dev);
7081         uint16_t tmp = 0;
7082
7083         pci_read_config_word(dev->pdev, GCFGC, &tmp);
7084
7085         cdclk_sel = ((tmp >> 8) & 0x1f) - 1;
7086
7087         if (cdclk_sel >= ARRAY_SIZE(div_3200))
7088                 goto fail;
7089
7090         switch (vco) {
7091         case 3200000:
7092                 div_table = div_3200;
7093                 break;
7094         case 4000000:
7095                 div_table = div_4000;
7096                 break;
7097         case 5333333:
7098                 div_table = div_5333;
7099                 break;
7100         default:
7101                 goto fail;
7102         }
7103
7104         return DIV_ROUND_CLOSEST(vco, div_table[cdclk_sel]);
7105
7106 fail:
7107         DRM_ERROR("Unable to determine CDCLK. HPLL VCO=%u kHz, CFGC=0x%04x\n", vco, tmp);
7108         return 200000;
7109 }
7110
7111 static int g33_get_display_clock_speed(struct drm_device *dev)
7112 {
7113         static const uint8_t div_3200[] = { 12, 10,  8,  7, 5, 16 };
7114         static const uint8_t div_4000[] = { 14, 12, 10,  8, 6, 20 };
7115         static const uint8_t div_4800[] = { 20, 14, 12, 10, 8, 24 };
7116         static const uint8_t div_5333[] = { 20, 16, 12, 12, 8, 28 };
7117         const uint8_t *div_table;
7118         unsigned int cdclk_sel, vco = intel_hpll_vco(dev);
7119         uint16_t tmp = 0;
7120
7121         pci_read_config_word(dev->pdev, GCFGC, &tmp);
7122
7123         cdclk_sel = (tmp >> 4) & 0x7;
7124
7125         if (cdclk_sel >= ARRAY_SIZE(div_3200))
7126                 goto fail;
7127
7128         switch (vco) {
7129         case 3200000:
7130                 div_table = div_3200;
7131                 break;
7132         case 4000000:
7133                 div_table = div_4000;
7134                 break;
7135         case 4800000:
7136                 div_table = div_4800;
7137                 break;
7138         case 5333333:
7139                 div_table = div_5333;
7140                 break;
7141         default:
7142                 goto fail;
7143         }
7144
7145         return DIV_ROUND_CLOSEST(vco, div_table[cdclk_sel]);
7146
7147 fail:
7148         DRM_ERROR("Unable to determine CDCLK. HPLL VCO=%u kHz, CFGC=0x%08x\n", vco, tmp);
7149         return 190476;
7150 }
7151
7152 static void
7153 intel_reduce_m_n_ratio(uint32_t *num, uint32_t *den)
7154 {
7155         while (*num > DATA_LINK_M_N_MASK ||
7156                *den > DATA_LINK_M_N_MASK) {
7157                 *num >>= 1;
7158                 *den >>= 1;
7159         }
7160 }
7161
7162 static void compute_m_n(unsigned int m, unsigned int n,
7163                         uint32_t *ret_m, uint32_t *ret_n)
7164 {
7165         *ret_n = min_t(unsigned int, roundup_pow_of_two(n), DATA_LINK_N_MAX);
7166         *ret_m = div_u64((uint64_t) m * *ret_n, n);
7167         intel_reduce_m_n_ratio(ret_m, ret_n);
7168 }
7169
7170 void
7171 intel_link_compute_m_n(int bits_per_pixel, int nlanes,
7172                        int pixel_clock, int link_clock,
7173                        struct intel_link_m_n *m_n)
7174 {
7175         m_n->tu = 64;
7176
7177         compute_m_n(bits_per_pixel * pixel_clock,
7178                     link_clock * nlanes * 8,
7179                     &m_n->gmch_m, &m_n->gmch_n);
7180
7181         compute_m_n(pixel_clock, link_clock,
7182                     &m_n->link_m, &m_n->link_n);
7183 }
7184
7185 static inline bool intel_panel_use_ssc(struct drm_i915_private *dev_priv)
7186 {
7187         if (i915.panel_use_ssc >= 0)
7188                 return i915.panel_use_ssc != 0;
7189         return dev_priv->vbt.lvds_use_ssc
7190                 && !(dev_priv->quirks & QUIRK_LVDS_SSC_DISABLE);
7191 }
7192
7193 static int i9xx_get_refclk(const struct intel_crtc_state *crtc_state,
7194                            int num_connectors)
7195 {
7196         struct drm_device *dev = crtc_state->base.crtc->dev;
7197         struct drm_i915_private *dev_priv = dev->dev_private;
7198         int refclk;
7199
7200         WARN_ON(!crtc_state->base.state);
7201
7202         if (IS_VALLEYVIEW(dev) || IS_CHERRYVIEW(dev) || IS_BROXTON(dev)) {
7203                 refclk = 100000;
7204         } else if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_LVDS) &&
7205             intel_panel_use_ssc(dev_priv) && num_connectors < 2) {
7206                 refclk = dev_priv->vbt.lvds_ssc_freq;
7207                 DRM_DEBUG_KMS("using SSC reference clock of %d kHz\n", refclk);
7208         } else if (!IS_GEN2(dev)) {
7209                 refclk = 96000;
7210         } else {
7211                 refclk = 48000;
7212         }
7213
7214         return refclk;
7215 }
7216
7217 static uint32_t pnv_dpll_compute_fp(struct dpll *dpll)
7218 {
7219         return (1 << dpll->n) << 16 | dpll->m2;
7220 }
7221
7222 static uint32_t i9xx_dpll_compute_fp(struct dpll *dpll)
7223 {
7224         return dpll->n << 16 | dpll->m1 << 8 | dpll->m2;
7225 }
7226
7227 static void i9xx_update_pll_dividers(struct intel_crtc *crtc,
7228                                      struct intel_crtc_state *crtc_state,
7229                                      intel_clock_t *reduced_clock)
7230 {
7231         struct drm_device *dev = crtc->base.dev;
7232         u32 fp, fp2 = 0;
7233
7234         if (IS_PINEVIEW(dev)) {
7235                 fp = pnv_dpll_compute_fp(&crtc_state->dpll);
7236                 if (reduced_clock)
7237                         fp2 = pnv_dpll_compute_fp(reduced_clock);
7238         } else {
7239                 fp = i9xx_dpll_compute_fp(&crtc_state->dpll);
7240                 if (reduced_clock)
7241                         fp2 = i9xx_dpll_compute_fp(reduced_clock);
7242         }
7243
7244         crtc_state->dpll_hw_state.fp0 = fp;
7245
7246         crtc->lowfreq_avail = false;
7247         if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_LVDS) &&
7248             reduced_clock) {
7249                 crtc_state->dpll_hw_state.fp1 = fp2;
7250                 crtc->lowfreq_avail = true;
7251         } else {
7252                 crtc_state->dpll_hw_state.fp1 = fp;
7253         }
7254 }
7255
7256 static void vlv_pllb_recal_opamp(struct drm_i915_private *dev_priv, enum pipe
7257                 pipe)
7258 {
7259         u32 reg_val;
7260
7261         /*
7262          * PLLB opamp always calibrates to max value of 0x3f, force enable it
7263          * and set it to a reasonable value instead.
7264          */
7265         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW9(1));
7266         reg_val &= 0xffffff00;
7267         reg_val |= 0x00000030;
7268         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW9(1), reg_val);
7269
7270         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_REF_DW13);
7271         reg_val &= 0x8cffffff;
7272         reg_val = 0x8c000000;
7273         vlv_dpio_write(dev_priv, pipe, VLV_REF_DW13, reg_val);
7274
7275         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW9(1));
7276         reg_val &= 0xffffff00;
7277         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW9(1), reg_val);
7278
7279         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_REF_DW13);
7280         reg_val &= 0x00ffffff;
7281         reg_val |= 0xb0000000;
7282         vlv_dpio_write(dev_priv, pipe, VLV_REF_DW13, reg_val);
7283 }
7284
7285 static void intel_pch_transcoder_set_m_n(struct intel_crtc *crtc,
7286                                          struct intel_link_m_n *m_n)
7287 {
7288         struct drm_device *dev = crtc->base.dev;
7289         struct drm_i915_private *dev_priv = dev->dev_private;
7290         int pipe = crtc->pipe;
7291
7292         I915_WRITE(PCH_TRANS_DATA_M1(pipe), TU_SIZE(m_n->tu) | m_n->gmch_m);
7293         I915_WRITE(PCH_TRANS_DATA_N1(pipe), m_n->gmch_n);
7294         I915_WRITE(PCH_TRANS_LINK_M1(pipe), m_n->link_m);
7295         I915_WRITE(PCH_TRANS_LINK_N1(pipe), m_n->link_n);
7296 }
7297
7298 static void intel_cpu_transcoder_set_m_n(struct intel_crtc *crtc,
7299                                          struct intel_link_m_n *m_n,
7300                                          struct intel_link_m_n *m2_n2)
7301 {
7302         struct drm_device *dev = crtc->base.dev;
7303         struct drm_i915_private *dev_priv = dev->dev_private;
7304         int pipe = crtc->pipe;
7305         enum transcoder transcoder = crtc->config->cpu_transcoder;
7306
7307         if (INTEL_INFO(dev)->gen >= 5) {
7308                 I915_WRITE(PIPE_DATA_M1(transcoder), TU_SIZE(m_n->tu) | m_n->gmch_m);
7309                 I915_WRITE(PIPE_DATA_N1(transcoder), m_n->gmch_n);
7310                 I915_WRITE(PIPE_LINK_M1(transcoder), m_n->link_m);
7311                 I915_WRITE(PIPE_LINK_N1(transcoder), m_n->link_n);
7312                 /* M2_N2 registers to be set only for gen < 8 (M2_N2 available
7313                  * for gen < 8) and if DRRS is supported (to make sure the
7314                  * registers are not unnecessarily accessed).
7315                  */
7316                 if (m2_n2 && (IS_CHERRYVIEW(dev) || INTEL_INFO(dev)->gen < 8) &&
7317                         crtc->config->has_drrs) {
7318                         I915_WRITE(PIPE_DATA_M2(transcoder),
7319                                         TU_SIZE(m2_n2->tu) | m2_n2->gmch_m);
7320                         I915_WRITE(PIPE_DATA_N2(transcoder), m2_n2->gmch_n);
7321                         I915_WRITE(PIPE_LINK_M2(transcoder), m2_n2->link_m);
7322                         I915_WRITE(PIPE_LINK_N2(transcoder), m2_n2->link_n);
7323                 }
7324         } else {
7325                 I915_WRITE(PIPE_DATA_M_G4X(pipe), TU_SIZE(m_n->tu) | m_n->gmch_m);
7326                 I915_WRITE(PIPE_DATA_N_G4X(pipe), m_n->gmch_n);
7327                 I915_WRITE(PIPE_LINK_M_G4X(pipe), m_n->link_m);
7328                 I915_WRITE(PIPE_LINK_N_G4X(pipe), m_n->link_n);
7329         }
7330 }
7331
7332 void intel_dp_set_m_n(struct intel_crtc *crtc, enum link_m_n_set m_n)
7333 {
7334         struct intel_link_m_n *dp_m_n, *dp_m2_n2 = NULL;
7335
7336         if (m_n == M1_N1) {
7337                 dp_m_n = &crtc->config->dp_m_n;
7338                 dp_m2_n2 = &crtc->config->dp_m2_n2;
7339         } else if (m_n == M2_N2) {
7340
7341                 /*
7342                  * M2_N2 registers are not supported. Hence m2_n2 divider value
7343                  * needs to be programmed into M1_N1.
7344                  */
7345                 dp_m_n = &crtc->config->dp_m2_n2;
7346         } else {
7347                 DRM_ERROR("Unsupported divider value\n");
7348                 return;
7349         }
7350
7351         if (crtc->config->has_pch_encoder)
7352                 intel_pch_transcoder_set_m_n(crtc, &crtc->config->dp_m_n);
7353         else
7354                 intel_cpu_transcoder_set_m_n(crtc, dp_m_n, dp_m2_n2);
7355 }
7356
7357 static void vlv_compute_dpll(struct intel_crtc *crtc,
7358                              struct intel_crtc_state *pipe_config)
7359 {
7360         u32 dpll, dpll_md;
7361
7362         /*
7363          * Enable DPIO clock input. We should never disable the reference
7364          * clock for pipe B, since VGA hotplug / manual detection depends
7365          * on it.
7366          */
7367         dpll = DPLL_EXT_BUFFER_ENABLE_VLV | DPLL_REF_CLK_ENABLE_VLV |
7368                 DPLL_VGA_MODE_DIS | DPLL_INTEGRATED_REF_CLK_VLV;
7369         /* We should never disable this, set it here for state tracking */
7370         if (crtc->pipe == PIPE_B)
7371                 dpll |= DPLL_INTEGRATED_CRI_CLK_VLV;
7372         dpll |= DPLL_VCO_ENABLE;
7373         pipe_config->dpll_hw_state.dpll = dpll;
7374
7375         dpll_md = (pipe_config->pixel_multiplier - 1)
7376                 << DPLL_MD_UDI_MULTIPLIER_SHIFT;
7377         pipe_config->dpll_hw_state.dpll_md = dpll_md;
7378 }
7379
7380 static void vlv_prepare_pll(struct intel_crtc *crtc,
7381                             const struct intel_crtc_state *pipe_config)
7382 {
7383         struct drm_device *dev = crtc->base.dev;
7384         struct drm_i915_private *dev_priv = dev->dev_private;
7385         int pipe = crtc->pipe;
7386         u32 mdiv;
7387         u32 bestn, bestm1, bestm2, bestp1, bestp2;
7388         u32 coreclk, reg_val;
7389
7390         mutex_lock(&dev_priv->sb_lock);
7391
7392         bestn = pipe_config->dpll.n;
7393         bestm1 = pipe_config->dpll.m1;
7394         bestm2 = pipe_config->dpll.m2;
7395         bestp1 = pipe_config->dpll.p1;
7396         bestp2 = pipe_config->dpll.p2;
7397
7398         /* See eDP HDMI DPIO driver vbios notes doc */
7399
7400         /* PLL B needs special handling */
7401         if (pipe == PIPE_B)
7402                 vlv_pllb_recal_opamp(dev_priv, pipe);
7403
7404         /* Set up Tx target for periodic Rcomp update */
7405         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW9_BCAST, 0x0100000f);
7406
7407         /* Disable target IRef on PLL */
7408         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW8(pipe));
7409         reg_val &= 0x00ffffff;
7410         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW8(pipe), reg_val);
7411
7412         /* Disable fast lock */
7413         vlv_dpio_write(dev_priv, pipe, VLV_CMN_DW0, 0x610);
7414
7415         /* Set idtafcrecal before PLL is enabled */
7416         mdiv = ((bestm1 << DPIO_M1DIV_SHIFT) | (bestm2 & DPIO_M2DIV_MASK));
7417         mdiv |= ((bestp1 << DPIO_P1_SHIFT) | (bestp2 << DPIO_P2_SHIFT));
7418         mdiv |= ((bestn << DPIO_N_SHIFT));
7419         mdiv |= (1 << DPIO_K_SHIFT);
7420
7421         /*
7422          * Post divider depends on pixel clock rate, DAC vs digital (and LVDS,
7423          * but we don't support that).
7424          * Note: don't use the DAC post divider as it seems unstable.
7425          */
7426         mdiv |= (DPIO_POST_DIV_HDMIDP << DPIO_POST_DIV_SHIFT);
7427         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW3(pipe), mdiv);
7428
7429         mdiv |= DPIO_ENABLE_CALIBRATION;
7430         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW3(pipe), mdiv);
7431
7432         /* Set HBR and RBR LPF coefficients */
7433         if (pipe_config->port_clock == 162000 ||
7434             intel_pipe_has_type(crtc, INTEL_OUTPUT_ANALOG) ||
7435             intel_pipe_has_type(crtc, INTEL_OUTPUT_HDMI))
7436                 vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW10(pipe),
7437                                  0x009f0003);
7438         else
7439                 vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW10(pipe),
7440                                  0x00d0000f);
7441
7442         if (pipe_config->has_dp_encoder) {
7443                 /* Use SSC source */
7444                 if (pipe == PIPE_A)
7445                         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW5(pipe),
7446                                          0x0df40000);
7447                 else
7448                         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW5(pipe),
7449                                          0x0df70000);
7450         } else { /* HDMI or VGA */
7451                 /* Use bend source */
7452                 if (pipe == PIPE_A)
7453                         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW5(pipe),
7454                                          0x0df70000);
7455                 else
7456                         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW5(pipe),
7457                                          0x0df40000);
7458         }
7459
7460         coreclk = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW7(pipe));
7461         coreclk = (coreclk & 0x0000ff00) | 0x01c00000;
7462         if (intel_pipe_has_type(crtc, INTEL_OUTPUT_DISPLAYPORT) ||
7463             intel_pipe_has_type(crtc, INTEL_OUTPUT_EDP))
7464                 coreclk |= 0x01000000;
7465         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW7(pipe), coreclk);
7466
7467         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW11(pipe), 0x87871000);
7468         mutex_unlock(&dev_priv->sb_lock);
7469 }
7470
7471 static void chv_compute_dpll(struct intel_crtc *crtc,
7472                              struct intel_crtc_state *pipe_config)
7473 {
7474         pipe_config->dpll_hw_state.dpll = DPLL_SSC_REF_CLK_CHV |
7475                 DPLL_REF_CLK_ENABLE_VLV | DPLL_VGA_MODE_DIS |
7476                 DPLL_VCO_ENABLE;
7477         if (crtc->pipe != PIPE_A)
7478                 pipe_config->dpll_hw_state.dpll |= DPLL_INTEGRATED_CRI_CLK_VLV;
7479
7480         pipe_config->dpll_hw_state.dpll_md =
7481                 (pipe_config->pixel_multiplier - 1) << DPLL_MD_UDI_MULTIPLIER_SHIFT;
7482 }
7483
7484 static void chv_prepare_pll(struct intel_crtc *crtc,
7485                             const struct intel_crtc_state *pipe_config)
7486 {
7487         struct drm_device *dev = crtc->base.dev;
7488         struct drm_i915_private *dev_priv = dev->dev_private;
7489         int pipe = crtc->pipe;
7490         i915_reg_t dpll_reg = DPLL(crtc->pipe);
7491         enum dpio_channel port = vlv_pipe_to_channel(pipe);
7492         u32 loopfilter, tribuf_calcntr;
7493         u32 bestn, bestm1, bestm2, bestp1, bestp2, bestm2_frac;
7494         u32 dpio_val;
7495         int vco;
7496
7497         bestn = pipe_config->dpll.n;
7498         bestm2_frac = pipe_config->dpll.m2 & 0x3fffff;
7499         bestm1 = pipe_config->dpll.m1;
7500         bestm2 = pipe_config->dpll.m2 >> 22;
7501         bestp1 = pipe_config->dpll.p1;
7502         bestp2 = pipe_config->dpll.p2;
7503         vco = pipe_config->dpll.vco;
7504         dpio_val = 0;
7505         loopfilter = 0;
7506
7507         /*
7508          * Enable Refclk and SSC
7509          */
7510         I915_WRITE(dpll_reg,
7511                    pipe_config->dpll_hw_state.dpll & ~DPLL_VCO_ENABLE);
7512
7513         mutex_lock(&dev_priv->sb_lock);
7514
7515         /* p1 and p2 divider */
7516         vlv_dpio_write(dev_priv, pipe, CHV_CMN_DW13(port),
7517                         5 << DPIO_CHV_S1_DIV_SHIFT |
7518                         bestp1 << DPIO_CHV_P1_DIV_SHIFT |
7519                         bestp2 << DPIO_CHV_P2_DIV_SHIFT |
7520                         1 << DPIO_CHV_K_DIV_SHIFT);
7521
7522         /* Feedback post-divider - m2 */
7523         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW0(port), bestm2);
7524
7525         /* Feedback refclk divider - n and m1 */
7526         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW1(port),
7527                         DPIO_CHV_M1_DIV_BY_2 |
7528                         1 << DPIO_CHV_N_DIV_SHIFT);
7529
7530         /* M2 fraction division */
7531         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW2(port), bestm2_frac);
7532
7533         /* M2 fraction division enable */
7534         dpio_val = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW3(port));
7535         dpio_val &= ~(DPIO_CHV_FEEDFWD_GAIN_MASK | DPIO_CHV_FRAC_DIV_EN);
7536         dpio_val |= (2 << DPIO_CHV_FEEDFWD_GAIN_SHIFT);
7537         if (bestm2_frac)
7538                 dpio_val |= DPIO_CHV_FRAC_DIV_EN;
7539         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW3(port), dpio_val);
7540
7541         /* Program digital lock detect threshold */
7542         dpio_val = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW9(port));
7543         dpio_val &= ~(DPIO_CHV_INT_LOCK_THRESHOLD_MASK |
7544                                         DPIO_CHV_INT_LOCK_THRESHOLD_SEL_COARSE);
7545         dpio_val |= (0x5 << DPIO_CHV_INT_LOCK_THRESHOLD_SHIFT);
7546         if (!bestm2_frac)
7547                 dpio_val |= DPIO_CHV_INT_LOCK_THRESHOLD_SEL_COARSE;
7548         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW9(port), dpio_val);
7549
7550         /* Loop filter */
7551         if (vco == 5400000) {
7552                 loopfilter |= (0x3 << DPIO_CHV_PROP_COEFF_SHIFT);
7553                 loopfilter |= (0x8 << DPIO_CHV_INT_COEFF_SHIFT);
7554                 loopfilter |= (0x1 << DPIO_CHV_GAIN_CTRL_SHIFT);
7555                 tribuf_calcntr = 0x9;
7556         } else if (vco <= 6200000) {
7557                 loopfilter |= (0x5 << DPIO_CHV_PROP_COEFF_SHIFT);
7558                 loopfilter |= (0xB << DPIO_CHV_INT_COEFF_SHIFT);
7559                 loopfilter |= (0x3 << DPIO_CHV_GAIN_CTRL_SHIFT);
7560                 tribuf_calcntr = 0x9;
7561         } else if (vco <= 6480000) {
7562                 loopfilter |= (0x4 << DPIO_CHV_PROP_COEFF_SHIFT);
7563                 loopfilter |= (0x9 << DPIO_CHV_INT_COEFF_SHIFT);
7564                 loopfilter |= (0x3 << DPIO_CHV_GAIN_CTRL_SHIFT);
7565                 tribuf_calcntr = 0x8;
7566         } else {
7567                 /* Not supported. Apply the same limits as in the max case */
7568                 loopfilter |= (0x4 << DPIO_CHV_PROP_COEFF_SHIFT);
7569                 loopfilter |= (0x9 << DPIO_CHV_INT_COEFF_SHIFT);
7570                 loopfilter |= (0x3 << DPIO_CHV_GAIN_CTRL_SHIFT);
7571                 tribuf_calcntr = 0;
7572         }
7573         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW6(port), loopfilter);
7574
7575         dpio_val = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW8(port));
7576         dpio_val &= ~DPIO_CHV_TDC_TARGET_CNT_MASK;
7577         dpio_val |= (tribuf_calcntr << DPIO_CHV_TDC_TARGET_CNT_SHIFT);
7578         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW8(port), dpio_val);
7579
7580         /* AFC Recal */
7581         vlv_dpio_write(dev_priv, pipe, CHV_CMN_DW14(port),
7582                         vlv_dpio_read(dev_priv, pipe, CHV_CMN_DW14(port)) |
7583                         DPIO_AFC_RECAL);
7584
7585         mutex_unlock(&dev_priv->sb_lock);
7586 }
7587
7588 /**
7589  * vlv_force_pll_on - forcibly enable just the PLL
7590  * @dev_priv: i915 private structure
7591  * @pipe: pipe PLL to enable
7592  * @dpll: PLL configuration
7593  *
7594  * Enable the PLL for @pipe using the supplied @dpll config. To be used
7595  * in cases where we need the PLL enabled even when @pipe is not going to
7596  * be enabled.
7597  */
7598 void vlv_force_pll_on(struct drm_device *dev, enum pipe pipe,
7599                       const struct dpll *dpll)
7600 {
7601         struct intel_crtc *crtc =
7602                 to_intel_crtc(intel_get_crtc_for_pipe(dev, pipe));
7603         struct intel_crtc_state pipe_config = {
7604                 .base.crtc = &crtc->base,
7605                 .pixel_multiplier = 1,
7606                 .dpll = *dpll,
7607         };
7608
7609         if (IS_CHERRYVIEW(dev)) {
7610                 chv_compute_dpll(crtc, &pipe_config);
7611                 chv_prepare_pll(crtc, &pipe_config);
7612                 chv_enable_pll(crtc, &pipe_config);
7613         } else {
7614                 vlv_compute_dpll(crtc, &pipe_config);
7615                 vlv_prepare_pll(crtc, &pipe_config);
7616                 vlv_enable_pll(crtc, &pipe_config);
7617         }
7618 }
7619
7620 /**
7621  * vlv_force_pll_off - forcibly disable just the PLL
7622  * @dev_priv: i915 private structure
7623  * @pipe: pipe PLL to disable
7624  *
7625  * Disable the PLL for @pipe. To be used in cases where we need
7626  * the PLL enabled even when @pipe is not going to be enabled.
7627  */
7628 void vlv_force_pll_off(struct drm_device *dev, enum pipe pipe)
7629 {
7630         if (IS_CHERRYVIEW(dev))
7631                 chv_disable_pll(to_i915(dev), pipe);
7632         else
7633                 vlv_disable_pll(to_i915(dev), pipe);
7634 }
7635
7636 static void i9xx_compute_dpll(struct intel_crtc *crtc,
7637                               struct intel_crtc_state *crtc_state,
7638                               intel_clock_t *reduced_clock,
7639                               int num_connectors)
7640 {
7641         struct drm_device *dev = crtc->base.dev;
7642         struct drm_i915_private *dev_priv = dev->dev_private;
7643         u32 dpll;
7644         bool is_sdvo;
7645         struct dpll *clock = &crtc_state->dpll;
7646
7647         i9xx_update_pll_dividers(crtc, crtc_state, reduced_clock);
7648
7649         is_sdvo = intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_SDVO) ||
7650                 intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_HDMI);
7651
7652         dpll = DPLL_VGA_MODE_DIS;
7653
7654         if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_LVDS))
7655                 dpll |= DPLLB_MODE_LVDS;
7656         else
7657                 dpll |= DPLLB_MODE_DAC_SERIAL;
7658
7659         if (IS_I945G(dev) || IS_I945GM(dev) || IS_G33(dev)) {
7660                 dpll |= (crtc_state->pixel_multiplier - 1)
7661                         << SDVO_MULTIPLIER_SHIFT_HIRES;
7662         }
7663
7664         if (is_sdvo)
7665                 dpll |= DPLL_SDVO_HIGH_SPEED;
7666
7667         if (crtc_state->has_dp_encoder)
7668                 dpll |= DPLL_SDVO_HIGH_SPEED;
7669
7670         /* compute bitmask from p1 value */
7671         if (IS_PINEVIEW(dev))
7672                 dpll |= (1 << (clock->p1 - 1)) << DPLL_FPA01_P1_POST_DIV_SHIFT_PINEVIEW;
7673         else {
7674                 dpll |= (1 << (clock->p1 - 1)) << DPLL_FPA01_P1_POST_DIV_SHIFT;
7675                 if (IS_G4X(dev) && reduced_clock)
7676                         dpll |= (1 << (reduced_clock->p1 - 1)) << DPLL_FPA1_P1_POST_DIV_SHIFT;
7677         }
7678         switch (clock->p2) {
7679         case 5:
7680                 dpll |= DPLL_DAC_SERIAL_P2_CLOCK_DIV_5;
7681                 break;
7682         case 7:
7683                 dpll |= DPLLB_LVDS_P2_CLOCK_DIV_7;
7684                 break;
7685         case 10:
7686                 dpll |= DPLL_DAC_SERIAL_P2_CLOCK_DIV_10;
7687                 break;
7688         case 14:
7689                 dpll |= DPLLB_LVDS_P2_CLOCK_DIV_14;
7690                 break;
7691         }
7692         if (INTEL_INFO(dev)->gen >= 4)
7693                 dpll |= (6 << PLL_LOAD_PULSE_PHASE_SHIFT);
7694
7695         if (crtc_state->sdvo_tv_clock)
7696                 dpll |= PLL_REF_INPUT_TVCLKINBC;
7697         else if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_LVDS) &&
7698                  intel_panel_use_ssc(dev_priv) && num_connectors < 2)
7699                 dpll |= PLLB_REF_INPUT_SPREADSPECTRUMIN;
7700         else
7701                 dpll |= PLL_REF_INPUT_DREFCLK;
7702
7703         dpll |= DPLL_VCO_ENABLE;
7704         crtc_state->dpll_hw_state.dpll = dpll;
7705
7706         if (INTEL_INFO(dev)->gen >= 4) {
7707                 u32 dpll_md = (crtc_state->pixel_multiplier - 1)
7708                         << DPLL_MD_UDI_MULTIPLIER_SHIFT;
7709                 crtc_state->dpll_hw_state.dpll_md = dpll_md;
7710         }
7711 }
7712
7713 static void i8xx_compute_dpll(struct intel_crtc *crtc,
7714                               struct intel_crtc_state *crtc_state,
7715                               intel_clock_t *reduced_clock,
7716                               int num_connectors)
7717 {
7718         struct drm_device *dev = crtc->base.dev;
7719         struct drm_i915_private *dev_priv = dev->dev_private;
7720         u32 dpll;
7721         struct dpll *clock = &crtc_state->dpll;
7722
7723         i9xx_update_pll_dividers(crtc, crtc_state, reduced_clock);
7724
7725         dpll = DPLL_VGA_MODE_DIS;
7726
7727         if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_LVDS)) {
7728                 dpll |= (1 << (clock->p1 - 1)) << DPLL_FPA01_P1_POST_DIV_SHIFT;
7729         } else {
7730                 if (clock->p1 == 2)
7731                         dpll |= PLL_P1_DIVIDE_BY_TWO;
7732                 else
7733                         dpll |= (clock->p1 - 2) << DPLL_FPA01_P1_POST_DIV_SHIFT;
7734                 if (clock->p2 == 4)
7735                         dpll |= PLL_P2_DIVIDE_BY_4;
7736         }
7737
7738         if (!IS_I830(dev) && intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_DVO))
7739                 dpll |= DPLL_DVO_2X_MODE;
7740
7741         if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_LVDS) &&
7742                  intel_panel_use_ssc(dev_priv) && num_connectors < 2)
7743                 dpll |= PLLB_REF_INPUT_SPREADSPECTRUMIN;
7744         else
7745                 dpll |= PLL_REF_INPUT_DREFCLK;
7746
7747         dpll |= DPLL_VCO_ENABLE;
7748         crtc_state->dpll_hw_state.dpll = dpll;
7749 }
7750
7751 static void intel_set_pipe_timings(struct intel_crtc *intel_crtc)
7752 {
7753         struct drm_device *dev = intel_crtc->base.dev;
7754         struct drm_i915_private *dev_priv = dev->dev_private;
7755         enum pipe pipe = intel_crtc->pipe;
7756         enum transcoder cpu_transcoder = intel_crtc->config->cpu_transcoder;
7757         const struct drm_display_mode *adjusted_mode = &intel_crtc->config->base.adjusted_mode;
7758         uint32_t crtc_vtotal, crtc_vblank_end;
7759         int vsyncshift = 0;
7760
7761         /* We need to be careful not to changed the adjusted mode, for otherwise
7762          * the hw state checker will get angry at the mismatch. */
7763         crtc_vtotal = adjusted_mode->crtc_vtotal;
7764         crtc_vblank_end = adjusted_mode->crtc_vblank_end;
7765
7766         if (adjusted_mode->flags & DRM_MODE_FLAG_INTERLACE) {
7767                 /* the chip adds 2 halflines automatically */
7768                 crtc_vtotal -= 1;
7769                 crtc_vblank_end -= 1;
7770
7771                 if (intel_pipe_has_type(intel_crtc, INTEL_OUTPUT_SDVO))
7772                         vsyncshift = (adjusted_mode->crtc_htotal - 1) / 2;
7773                 else
7774                         vsyncshift = adjusted_mode->crtc_hsync_start -
7775                                 adjusted_mode->crtc_htotal / 2;
7776                 if (vsyncshift < 0)
7777                         vsyncshift += adjusted_mode->crtc_htotal;
7778         }
7779
7780         if (INTEL_INFO(dev)->gen > 3)
7781                 I915_WRITE(VSYNCSHIFT(cpu_transcoder), vsyncshift);
7782
7783         I915_WRITE(HTOTAL(cpu_transcoder),
7784                    (adjusted_mode->crtc_hdisplay - 1) |
7785                    ((adjusted_mode->crtc_htotal - 1) << 16));
7786         I915_WRITE(HBLANK(cpu_transcoder),
7787                    (adjusted_mode->crtc_hblank_start - 1) |
7788                    ((adjusted_mode->crtc_hblank_end - 1) << 16));
7789         I915_WRITE(HSYNC(cpu_transcoder),
7790                    (adjusted_mode->crtc_hsync_start - 1) |
7791                    ((adjusted_mode->crtc_hsync_end - 1) << 16));
7792
7793         I915_WRITE(VTOTAL(cpu_transcoder),
7794                    (adjusted_mode->crtc_vdisplay - 1) |
7795                    ((crtc_vtotal - 1) << 16));
7796         I915_WRITE(VBLANK(cpu_transcoder),
7797                    (adjusted_mode->crtc_vblank_start - 1) |
7798                    ((crtc_vblank_end - 1) << 16));
7799         I915_WRITE(VSYNC(cpu_transcoder),
7800                    (adjusted_mode->crtc_vsync_start - 1) |
7801                    ((adjusted_mode->crtc_vsync_end - 1) << 16));
7802
7803         /* Workaround: when the EDP input selection is B, the VTOTAL_B must be
7804          * programmed with the VTOTAL_EDP value. Same for VTOTAL_C. This is
7805          * documented on the DDI_FUNC_CTL register description, EDP Input Select
7806          * bits. */
7807         if (IS_HASWELL(dev) && cpu_transcoder == TRANSCODER_EDP &&
7808             (pipe == PIPE_B || pipe == PIPE_C))
7809                 I915_WRITE(VTOTAL(pipe), I915_READ(VTOTAL(cpu_transcoder)));
7810
7811         /* pipesrc controls the size that is scaled from, which should
7812          * always be the user's requested size.
7813          */
7814         I915_WRITE(PIPESRC(pipe),
7815                    ((intel_crtc->config->pipe_src_w - 1) << 16) |
7816                    (intel_crtc->config->pipe_src_h - 1));
7817 }
7818
7819 static void intel_get_pipe_timings(struct intel_crtc *crtc,
7820                                    struct intel_crtc_state *pipe_config)
7821 {
7822         struct drm_device *dev = crtc->base.dev;
7823         struct drm_i915_private *dev_priv = dev->dev_private;
7824         enum transcoder cpu_transcoder = pipe_config->cpu_transcoder;
7825         uint32_t tmp;
7826
7827         tmp = I915_READ(HTOTAL(cpu_transcoder));
7828         pipe_config->base.adjusted_mode.crtc_hdisplay = (tmp & 0xffff) + 1;
7829         pipe_config->base.adjusted_mode.crtc_htotal = ((tmp >> 16) & 0xffff) + 1;
7830         tmp = I915_READ(HBLANK(cpu_transcoder));
7831         pipe_config->base.adjusted_mode.crtc_hblank_start = (tmp & 0xffff) + 1;
7832         pipe_config->base.adjusted_mode.crtc_hblank_end = ((tmp >> 16) & 0xffff) + 1;
7833         tmp = I915_READ(HSYNC(cpu_transcoder));
7834         pipe_config->base.adjusted_mode.crtc_hsync_start = (tmp & 0xffff) + 1;
7835         pipe_config->base.adjusted_mode.crtc_hsync_end = ((tmp >> 16) & 0xffff) + 1;
7836
7837         tmp = I915_READ(VTOTAL(cpu_transcoder));
7838         pipe_config->base.adjusted_mode.crtc_vdisplay = (tmp & 0xffff) + 1;
7839         pipe_config->base.adjusted_mode.crtc_vtotal = ((tmp >> 16) & 0xffff) + 1;
7840         tmp = I915_READ(VBLANK(cpu_transcoder));
7841         pipe_config->base.adjusted_mode.crtc_vblank_start = (tmp & 0xffff) + 1;
7842         pipe_config->base.adjusted_mode.crtc_vblank_end = ((tmp >> 16) & 0xffff) + 1;
7843         tmp = I915_READ(VSYNC(cpu_transcoder));
7844         pipe_config->base.adjusted_mode.crtc_vsync_start = (tmp & 0xffff) + 1;
7845         pipe_config->base.adjusted_mode.crtc_vsync_end = ((tmp >> 16) & 0xffff) + 1;
7846
7847         if (I915_READ(PIPECONF(cpu_transcoder)) & PIPECONF_INTERLACE_MASK) {
7848                 pipe_config->base.adjusted_mode.flags |= DRM_MODE_FLAG_INTERLACE;
7849                 pipe_config->base.adjusted_mode.crtc_vtotal += 1;
7850                 pipe_config->base.adjusted_mode.crtc_vblank_end += 1;
7851         }
7852
7853         tmp = I915_READ(PIPESRC(crtc->pipe));
7854         pipe_config->pipe_src_h = (tmp & 0xffff) + 1;
7855         pipe_config->pipe_src_w = ((tmp >> 16) & 0xffff) + 1;
7856
7857         pipe_config->base.mode.vdisplay = pipe_config->pipe_src_h;
7858         pipe_config->base.mode.hdisplay = pipe_config->pipe_src_w;
7859 }
7860
7861 void intel_mode_from_pipe_config(struct drm_display_mode *mode,
7862                                  struct intel_crtc_state *pipe_config)
7863 {
7864         mode->hdisplay = pipe_config->base.adjusted_mode.crtc_hdisplay;
7865         mode->htotal = pipe_config->base.adjusted_mode.crtc_htotal;
7866         mode->hsync_start = pipe_config->base.adjusted_mode.crtc_hsync_start;
7867         mode->hsync_end = pipe_config->base.adjusted_mode.crtc_hsync_end;
7868
7869         mode->vdisplay = pipe_config->base.adjusted_mode.crtc_vdisplay;
7870         mode->vtotal = pipe_config->base.adjusted_mode.crtc_vtotal;
7871         mode->vsync_start = pipe_config->base.adjusted_mode.crtc_vsync_start;
7872         mode->vsync_end = pipe_config->base.adjusted_mode.crtc_vsync_end;
7873
7874         mode->flags = pipe_config->base.adjusted_mode.flags;
7875         mode->type = DRM_MODE_TYPE_DRIVER;
7876
7877         mode->clock = pipe_config->base.adjusted_mode.crtc_clock;
7878         mode->flags |= pipe_config->base.adjusted_mode.flags;
7879
7880         mode->hsync = drm_mode_hsync(mode);
7881         mode->vrefresh = drm_mode_vrefresh(mode);
7882         drm_mode_set_name(mode);
7883 }
7884
7885 static void i9xx_set_pipeconf(struct intel_crtc *intel_crtc)
7886 {
7887         struct drm_device *dev = intel_crtc->base.dev;
7888         struct drm_i915_private *dev_priv = dev->dev_private;
7889         uint32_t pipeconf;
7890
7891         pipeconf = 0;
7892
7893         if ((intel_crtc->pipe == PIPE_A && dev_priv->quirks & QUIRK_PIPEA_FORCE) ||
7894             (intel_crtc->pipe == PIPE_B && dev_priv->quirks & QUIRK_PIPEB_FORCE))
7895                 pipeconf |= I915_READ(PIPECONF(intel_crtc->pipe)) & PIPECONF_ENABLE;
7896
7897         if (intel_crtc->config->double_wide)
7898                 pipeconf |= PIPECONF_DOUBLE_WIDE;
7899
7900         /* only g4x and later have fancy bpc/dither controls */
7901         if (IS_G4X(dev) || IS_VALLEYVIEW(dev) || IS_CHERRYVIEW(dev)) {
7902                 /* Bspec claims that we can't use dithering for 30bpp pipes. */
7903                 if (intel_crtc->config->dither && intel_crtc->config->pipe_bpp != 30)
7904                         pipeconf |= PIPECONF_DITHER_EN |
7905                                     PIPECONF_DITHER_TYPE_SP;
7906
7907                 switch (intel_crtc->config->pipe_bpp) {
7908                 case 18:
7909                         pipeconf |= PIPECONF_6BPC;
7910                         break;
7911                 case 24:
7912                         pipeconf |= PIPECONF_8BPC;
7913                         break;
7914                 case 30:
7915                         pipeconf |= PIPECONF_10BPC;
7916                         break;
7917                 default:
7918                         /* Case prevented by intel_choose_pipe_bpp_dither. */
7919                         BUG();
7920                 }
7921         }
7922
7923         if (HAS_PIPE_CXSR(dev)) {
7924                 if (intel_crtc->lowfreq_avail) {
7925                         DRM_DEBUG_KMS("enabling CxSR downclocking\n");
7926                         pipeconf |= PIPECONF_CXSR_DOWNCLOCK;
7927                 } else {
7928                         DRM_DEBUG_KMS("disabling CxSR downclocking\n");
7929                 }
7930         }
7931
7932         if (intel_crtc->config->base.adjusted_mode.flags & DRM_MODE_FLAG_INTERLACE) {
7933                 if (INTEL_INFO(dev)->gen < 4 ||
7934                     intel_pipe_has_type(intel_crtc, INTEL_OUTPUT_SDVO))
7935                         pipeconf |= PIPECONF_INTERLACE_W_FIELD_INDICATION;
7936                 else
7937                         pipeconf |= PIPECONF_INTERLACE_W_SYNC_SHIFT;
7938         } else
7939                 pipeconf |= PIPECONF_PROGRESSIVE;
7940
7941         if ((IS_VALLEYVIEW(dev) || IS_CHERRYVIEW(dev)) &&
7942              intel_crtc->config->limited_color_range)
7943                 pipeconf |= PIPECONF_COLOR_RANGE_SELECT;
7944
7945         I915_WRITE(PIPECONF(intel_crtc->pipe), pipeconf);
7946         POSTING_READ(PIPECONF(intel_crtc->pipe));
7947 }
7948
7949 static int i9xx_crtc_compute_clock(struct intel_crtc *crtc,
7950                                    struct intel_crtc_state *crtc_state)
7951 {
7952         struct drm_device *dev = crtc->base.dev;
7953         struct drm_i915_private *dev_priv = dev->dev_private;
7954         int refclk, num_connectors = 0;
7955         intel_clock_t clock;
7956         bool ok;
7957         const intel_limit_t *limit;
7958         struct drm_atomic_state *state = crtc_state->base.state;
7959         struct drm_connector *connector;
7960         struct drm_connector_state *connector_state;
7961         int i;
7962
7963         memset(&crtc_state->dpll_hw_state, 0,
7964                sizeof(crtc_state->dpll_hw_state));
7965
7966         if (crtc_state->has_dsi_encoder)
7967                 return 0;
7968
7969         for_each_connector_in_state(state, connector, connector_state, i) {
7970                 if (connector_state->crtc == &crtc->base)
7971                         num_connectors++;
7972         }
7973
7974         if (!crtc_state->clock_set) {
7975                 refclk = i9xx_get_refclk(crtc_state, num_connectors);
7976
7977                 /*
7978                  * Returns a set of divisors for the desired target clock with
7979                  * the given refclk, or FALSE.  The returned values represent
7980                  * the clock equation: reflck * (5 * (m1 + 2) + (m2 + 2)) / (n +
7981                  * 2) / p1 / p2.
7982                  */
7983                 limit = intel_limit(crtc_state, refclk);
7984                 ok = dev_priv->display.find_dpll(limit, crtc_state,
7985                                                  crtc_state->port_clock,
7986                                                  refclk, NULL, &clock);
7987                 if (!ok) {
7988                         DRM_ERROR("Couldn't find PLL settings for mode!\n");
7989                         return -EINVAL;
7990                 }
7991
7992                 /* Compat-code for transition, will disappear. */
7993                 crtc_state->dpll.n = clock.n;
7994                 crtc_state->dpll.m1 = clock.m1;
7995                 crtc_state->dpll.m2 = clock.m2;
7996                 crtc_state->dpll.p1 = clock.p1;
7997                 crtc_state->dpll.p2 = clock.p2;
7998         }
7999
8000         if (IS_GEN2(dev)) {
8001                 i8xx_compute_dpll(crtc, crtc_state, NULL,
8002                                   num_connectors);
8003         } else if (IS_CHERRYVIEW(dev)) {
8004                 chv_compute_dpll(crtc, crtc_state);
8005         } else if (IS_VALLEYVIEW(dev)) {
8006                 vlv_compute_dpll(crtc, crtc_state);
8007         } else {
8008                 i9xx_compute_dpll(crtc, crtc_state, NULL,
8009                                   num_connectors);
8010         }
8011
8012         return 0;
8013 }
8014
8015 static void i9xx_get_pfit_config(struct intel_crtc *crtc,
8016                                  struct intel_crtc_state *pipe_config)
8017 {
8018         struct drm_device *dev = crtc->base.dev;
8019         struct drm_i915_private *dev_priv = dev->dev_private;
8020         uint32_t tmp;
8021
8022         if (INTEL_INFO(dev)->gen <= 3 && (IS_I830(dev) || !IS_MOBILE(dev)))
8023                 return;
8024
8025         tmp = I915_READ(PFIT_CONTROL);
8026         if (!(tmp & PFIT_ENABLE))
8027                 return;
8028
8029         /* Check whether the pfit is attached to our pipe. */
8030         if (INTEL_INFO(dev)->gen < 4) {
8031                 if (crtc->pipe != PIPE_B)
8032                         return;
8033         } else {
8034                 if ((tmp & PFIT_PIPE_MASK) != (crtc->pipe << PFIT_PIPE_SHIFT))
8035                         return;
8036         }
8037
8038         pipe_config->gmch_pfit.control = tmp;
8039         pipe_config->gmch_pfit.pgm_ratios = I915_READ(PFIT_PGM_RATIOS);
8040         if (INTEL_INFO(dev)->gen < 5)
8041                 pipe_config->gmch_pfit.lvds_border_bits =
8042                         I915_READ(LVDS) & LVDS_BORDER_ENABLE;
8043 }
8044
8045 static void vlv_crtc_clock_get(struct intel_crtc *crtc,
8046                                struct intel_crtc_state *pipe_config)
8047 {
8048         struct drm_device *dev = crtc->base.dev;
8049         struct drm_i915_private *dev_priv = dev->dev_private;
8050         int pipe = pipe_config->cpu_transcoder;
8051         intel_clock_t clock;
8052         u32 mdiv;
8053         int refclk = 100000;
8054
8055         /* In case of MIPI DPLL will not even be used */
8056         if (!(pipe_config->dpll_hw_state.dpll & DPLL_VCO_ENABLE))
8057                 return;
8058
8059         mutex_lock(&dev_priv->sb_lock);
8060         mdiv = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW3(pipe));
8061         mutex_unlock(&dev_priv->sb_lock);
8062
8063         clock.m1 = (mdiv >> DPIO_M1DIV_SHIFT) & 7;
8064         clock.m2 = mdiv & DPIO_M2DIV_MASK;
8065         clock.n = (mdiv >> DPIO_N_SHIFT) & 0xf;
8066         clock.p1 = (mdiv >> DPIO_P1_SHIFT) & 7;
8067         clock.p2 = (mdiv >> DPIO_P2_SHIFT) & 0x1f;
8068
8069         pipe_config->port_clock = vlv_calc_dpll_params(refclk, &clock);
8070 }
8071
8072 static void
8073 i9xx_get_initial_plane_config(struct intel_crtc *crtc,
8074                               struct intel_initial_plane_config *plane_config)
8075 {
8076         struct drm_device *dev = crtc->base.dev;
8077         struct drm_i915_private *dev_priv = dev->dev_private;
8078         u32 val, base, offset;
8079         int pipe = crtc->pipe, plane = crtc->plane;
8080         int fourcc, pixel_format;
8081         unsigned int aligned_height;
8082         struct drm_framebuffer *fb;
8083         struct intel_framebuffer *intel_fb;
8084
8085         val = I915_READ(DSPCNTR(plane));
8086         if (!(val & DISPLAY_PLANE_ENABLE))
8087                 return;
8088
8089         intel_fb = kzalloc(sizeof(*intel_fb), GFP_KERNEL);
8090         if (!intel_fb) {
8091                 DRM_DEBUG_KMS("failed to alloc fb\n");
8092                 return;
8093         }
8094
8095         fb = &intel_fb->base;
8096
8097         if (INTEL_INFO(dev)->gen >= 4) {
8098                 if (val & DISPPLANE_TILED) {
8099                         plane_config->tiling = I915_TILING_X;
8100                         fb->modifier[0] = I915_FORMAT_MOD_X_TILED;
8101                 }
8102         }
8103
8104         pixel_format = val & DISPPLANE_PIXFORMAT_MASK;
8105         fourcc = i9xx_format_to_fourcc(pixel_format);
8106         fb->pixel_format = fourcc;
8107         fb->bits_per_pixel = drm_format_plane_cpp(fourcc, 0) * 8;
8108
8109         if (INTEL_INFO(dev)->gen >= 4) {
8110                 if (plane_config->tiling)
8111                         offset = I915_READ(DSPTILEOFF(plane));
8112                 else
8113                         offset = I915_READ(DSPLINOFF(plane));
8114                 base = I915_READ(DSPSURF(plane)) & 0xfffff000;
8115         } else {
8116                 base = I915_READ(DSPADDR(plane));
8117         }
8118         plane_config->base = base;
8119
8120         val = I915_READ(PIPESRC(pipe));
8121         fb->width = ((val >> 16) & 0xfff) + 1;
8122         fb->height = ((val >> 0) & 0xfff) + 1;
8123
8124         val = I915_READ(DSPSTRIDE(pipe));
8125         fb->pitches[0] = val & 0xffffffc0;
8126
8127         aligned_height = intel_fb_align_height(dev, fb->height,
8128                                                fb->pixel_format,
8129                                                fb->modifier[0]);
8130
8131         plane_config->size = fb->pitches[0] * aligned_height;
8132
8133         DRM_DEBUG_KMS("pipe/plane %c/%d with fb: size=%dx%d@%d, offset=%x, pitch %d, size 0x%x\n",
8134                       pipe_name(pipe), plane, fb->width, fb->height,
8135                       fb->bits_per_pixel, base, fb->pitches[0],
8136                       plane_config->size);
8137
8138         plane_config->fb = intel_fb;
8139 }
8140
8141 static void chv_crtc_clock_get(struct intel_crtc *crtc,
8142                                struct intel_crtc_state *pipe_config)
8143 {
8144         struct drm_device *dev = crtc->base.dev;
8145         struct drm_i915_private *dev_priv = dev->dev_private;
8146         int pipe = pipe_config->cpu_transcoder;
8147         enum dpio_channel port = vlv_pipe_to_channel(pipe);
8148         intel_clock_t clock;
8149         u32 cmn_dw13, pll_dw0, pll_dw1, pll_dw2, pll_dw3;
8150         int refclk = 100000;
8151
8152         mutex_lock(&dev_priv->sb_lock);
8153         cmn_dw13 = vlv_dpio_read(dev_priv, pipe, CHV_CMN_DW13(port));
8154         pll_dw0 = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW0(port));
8155         pll_dw1 = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW1(port));
8156         pll_dw2 = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW2(port));
8157         pll_dw3 = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW3(port));
8158         mutex_unlock(&dev_priv->sb_lock);
8159
8160         clock.m1 = (pll_dw1 & 0x7) == DPIO_CHV_M1_DIV_BY_2 ? 2 : 0;
8161         clock.m2 = (pll_dw0 & 0xff) << 22;
8162         if (pll_dw3 & DPIO_CHV_FRAC_DIV_EN)
8163                 clock.m2 |= pll_dw2 & 0x3fffff;
8164         clock.n = (pll_dw1 >> DPIO_CHV_N_DIV_SHIFT) & 0xf;
8165         clock.p1 = (cmn_dw13 >> DPIO_CHV_P1_DIV_SHIFT) & 0x7;
8166         clock.p2 = (cmn_dw13 >> DPIO_CHV_P2_DIV_SHIFT) & 0x1f;
8167
8168         pipe_config->port_clock = chv_calc_dpll_params(refclk, &clock);
8169 }
8170
8171 static bool i9xx_get_pipe_config(struct intel_crtc *crtc,
8172                                  struct intel_crtc_state *pipe_config)
8173 {
8174         struct drm_device *dev = crtc->base.dev;
8175         struct drm_i915_private *dev_priv = dev->dev_private;
8176         uint32_t tmp;
8177
8178         if (!intel_display_power_is_enabled(dev_priv,
8179                                             POWER_DOMAIN_PIPE(crtc->pipe)))
8180                 return false;
8181
8182         pipe_config->cpu_transcoder = (enum transcoder) crtc->pipe;
8183         pipe_config->shared_dpll = DPLL_ID_PRIVATE;
8184
8185         tmp = I915_READ(PIPECONF(crtc->pipe));
8186         if (!(tmp & PIPECONF_ENABLE))
8187                 return false;
8188
8189         if (IS_G4X(dev) || IS_VALLEYVIEW(dev) || IS_CHERRYVIEW(dev)) {
8190                 switch (tmp & PIPECONF_BPC_MASK) {
8191                 case PIPECONF_6BPC:
8192                         pipe_config->pipe_bpp = 18;
8193                         break;
8194                 case PIPECONF_8BPC:
8195                         pipe_config->pipe_bpp = 24;
8196                         break;
8197                 case PIPECONF_10BPC:
8198                         pipe_config->pipe_bpp = 30;
8199                         break;
8200                 default:
8201                         break;
8202                 }
8203         }
8204
8205         if ((IS_VALLEYVIEW(dev) || IS_CHERRYVIEW(dev)) &&
8206             (tmp & PIPECONF_COLOR_RANGE_SELECT))
8207                 pipe_config->limited_color_range = true;
8208
8209         if (INTEL_INFO(dev)->gen < 4)
8210                 pipe_config->double_wide = tmp & PIPECONF_DOUBLE_WIDE;
8211
8212         intel_get_pipe_timings(crtc, pipe_config);
8213
8214         i9xx_get_pfit_config(crtc, pipe_config);
8215
8216         if (INTEL_INFO(dev)->gen >= 4) {
8217                 tmp = I915_READ(DPLL_MD(crtc->pipe));
8218                 pipe_config->pixel_multiplier =
8219                         ((tmp & DPLL_MD_UDI_MULTIPLIER_MASK)
8220                          >> DPLL_MD_UDI_MULTIPLIER_SHIFT) + 1;
8221                 pipe_config->dpll_hw_state.dpll_md = tmp;
8222         } else if (IS_I945G(dev) || IS_I945GM(dev) || IS_G33(dev)) {
8223                 tmp = I915_READ(DPLL(crtc->pipe));
8224                 pipe_config->pixel_multiplier =
8225                         ((tmp & SDVO_MULTIPLIER_MASK)
8226                          >> SDVO_MULTIPLIER_SHIFT_HIRES) + 1;
8227         } else {
8228                 /* Note that on i915G/GM the pixel multiplier is in the sdvo
8229                  * port and will be fixed up in the encoder->get_config
8230                  * function. */
8231                 pipe_config->pixel_multiplier = 1;
8232         }
8233         pipe_config->dpll_hw_state.dpll = I915_READ(DPLL(crtc->pipe));
8234         if (!IS_VALLEYVIEW(dev) && !IS_CHERRYVIEW(dev)) {
8235                 /*
8236                  * DPLL_DVO_2X_MODE must be enabled for both DPLLs
8237                  * on 830. Filter it out here so that we don't
8238                  * report errors due to that.
8239                  */
8240                 if (IS_I830(dev))
8241                         pipe_config->dpll_hw_state.dpll &= ~DPLL_DVO_2X_MODE;
8242
8243                 pipe_config->dpll_hw_state.fp0 = I915_READ(FP0(crtc->pipe));
8244                 pipe_config->dpll_hw_state.fp1 = I915_READ(FP1(crtc->pipe));
8245         } else {
8246                 /* Mask out read-only status bits. */
8247                 pipe_config->dpll_hw_state.dpll &= ~(DPLL_LOCK_VLV |
8248                                                      DPLL_PORTC_READY_MASK |
8249                                                      DPLL_PORTB_READY_MASK);
8250         }
8251
8252         if (IS_CHERRYVIEW(dev))
8253                 chv_crtc_clock_get(crtc, pipe_config);
8254         else if (IS_VALLEYVIEW(dev))
8255                 vlv_crtc_clock_get(crtc, pipe_config);
8256         else
8257                 i9xx_crtc_clock_get(crtc, pipe_config);
8258
8259         /*
8260          * Normally the dotclock is filled in by the encoder .get_config()
8261          * but in case the pipe is enabled w/o any ports we need a sane
8262          * default.
8263          */
8264         pipe_config->base.adjusted_mode.crtc_clock =
8265                 pipe_config->port_clock / pipe_config->pixel_multiplier;
8266
8267         return true;
8268 }
8269
8270 static void ironlake_init_pch_refclk(struct drm_device *dev)
8271 {
8272         struct drm_i915_private *dev_priv = dev->dev_private;
8273         struct intel_encoder *encoder;
8274         u32 val, final;
8275         bool has_lvds = false;
8276         bool has_cpu_edp = false;
8277         bool has_panel = false;
8278         bool has_ck505 = false;
8279         bool can_ssc = false;
8280
8281         /* We need to take the global config into account */
8282         for_each_intel_encoder(dev, encoder) {
8283                 switch (encoder->type) {
8284                 case INTEL_OUTPUT_LVDS:
8285                         has_panel = true;
8286                         has_lvds = true;
8287                         break;
8288                 case INTEL_OUTPUT_EDP:
8289                         has_panel = true;
8290                         if (enc_to_dig_port(&encoder->base)->port == PORT_A)
8291                                 has_cpu_edp = true;
8292                         break;
8293                 default:
8294                         break;
8295                 }
8296         }
8297
8298         if (HAS_PCH_IBX(dev)) {
8299                 has_ck505 = dev_priv->vbt.display_clock_mode;
8300                 can_ssc = has_ck505;
8301         } else {
8302                 has_ck505 = false;
8303                 can_ssc = true;
8304         }
8305
8306         DRM_DEBUG_KMS("has_panel %d has_lvds %d has_ck505 %d\n",
8307                       has_panel, has_lvds, has_ck505);
8308
8309         /* Ironlake: try to setup display ref clock before DPLL
8310          * enabling. This is only under driver's control after
8311          * PCH B stepping, previous chipset stepping should be
8312          * ignoring this setting.
8313          */
8314         val = I915_READ(PCH_DREF_CONTROL);
8315
8316         /* As we must carefully and slowly disable/enable each source in turn,
8317          * compute the final state we want first and check if we need to
8318          * make any changes at all.
8319          */
8320         final = val;
8321         final &= ~DREF_NONSPREAD_SOURCE_MASK;
8322         if (has_ck505)
8323                 final |= DREF_NONSPREAD_CK505_ENABLE;
8324         else
8325                 final |= DREF_NONSPREAD_SOURCE_ENABLE;
8326
8327         final &= ~DREF_SSC_SOURCE_MASK;
8328         final &= ~DREF_CPU_SOURCE_OUTPUT_MASK;
8329         final &= ~DREF_SSC1_ENABLE;
8330
8331         if (has_panel) {
8332                 final |= DREF_SSC_SOURCE_ENABLE;
8333
8334                 if (intel_panel_use_ssc(dev_priv) && can_ssc)
8335                         final |= DREF_SSC1_ENABLE;
8336
8337                 if (has_cpu_edp) {
8338                         if (intel_panel_use_ssc(dev_priv) && can_ssc)
8339                                 final |= DREF_CPU_SOURCE_OUTPUT_DOWNSPREAD;
8340                         else
8341                                 final |= DREF_CPU_SOURCE_OUTPUT_NONSPREAD;
8342                 } else
8343                         final |= DREF_CPU_SOURCE_OUTPUT_DISABLE;
8344         } else {
8345                 final |= DREF_SSC_SOURCE_DISABLE;
8346                 final |= DREF_CPU_SOURCE_OUTPUT_DISABLE;
8347         }
8348
8349         if (final == val)
8350                 return;
8351
8352         /* Always enable nonspread source */
8353         val &= ~DREF_NONSPREAD_SOURCE_MASK;
8354
8355         if (has_ck505)
8356                 val |= DREF_NONSPREAD_CK505_ENABLE;
8357         else
8358                 val |= DREF_NONSPREAD_SOURCE_ENABLE;
8359
8360         if (has_panel) {
8361                 val &= ~DREF_SSC_SOURCE_MASK;
8362                 val |= DREF_SSC_SOURCE_ENABLE;
8363
8364                 /* SSC must be turned on before enabling the CPU output  */
8365                 if (intel_panel_use_ssc(dev_priv) && can_ssc) {
8366                         DRM_DEBUG_KMS("Using SSC on panel\n");
8367                         val |= DREF_SSC1_ENABLE;
8368                 } else
8369                         val &= ~DREF_SSC1_ENABLE;
8370
8371                 /* Get SSC going before enabling the outputs */
8372                 I915_WRITE(PCH_DREF_CONTROL, val);
8373                 POSTING_READ(PCH_DREF_CONTROL);
8374                 udelay(200);
8375
8376                 val &= ~DREF_CPU_SOURCE_OUTPUT_MASK;
8377
8378                 /* Enable CPU source on CPU attached eDP */
8379                 if (has_cpu_edp) {
8380                         if (intel_panel_use_ssc(dev_priv) && can_ssc) {
8381                                 DRM_DEBUG_KMS("Using SSC on eDP\n");
8382                                 val |= DREF_CPU_SOURCE_OUTPUT_DOWNSPREAD;
8383                         } else
8384                                 val |= DREF_CPU_SOURCE_OUTPUT_NONSPREAD;
8385                 } else
8386                         val |= DREF_CPU_SOURCE_OUTPUT_DISABLE;
8387
8388                 I915_WRITE(PCH_DREF_CONTROL, val);
8389                 POSTING_READ(PCH_DREF_CONTROL);
8390                 udelay(200);
8391         } else {
8392                 DRM_DEBUG_KMS("Disabling SSC entirely\n");
8393
8394                 val &= ~DREF_CPU_SOURCE_OUTPUT_MASK;
8395
8396                 /* Turn off CPU output */
8397                 val |= DREF_CPU_SOURCE_OUTPUT_DISABLE;
8398
8399                 I915_WRITE(PCH_DREF_CONTROL, val);
8400                 POSTING_READ(PCH_DREF_CONTROL);
8401                 udelay(200);
8402
8403                 /* Turn off the SSC source */
8404                 val &= ~DREF_SSC_SOURCE_MASK;
8405                 val |= DREF_SSC_SOURCE_DISABLE;
8406
8407                 /* Turn off SSC1 */
8408                 val &= ~DREF_SSC1_ENABLE;
8409
8410                 I915_WRITE(PCH_DREF_CONTROL, val);
8411                 POSTING_READ(PCH_DREF_CONTROL);
8412                 udelay(200);
8413         }
8414
8415         BUG_ON(val != final);
8416 }
8417
8418 static void lpt_reset_fdi_mphy(struct drm_i915_private *dev_priv)
8419 {
8420         uint32_t tmp;
8421
8422         tmp = I915_READ(SOUTH_CHICKEN2);
8423         tmp |= FDI_MPHY_IOSFSB_RESET_CTL;
8424         I915_WRITE(SOUTH_CHICKEN2, tmp);
8425
8426         if (wait_for_atomic_us(I915_READ(SOUTH_CHICKEN2) &
8427                                FDI_MPHY_IOSFSB_RESET_STATUS, 100))
8428                 DRM_ERROR("FDI mPHY reset assert timeout\n");
8429
8430         tmp = I915_READ(SOUTH_CHICKEN2);
8431         tmp &= ~FDI_MPHY_IOSFSB_RESET_CTL;
8432         I915_WRITE(SOUTH_CHICKEN2, tmp);
8433
8434         if (wait_for_atomic_us((I915_READ(SOUTH_CHICKEN2) &
8435                                 FDI_MPHY_IOSFSB_RESET_STATUS) == 0, 100))
8436                 DRM_ERROR("FDI mPHY reset de-assert timeout\n");
8437 }
8438
8439 /* WaMPhyProgramming:hsw */
8440 static void lpt_program_fdi_mphy(struct drm_i915_private *dev_priv)
8441 {
8442         uint32_t tmp;
8443
8444         tmp = intel_sbi_read(dev_priv, 0x8008, SBI_MPHY);
8445         tmp &= ~(0xFF << 24);
8446         tmp |= (0x12 << 24);
8447         intel_sbi_write(dev_priv, 0x8008, tmp, SBI_MPHY);
8448
8449         tmp = intel_sbi_read(dev_priv, 0x2008, SBI_MPHY);
8450         tmp |= (1 << 11);
8451         intel_sbi_write(dev_priv, 0x2008, tmp, SBI_MPHY);
8452
8453         tmp = intel_sbi_read(dev_priv, 0x2108, SBI_MPHY);
8454         tmp |= (1 << 11);
8455         intel_sbi_write(dev_priv, 0x2108, tmp, SBI_MPHY);
8456
8457         tmp = intel_sbi_read(dev_priv, 0x206C, SBI_MPHY);
8458         tmp |= (1 << 24) | (1 << 21) | (1 << 18);
8459         intel_sbi_write(dev_priv, 0x206C, tmp, SBI_MPHY);
8460
8461         tmp = intel_sbi_read(dev_priv, 0x216C, SBI_MPHY);
8462         tmp |= (1 << 24) | (1 << 21) | (1 << 18);
8463         intel_sbi_write(dev_priv, 0x216C, tmp, SBI_MPHY);
8464
8465         tmp = intel_sbi_read(dev_priv, 0x2080, SBI_MPHY);
8466         tmp &= ~(7 << 13);
8467         tmp |= (5 << 13);
8468         intel_sbi_write(dev_priv, 0x2080, tmp, SBI_MPHY);
8469
8470         tmp = intel_sbi_read(dev_priv, 0x2180, SBI_MPHY);
8471         tmp &= ~(7 << 13);
8472         tmp |= (5 << 13);
8473         intel_sbi_write(dev_priv, 0x2180, tmp, SBI_MPHY);
8474
8475         tmp = intel_sbi_read(dev_priv, 0x208C, SBI_MPHY);
8476         tmp &= ~0xFF;
8477         tmp |= 0x1C;
8478         intel_sbi_write(dev_priv, 0x208C, tmp, SBI_MPHY);
8479
8480         tmp = intel_sbi_read(dev_priv, 0x218C, SBI_MPHY);
8481         tmp &= ~0xFF;
8482         tmp |= 0x1C;
8483         intel_sbi_write(dev_priv, 0x218C, tmp, SBI_MPHY);
8484
8485         tmp = intel_sbi_read(dev_priv, 0x2098, SBI_MPHY);
8486         tmp &= ~(0xFF << 16);
8487         tmp |= (0x1C << 16);
8488         intel_sbi_write(dev_priv, 0x2098, tmp, SBI_MPHY);
8489
8490         tmp = intel_sbi_read(dev_priv, 0x2198, SBI_MPHY);
8491         tmp &= ~(0xFF << 16);
8492         tmp |= (0x1C << 16);
8493         intel_sbi_write(dev_priv, 0x2198, tmp, SBI_MPHY);
8494
8495         tmp = intel_sbi_read(dev_priv, 0x20C4, SBI_MPHY);
8496         tmp |= (1 << 27);
8497         intel_sbi_write(dev_priv, 0x20C4, tmp, SBI_MPHY);
8498
8499         tmp = intel_sbi_read(dev_priv, 0x21C4, SBI_MPHY);
8500         tmp |= (1 << 27);
8501         intel_sbi_write(dev_priv, 0x21C4, tmp, SBI_MPHY);
8502
8503         tmp = intel_sbi_read(dev_priv, 0x20EC, SBI_MPHY);
8504         tmp &= ~(0xF << 28);
8505         tmp |= (4 << 28);
8506         intel_sbi_write(dev_priv, 0x20EC, tmp, SBI_MPHY);
8507
8508         tmp = intel_sbi_read(dev_priv, 0x21EC, SBI_MPHY);
8509         tmp &= ~(0xF << 28);
8510         tmp |= (4 << 28);
8511         intel_sbi_write(dev_priv, 0x21EC, tmp, SBI_MPHY);
8512 }
8513
8514 /* Implements 3 different sequences from BSpec chapter "Display iCLK
8515  * Programming" based on the parameters passed:
8516  * - Sequence to enable CLKOUT_DP
8517  * - Sequence to enable CLKOUT_DP without spread
8518  * - Sequence to enable CLKOUT_DP for FDI usage and configure PCH FDI I/O
8519  */
8520 static void lpt_enable_clkout_dp(struct drm_device *dev, bool with_spread,
8521                                  bool with_fdi)
8522 {
8523         struct drm_i915_private *dev_priv = dev->dev_private;
8524         uint32_t reg, tmp;
8525
8526         if (WARN(with_fdi && !with_spread, "FDI requires downspread\n"))
8527                 with_spread = true;
8528         if (WARN(HAS_PCH_LPT_LP(dev) && with_fdi, "LP PCH doesn't have FDI\n"))
8529                 with_fdi = false;
8530
8531         mutex_lock(&dev_priv->sb_lock);
8532
8533         tmp = intel_sbi_read(dev_priv, SBI_SSCCTL, SBI_ICLK);
8534         tmp &= ~SBI_SSCCTL_DISABLE;
8535         tmp |= SBI_SSCCTL_PATHALT;
8536         intel_sbi_write(dev_priv, SBI_SSCCTL, tmp, SBI_ICLK);
8537
8538         udelay(24);
8539
8540         if (with_spread) {
8541                 tmp = intel_sbi_read(dev_priv, SBI_SSCCTL, SBI_ICLK);
8542                 tmp &= ~SBI_SSCCTL_PATHALT;
8543                 intel_sbi_write(dev_priv, SBI_SSCCTL, tmp, SBI_ICLK);
8544
8545                 if (with_fdi) {
8546                         lpt_reset_fdi_mphy(dev_priv);
8547                         lpt_program_fdi_mphy(dev_priv);
8548                 }
8549         }
8550
8551         reg = HAS_PCH_LPT_LP(dev) ? SBI_GEN0 : SBI_DBUFF0;
8552         tmp = intel_sbi_read(dev_priv, reg, SBI_ICLK);
8553         tmp |= SBI_GEN0_CFG_BUFFENABLE_DISABLE;
8554         intel_sbi_write(dev_priv, reg, tmp, SBI_ICLK);
8555
8556         mutex_unlock(&dev_priv->sb_lock);
8557 }
8558
8559 /* Sequence to disable CLKOUT_DP */
8560 static void lpt_disable_clkout_dp(struct drm_device *dev)
8561 {
8562         struct drm_i915_private *dev_priv = dev->dev_private;
8563         uint32_t reg, tmp;
8564
8565         mutex_lock(&dev_priv->sb_lock);
8566
8567         reg = HAS_PCH_LPT_LP(dev) ? SBI_GEN0 : SBI_DBUFF0;
8568         tmp = intel_sbi_read(dev_priv, reg, SBI_ICLK);
8569         tmp &= ~SBI_GEN0_CFG_BUFFENABLE_DISABLE;
8570         intel_sbi_write(dev_priv, reg, tmp, SBI_ICLK);
8571
8572         tmp = intel_sbi_read(dev_priv, SBI_SSCCTL, SBI_ICLK);
8573         if (!(tmp & SBI_SSCCTL_DISABLE)) {
8574                 if (!(tmp & SBI_SSCCTL_PATHALT)) {
8575                         tmp |= SBI_SSCCTL_PATHALT;
8576                         intel_sbi_write(dev_priv, SBI_SSCCTL, tmp, SBI_ICLK);
8577                         udelay(32);
8578                 }
8579                 tmp |= SBI_SSCCTL_DISABLE;
8580                 intel_sbi_write(dev_priv, SBI_SSCCTL, tmp, SBI_ICLK);
8581         }
8582
8583         mutex_unlock(&dev_priv->sb_lock);
8584 }
8585
8586 #define BEND_IDX(steps) ((50 + (steps)) / 5)
8587
8588 static const uint16_t sscdivintphase[] = {
8589         [BEND_IDX( 50)] = 0x3B23,
8590         [BEND_IDX( 45)] = 0x3B23,
8591         [BEND_IDX( 40)] = 0x3C23,
8592         [BEND_IDX( 35)] = 0x3C23,
8593         [BEND_IDX( 30)] = 0x3D23,
8594         [BEND_IDX( 25)] = 0x3D23,
8595         [BEND_IDX( 20)] = 0x3E23,
8596         [BEND_IDX( 15)] = 0x3E23,
8597         [BEND_IDX( 10)] = 0x3F23,
8598         [BEND_IDX(  5)] = 0x3F23,
8599         [BEND_IDX(  0)] = 0x0025,
8600         [BEND_IDX( -5)] = 0x0025,
8601         [BEND_IDX(-10)] = 0x0125,
8602         [BEND_IDX(-15)] = 0x0125,
8603         [BEND_IDX(-20)] = 0x0225,
8604         [BEND_IDX(-25)] = 0x0225,
8605         [BEND_IDX(-30)] = 0x0325,
8606         [BEND_IDX(-35)] = 0x0325,
8607         [BEND_IDX(-40)] = 0x0425,
8608         [BEND_IDX(-45)] = 0x0425,
8609         [BEND_IDX(-50)] = 0x0525,
8610 };
8611
8612 /*
8613  * Bend CLKOUT_DP
8614  * steps -50 to 50 inclusive, in steps of 5
8615  * < 0 slow down the clock, > 0 speed up the clock, 0 == no bend (135MHz)
8616  * change in clock period = -(steps / 10) * 5.787 ps
8617  */
8618 static void lpt_bend_clkout_dp(struct drm_i915_private *dev_priv, int steps)
8619 {
8620         uint32_t tmp;
8621         int idx = BEND_IDX(steps);
8622
8623         if (WARN_ON(steps % 5 != 0))
8624                 return;
8625
8626         if (WARN_ON(idx >= ARRAY_SIZE(sscdivintphase)))
8627                 return;
8628
8629         mutex_lock(&dev_priv->sb_lock);
8630
8631         if (steps % 10 != 0)
8632                 tmp = 0xAAAAAAAB;
8633         else
8634                 tmp = 0x00000000;
8635         intel_sbi_write(dev_priv, SBI_SSCDITHPHASE, tmp, SBI_ICLK);
8636
8637         tmp = intel_sbi_read(dev_priv, SBI_SSCDIVINTPHASE, SBI_ICLK);
8638         tmp &= 0xffff0000;
8639         tmp |= sscdivintphase[idx];
8640         intel_sbi_write(dev_priv, SBI_SSCDIVINTPHASE, tmp, SBI_ICLK);
8641
8642         mutex_unlock(&dev_priv->sb_lock);
8643 }
8644
8645 #undef BEND_IDX
8646
8647 static void lpt_init_pch_refclk(struct drm_device *dev)
8648 {
8649         struct intel_encoder *encoder;
8650         bool has_vga = false;
8651
8652         for_each_intel_encoder(dev, encoder) {
8653                 switch (encoder->type) {
8654                 case INTEL_OUTPUT_ANALOG:
8655                         has_vga = true;
8656                         break;
8657                 default:
8658                         break;
8659                 }
8660         }
8661
8662         if (has_vga) {
8663                 lpt_bend_clkout_dp(to_i915(dev), 0);
8664                 lpt_enable_clkout_dp(dev, true, true);
8665         } else {
8666                 lpt_disable_clkout_dp(dev);
8667         }
8668 }
8669
8670 /*
8671  * Initialize reference clocks when the driver loads
8672  */
8673 void intel_init_pch_refclk(struct drm_device *dev)
8674 {
8675         if (HAS_PCH_IBX(dev) || HAS_PCH_CPT(dev))
8676                 ironlake_init_pch_refclk(dev);
8677         else if (HAS_PCH_LPT(dev))
8678                 lpt_init_pch_refclk(dev);
8679 }
8680
8681 static int ironlake_get_refclk(struct intel_crtc_state *crtc_state)
8682 {
8683         struct drm_device *dev = crtc_state->base.crtc->dev;
8684         struct drm_i915_private *dev_priv = dev->dev_private;
8685         struct drm_atomic_state *state = crtc_state->base.state;
8686         struct drm_connector *connector;
8687         struct drm_connector_state *connector_state;
8688         struct intel_encoder *encoder;
8689         int num_connectors = 0, i;
8690         bool is_lvds = false;
8691
8692         for_each_connector_in_state(state, connector, connector_state, i) {
8693                 if (connector_state->crtc != crtc_state->base.crtc)
8694                         continue;
8695
8696                 encoder = to_intel_encoder(connector_state->best_encoder);
8697
8698                 switch (encoder->type) {
8699                 case INTEL_OUTPUT_LVDS:
8700                         is_lvds = true;
8701                         break;
8702                 default:
8703                         break;
8704                 }
8705                 num_connectors++;
8706         }
8707
8708         if (is_lvds && intel_panel_use_ssc(dev_priv) && num_connectors < 2) {
8709                 DRM_DEBUG_KMS("using SSC reference clock of %d kHz\n",
8710                               dev_priv->vbt.lvds_ssc_freq);
8711                 return dev_priv->vbt.lvds_ssc_freq;
8712         }
8713
8714         return 120000;
8715 }
8716
8717 static void ironlake_set_pipeconf(struct drm_crtc *crtc)
8718 {
8719         struct drm_i915_private *dev_priv = crtc->dev->dev_private;
8720         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
8721         int pipe = intel_crtc->pipe;
8722         uint32_t val;
8723
8724         val = 0;
8725
8726         switch (intel_crtc->config->pipe_bpp) {
8727         case 18:
8728                 val |= PIPECONF_6BPC;
8729                 break;
8730         case 24:
8731                 val |= PIPECONF_8BPC;
8732                 break;
8733         case 30:
8734                 val |= PIPECONF_10BPC;
8735                 break;
8736         case 36:
8737                 val |= PIPECONF_12BPC;
8738                 break;
8739         default:
8740                 /* Case prevented by intel_choose_pipe_bpp_dither. */
8741                 BUG();
8742         }
8743
8744         if (intel_crtc->config->dither)
8745                 val |= (PIPECONF_DITHER_EN | PIPECONF_DITHER_TYPE_SP);
8746
8747         if (intel_crtc->config->base.adjusted_mode.flags & DRM_MODE_FLAG_INTERLACE)
8748                 val |= PIPECONF_INTERLACED_ILK;
8749         else
8750                 val |= PIPECONF_PROGRESSIVE;
8751
8752         if (intel_crtc->config->limited_color_range)
8753                 val |= PIPECONF_COLOR_RANGE_SELECT;
8754
8755         I915_WRITE(PIPECONF(pipe), val);
8756         POSTING_READ(PIPECONF(pipe));
8757 }
8758
8759 /*
8760  * Set up the pipe CSC unit.
8761  *
8762  * Currently only full range RGB to limited range RGB conversion
8763  * is supported, but eventually this should handle various
8764  * RGB<->YCbCr scenarios as well.
8765  */
8766 static void intel_set_pipe_csc(struct drm_crtc *crtc)
8767 {
8768         struct drm_device *dev = crtc->dev;
8769         struct drm_i915_private *dev_priv = dev->dev_private;
8770         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
8771         int pipe = intel_crtc->pipe;
8772         uint16_t coeff = 0x7800; /* 1.0 */
8773
8774         /*
8775          * TODO: Check what kind of values actually come out of the pipe
8776          * with these coeff/postoff values and adjust to get the best
8777          * accuracy. Perhaps we even need to take the bpc value into
8778          * consideration.
8779          */
8780
8781         if (intel_crtc->config->limited_color_range)
8782                 coeff = ((235 - 16) * (1 << 12) / 255) & 0xff8; /* 0.xxx... */
8783
8784         /*
8785          * GY/GU and RY/RU should be the other way around according
8786          * to BSpec, but reality doesn't agree. Just set them up in
8787          * a way that results in the correct picture.
8788          */
8789         I915_WRITE(PIPE_CSC_COEFF_RY_GY(pipe), coeff << 16);
8790         I915_WRITE(PIPE_CSC_COEFF_BY(pipe), 0);
8791
8792         I915_WRITE(PIPE_CSC_COEFF_RU_GU(pipe), coeff);
8793         I915_WRITE(PIPE_CSC_COEFF_BU(pipe), 0);
8794
8795         I915_WRITE(PIPE_CSC_COEFF_RV_GV(pipe), 0);
8796         I915_WRITE(PIPE_CSC_COEFF_BV(pipe), coeff << 16);
8797
8798         I915_WRITE(PIPE_CSC_PREOFF_HI(pipe), 0);
8799         I915_WRITE(PIPE_CSC_PREOFF_ME(pipe), 0);
8800         I915_WRITE(PIPE_CSC_PREOFF_LO(pipe), 0);
8801
8802         if (INTEL_INFO(dev)->gen > 6) {
8803                 uint16_t postoff = 0;
8804
8805                 if (intel_crtc->config->limited_color_range)
8806                         postoff = (16 * (1 << 12) / 255) & 0x1fff;
8807
8808                 I915_WRITE(PIPE_CSC_POSTOFF_HI(pipe), postoff);
8809                 I915_WRITE(PIPE_CSC_POSTOFF_ME(pipe), postoff);
8810                 I915_WRITE(PIPE_CSC_POSTOFF_LO(pipe), postoff);
8811
8812                 I915_WRITE(PIPE_CSC_MODE(pipe), 0);
8813         } else {
8814                 uint32_t mode = CSC_MODE_YUV_TO_RGB;
8815
8816                 if (intel_crtc->config->limited_color_range)
8817                         mode |= CSC_BLACK_SCREEN_OFFSET;
8818
8819                 I915_WRITE(PIPE_CSC_MODE(pipe), mode);
8820         }
8821 }
8822
8823 static void haswell_set_pipeconf(struct drm_crtc *crtc)
8824 {
8825         struct drm_device *dev = crtc->dev;
8826         struct drm_i915_private *dev_priv = dev->dev_private;
8827         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
8828         enum pipe pipe = intel_crtc->pipe;
8829         enum transcoder cpu_transcoder = intel_crtc->config->cpu_transcoder;
8830         uint32_t val;
8831
8832         val = 0;
8833
8834         if (IS_HASWELL(dev) && intel_crtc->config->dither)
8835                 val |= (PIPECONF_DITHER_EN | PIPECONF_DITHER_TYPE_SP);
8836
8837         if (intel_crtc->config->base.adjusted_mode.flags & DRM_MODE_FLAG_INTERLACE)
8838                 val |= PIPECONF_INTERLACED_ILK;
8839         else
8840                 val |= PIPECONF_PROGRESSIVE;
8841
8842         I915_WRITE(PIPECONF(cpu_transcoder), val);
8843         POSTING_READ(PIPECONF(cpu_transcoder));
8844
8845         I915_WRITE(GAMMA_MODE(intel_crtc->pipe), GAMMA_MODE_MODE_8BIT);
8846         POSTING_READ(GAMMA_MODE(intel_crtc->pipe));
8847
8848         if (IS_BROADWELL(dev) || INTEL_INFO(dev)->gen >= 9) {
8849                 val = 0;
8850
8851                 switch (intel_crtc->config->pipe_bpp) {
8852                 case 18:
8853                         val |= PIPEMISC_DITHER_6_BPC;
8854                         break;
8855                 case 24:
8856                         val |= PIPEMISC_DITHER_8_BPC;
8857                         break;
8858                 case 30:
8859                         val |= PIPEMISC_DITHER_10_BPC;
8860                         break;
8861                 case 36:
8862                         val |= PIPEMISC_DITHER_12_BPC;
8863                         break;
8864                 default:
8865                         /* Case prevented by pipe_config_set_bpp. */
8866                         BUG();
8867                 }
8868
8869                 if (intel_crtc->config->dither)
8870                         val |= PIPEMISC_DITHER_ENABLE | PIPEMISC_DITHER_TYPE_SP;
8871
8872                 I915_WRITE(PIPEMISC(pipe), val);
8873         }
8874 }
8875
8876 static bool ironlake_compute_clocks(struct drm_crtc *crtc,
8877                                     struct intel_crtc_state *crtc_state,
8878                                     intel_clock_t *clock,
8879                                     bool *has_reduced_clock,
8880                                     intel_clock_t *reduced_clock)
8881 {
8882         struct drm_device *dev = crtc->dev;
8883         struct drm_i915_private *dev_priv = dev->dev_private;
8884         int refclk;
8885         const intel_limit_t *limit;
8886         bool ret;
8887
8888         refclk = ironlake_get_refclk(crtc_state);
8889
8890         /*
8891          * Returns a set of divisors for the desired target clock with the given
8892          * refclk, or FALSE.  The returned values represent the clock equation:
8893          * reflck * (5 * (m1 + 2) + (m2 + 2)) / (n + 2) / p1 / p2.
8894          */
8895         limit = intel_limit(crtc_state, refclk);
8896         ret = dev_priv->display.find_dpll(limit, crtc_state,
8897                                           crtc_state->port_clock,
8898                                           refclk, NULL, clock);
8899         if (!ret)
8900                 return false;
8901
8902         return true;
8903 }
8904
8905 int ironlake_get_lanes_required(int target_clock, int link_bw, int bpp)
8906 {
8907         /*
8908          * Account for spread spectrum to avoid
8909          * oversubscribing the link. Max center spread
8910          * is 2.5%; use 5% for safety's sake.
8911          */
8912         u32 bps = target_clock * bpp * 21 / 20;
8913         return DIV_ROUND_UP(bps, link_bw * 8);
8914 }
8915
8916 static bool ironlake_needs_fb_cb_tune(struct dpll *dpll, int factor)
8917 {
8918         return i9xx_dpll_compute_m(dpll) < factor * dpll->n;
8919 }
8920
8921 static uint32_t ironlake_compute_dpll(struct intel_crtc *intel_crtc,
8922                                       struct intel_crtc_state *crtc_state,
8923                                       u32 *fp,
8924                                       intel_clock_t *reduced_clock, u32 *fp2)
8925 {
8926         struct drm_crtc *crtc = &intel_crtc->base;
8927         struct drm_device *dev = crtc->dev;
8928         struct drm_i915_private *dev_priv = dev->dev_private;
8929         struct drm_atomic_state *state = crtc_state->base.state;
8930         struct drm_connector *connector;
8931         struct drm_connector_state *connector_state;
8932         struct intel_encoder *encoder;
8933         uint32_t dpll;
8934         int factor, num_connectors = 0, i;
8935         bool is_lvds = false, is_sdvo = false;
8936
8937         for_each_connector_in_state(state, connector, connector_state, i) {
8938                 if (connector_state->crtc != crtc_state->base.crtc)
8939                         continue;
8940
8941                 encoder = to_intel_encoder(connector_state->best_encoder);
8942
8943                 switch (encoder->type) {
8944                 case INTEL_OUTPUT_LVDS:
8945                         is_lvds = true;
8946                         break;
8947                 case INTEL_OUTPUT_SDVO:
8948                 case INTEL_OUTPUT_HDMI:
8949                         is_sdvo = true;
8950                         break;
8951                 default:
8952                         break;
8953                 }
8954
8955                 num_connectors++;
8956         }
8957
8958         /* Enable autotuning of the PLL clock (if permissible) */
8959         factor = 21;
8960         if (is_lvds) {
8961                 if ((intel_panel_use_ssc(dev_priv) &&
8962                      dev_priv->vbt.lvds_ssc_freq == 100000) ||
8963                     (HAS_PCH_IBX(dev) && intel_is_dual_link_lvds(dev)))
8964                         factor = 25;
8965         } else if (crtc_state->sdvo_tv_clock)
8966                 factor = 20;
8967
8968         if (ironlake_needs_fb_cb_tune(&crtc_state->dpll, factor))
8969                 *fp |= FP_CB_TUNE;
8970
8971         if (fp2 && (reduced_clock->m < factor * reduced_clock->n))
8972                 *fp2 |= FP_CB_TUNE;
8973
8974         dpll = 0;
8975
8976         if (is_lvds)
8977                 dpll |= DPLLB_MODE_LVDS;
8978         else
8979                 dpll |= DPLLB_MODE_DAC_SERIAL;
8980
8981         dpll |= (crtc_state->pixel_multiplier - 1)
8982                 << PLL_REF_SDVO_HDMI_MULTIPLIER_SHIFT;
8983
8984         if (is_sdvo)
8985                 dpll |= DPLL_SDVO_HIGH_SPEED;
8986         if (crtc_state->has_dp_encoder)
8987                 dpll |= DPLL_SDVO_HIGH_SPEED;
8988
8989         /* compute bitmask from p1 value */
8990         dpll |= (1 << (crtc_state->dpll.p1 - 1)) << DPLL_FPA01_P1_POST_DIV_SHIFT;
8991         /* also FPA1 */
8992         dpll |= (1 << (crtc_state->dpll.p1 - 1)) << DPLL_FPA1_P1_POST_DIV_SHIFT;
8993
8994         switch (crtc_state->dpll.p2) {
8995         case 5:
8996                 dpll |= DPLL_DAC_SERIAL_P2_CLOCK_DIV_5;
8997                 break;
8998         case 7:
8999                 dpll |= DPLLB_LVDS_P2_CLOCK_DIV_7;
9000                 break;
9001         case 10:
9002                 dpll |= DPLL_DAC_SERIAL_P2_CLOCK_DIV_10;
9003                 break;
9004         case 14:
9005                 dpll |= DPLLB_LVDS_P2_CLOCK_DIV_14;
9006                 break;
9007         }
9008
9009         if (is_lvds && intel_panel_use_ssc(dev_priv) && num_connectors < 2)
9010                 dpll |= PLLB_REF_INPUT_SPREADSPECTRUMIN;
9011         else
9012                 dpll |= PLL_REF_INPUT_DREFCLK;
9013
9014         return dpll | DPLL_VCO_ENABLE;
9015 }
9016
9017 static int ironlake_crtc_compute_clock(struct intel_crtc *crtc,
9018                                        struct intel_crtc_state *crtc_state)
9019 {
9020         struct drm_device *dev = crtc->base.dev;
9021         intel_clock_t clock, reduced_clock;
9022         u32 dpll = 0, fp = 0, fp2 = 0;
9023         bool ok, has_reduced_clock = false;
9024         bool is_lvds = false;
9025         struct intel_shared_dpll *pll;
9026
9027         memset(&crtc_state->dpll_hw_state, 0,
9028                sizeof(crtc_state->dpll_hw_state));
9029
9030         is_lvds = intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_LVDS);
9031
9032         WARN(!(HAS_PCH_IBX(dev) || HAS_PCH_CPT(dev)),
9033              "Unexpected PCH type %d\n", INTEL_PCH_TYPE(dev));
9034
9035         ok = ironlake_compute_clocks(&crtc->base, crtc_state, &clock,
9036                                      &has_reduced_clock, &reduced_clock);
9037         if (!ok && !crtc_state->clock_set) {
9038                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
9039                 return -EINVAL;
9040         }
9041         /* Compat-code for transition, will disappear. */
9042         if (!crtc_state->clock_set) {
9043                 crtc_state->dpll.n = clock.n;
9044                 crtc_state->dpll.m1 = clock.m1;
9045                 crtc_state->dpll.m2 = clock.m2;
9046                 crtc_state->dpll.p1 = clock.p1;
9047                 crtc_state->dpll.p2 = clock.p2;
9048         }
9049
9050         /* CPU eDP is the only output that doesn't need a PCH PLL of its own. */
9051         if (crtc_state->has_pch_encoder) {
9052                 fp = i9xx_dpll_compute_fp(&crtc_state->dpll);
9053                 if (has_reduced_clock)
9054                         fp2 = i9xx_dpll_compute_fp(&reduced_clock);
9055
9056                 dpll = ironlake_compute_dpll(crtc, crtc_state,
9057                                              &fp, &reduced_clock,
9058                                              has_reduced_clock ? &fp2 : NULL);
9059
9060                 crtc_state->dpll_hw_state.dpll = dpll;
9061                 crtc_state->dpll_hw_state.fp0 = fp;
9062                 if (has_reduced_clock)
9063                         crtc_state->dpll_hw_state.fp1 = fp2;
9064                 else
9065                         crtc_state->dpll_hw_state.fp1 = fp;
9066
9067                 pll = intel_get_shared_dpll(crtc, crtc_state);
9068                 if (pll == NULL) {
9069                         DRM_DEBUG_DRIVER("failed to find PLL for pipe %c\n",
9070                                          pipe_name(crtc->pipe));
9071                         return -EINVAL;
9072                 }
9073         }
9074
9075         if (is_lvds && has_reduced_clock)
9076                 crtc->lowfreq_avail = true;
9077         else
9078                 crtc->lowfreq_avail = false;
9079
9080         return 0;
9081 }
9082
9083 static void intel_pch_transcoder_get_m_n(struct intel_crtc *crtc,
9084                                          struct intel_link_m_n *m_n)
9085 {
9086         struct drm_device *dev = crtc->base.dev;
9087         struct drm_i915_private *dev_priv = dev->dev_private;
9088         enum pipe pipe = crtc->pipe;
9089
9090         m_n->link_m = I915_READ(PCH_TRANS_LINK_M1(pipe));
9091         m_n->link_n = I915_READ(PCH_TRANS_LINK_N1(pipe));
9092         m_n->gmch_m = I915_READ(PCH_TRANS_DATA_M1(pipe))
9093                 & ~TU_SIZE_MASK;
9094         m_n->gmch_n = I915_READ(PCH_TRANS_DATA_N1(pipe));
9095         m_n->tu = ((I915_READ(PCH_TRANS_DATA_M1(pipe))
9096                     & TU_SIZE_MASK) >> TU_SIZE_SHIFT) + 1;
9097 }
9098
9099 static void intel_cpu_transcoder_get_m_n(struct intel_crtc *crtc,
9100                                          enum transcoder transcoder,
9101                                          struct intel_link_m_n *m_n,
9102                                          struct intel_link_m_n *m2_n2)
9103 {
9104         struct drm_device *dev = crtc->base.dev;
9105         struct drm_i915_private *dev_priv = dev->dev_private;
9106         enum pipe pipe = crtc->pipe;
9107
9108         if (INTEL_INFO(dev)->gen >= 5) {
9109                 m_n->link_m = I915_READ(PIPE_LINK_M1(transcoder));
9110                 m_n->link_n = I915_READ(PIPE_LINK_N1(transcoder));
9111                 m_n->gmch_m = I915_READ(PIPE_DATA_M1(transcoder))
9112                         & ~TU_SIZE_MASK;
9113                 m_n->gmch_n = I915_READ(PIPE_DATA_N1(transcoder));
9114                 m_n->tu = ((I915_READ(PIPE_DATA_M1(transcoder))
9115                             & TU_SIZE_MASK) >> TU_SIZE_SHIFT) + 1;
9116                 /* Read M2_N2 registers only for gen < 8 (M2_N2 available for
9117                  * gen < 8) and if DRRS is supported (to make sure the
9118                  * registers are not unnecessarily read).
9119                  */
9120                 if (m2_n2 && INTEL_INFO(dev)->gen < 8 &&
9121                         crtc->config->has_drrs) {
9122                         m2_n2->link_m = I915_READ(PIPE_LINK_M2(transcoder));
9123                         m2_n2->link_n = I915_READ(PIPE_LINK_N2(transcoder));
9124                         m2_n2->gmch_m = I915_READ(PIPE_DATA_M2(transcoder))
9125                                         & ~TU_SIZE_MASK;
9126                         m2_n2->gmch_n = I915_READ(PIPE_DATA_N2(transcoder));
9127                         m2_n2->tu = ((I915_READ(PIPE_DATA_M2(transcoder))
9128                                         & TU_SIZE_MASK) >> TU_SIZE_SHIFT) + 1;
9129                 }
9130         } else {
9131                 m_n->link_m = I915_READ(PIPE_LINK_M_G4X(pipe));
9132                 m_n->link_n = I915_READ(PIPE_LINK_N_G4X(pipe));
9133                 m_n->gmch_m = I915_READ(PIPE_DATA_M_G4X(pipe))
9134                         & ~TU_SIZE_MASK;
9135                 m_n->gmch_n = I915_READ(PIPE_DATA_N_G4X(pipe));
9136                 m_n->tu = ((I915_READ(PIPE_DATA_M_G4X(pipe))
9137                             & TU_SIZE_MASK) >> TU_SIZE_SHIFT) + 1;
9138         }
9139 }
9140
9141 void intel_dp_get_m_n(struct intel_crtc *crtc,
9142                       struct intel_crtc_state *pipe_config)
9143 {
9144         if (pipe_config->has_pch_encoder)
9145                 intel_pch_transcoder_get_m_n(crtc, &pipe_config->dp_m_n);
9146         else
9147                 intel_cpu_transcoder_get_m_n(crtc, pipe_config->cpu_transcoder,
9148                                              &pipe_config->dp_m_n,
9149                                              &pipe_config->dp_m2_n2);
9150 }
9151
9152 static void ironlake_get_fdi_m_n_config(struct intel_crtc *crtc,
9153                                         struct intel_crtc_state *pipe_config)
9154 {
9155         intel_cpu_transcoder_get_m_n(crtc, pipe_config->cpu_transcoder,
9156                                      &pipe_config->fdi_m_n, NULL);
9157 }
9158
9159 static void skylake_get_pfit_config(struct intel_crtc *crtc,
9160                                     struct intel_crtc_state *pipe_config)
9161 {
9162         struct drm_device *dev = crtc->base.dev;
9163         struct drm_i915_private *dev_priv = dev->dev_private;
9164         struct intel_crtc_scaler_state *scaler_state = &pipe_config->scaler_state;
9165         uint32_t ps_ctrl = 0;
9166         int id = -1;
9167         int i;
9168
9169         /* find scaler attached to this pipe */
9170         for (i = 0; i < crtc->num_scalers; i++) {
9171                 ps_ctrl = I915_READ(SKL_PS_CTRL(crtc->pipe, i));
9172                 if (ps_ctrl & PS_SCALER_EN && !(ps_ctrl & PS_PLANE_SEL_MASK)) {
9173                         id = i;
9174                         pipe_config->pch_pfit.enabled = true;
9175                         pipe_config->pch_pfit.pos = I915_READ(SKL_PS_WIN_POS(crtc->pipe, i));
9176                         pipe_config->pch_pfit.size = I915_READ(SKL_PS_WIN_SZ(crtc->pipe, i));
9177                         break;
9178                 }
9179         }
9180
9181         scaler_state->scaler_id = id;
9182         if (id >= 0) {
9183                 scaler_state->scaler_users |= (1 << SKL_CRTC_INDEX);
9184         } else {
9185                 scaler_state->scaler_users &= ~(1 << SKL_CRTC_INDEX);
9186         }
9187 }
9188
9189 static void
9190 skylake_get_initial_plane_config(struct intel_crtc *crtc,
9191                                  struct intel_initial_plane_config *plane_config)
9192 {
9193         struct drm_device *dev = crtc->base.dev;
9194         struct drm_i915_private *dev_priv = dev->dev_private;
9195         u32 val, base, offset, stride_mult, tiling;
9196         int pipe = crtc->pipe;
9197         int fourcc, pixel_format;
9198         unsigned int aligned_height;
9199         struct drm_framebuffer *fb;
9200         struct intel_framebuffer *intel_fb;
9201
9202         intel_fb = kzalloc(sizeof(*intel_fb), GFP_KERNEL);
9203         if (!intel_fb) {
9204                 DRM_DEBUG_KMS("failed to alloc fb\n");
9205                 return;
9206         }
9207
9208         fb = &intel_fb->base;
9209
9210         val = I915_READ(PLANE_CTL(pipe, 0));
9211         if (!(val & PLANE_CTL_ENABLE))
9212                 goto error;
9213
9214         pixel_format = val & PLANE_CTL_FORMAT_MASK;
9215         fourcc = skl_format_to_fourcc(pixel_format,
9216                                       val & PLANE_CTL_ORDER_RGBX,
9217                                       val & PLANE_CTL_ALPHA_MASK);
9218         fb->pixel_format = fourcc;
9219         fb->bits_per_pixel = drm_format_plane_cpp(fourcc, 0) * 8;
9220
9221         tiling = val & PLANE_CTL_TILED_MASK;
9222         switch (tiling) {
9223         case PLANE_CTL_TILED_LINEAR:
9224                 fb->modifier[0] = DRM_FORMAT_MOD_NONE;
9225                 break;
9226         case PLANE_CTL_TILED_X:
9227                 plane_config->tiling = I915_TILING_X;
9228                 fb->modifier[0] = I915_FORMAT_MOD_X_TILED;
9229                 break;
9230         case PLANE_CTL_TILED_Y:
9231                 fb->modifier[0] = I915_FORMAT_MOD_Y_TILED;
9232                 break;
9233         case PLANE_CTL_TILED_YF:
9234                 fb->modifier[0] = I915_FORMAT_MOD_Yf_TILED;
9235                 break;
9236         default:
9237                 MISSING_CASE(tiling);
9238                 goto error;
9239         }
9240
9241         base = I915_READ(PLANE_SURF(pipe, 0)) & 0xfffff000;
9242         plane_config->base = base;
9243
9244         offset = I915_READ(PLANE_OFFSET(pipe, 0));
9245
9246         val = I915_READ(PLANE_SIZE(pipe, 0));
9247         fb->height = ((val >> 16) & 0xfff) + 1;
9248         fb->width = ((val >> 0) & 0x1fff) + 1;
9249
9250         val = I915_READ(PLANE_STRIDE(pipe, 0));
9251         stride_mult = intel_fb_stride_alignment(dev, fb->modifier[0],
9252                                                 fb->pixel_format);
9253         fb->pitches[0] = (val & 0x3ff) * stride_mult;
9254
9255         aligned_height = intel_fb_align_height(dev, fb->height,
9256                                                fb->pixel_format,
9257                                                fb->modifier[0]);
9258
9259         plane_config->size = fb->pitches[0] * aligned_height;
9260
9261         DRM_DEBUG_KMS("pipe %c with fb: size=%dx%d@%d, offset=%x, pitch %d, size 0x%x\n",
9262                       pipe_name(pipe), fb->width, fb->height,
9263                       fb->bits_per_pixel, base, fb->pitches[0],
9264                       plane_config->size);
9265
9266         plane_config->fb = intel_fb;
9267         return;
9268
9269 error:
9270         kfree(fb);
9271 }
9272
9273 static void ironlake_get_pfit_config(struct intel_crtc *crtc,
9274                                      struct intel_crtc_state *pipe_config)
9275 {
9276         struct drm_device *dev = crtc->base.dev;
9277         struct drm_i915_private *dev_priv = dev->dev_private;
9278         uint32_t tmp;
9279
9280         tmp = I915_READ(PF_CTL(crtc->pipe));
9281
9282         if (tmp & PF_ENABLE) {
9283                 pipe_config->pch_pfit.enabled = true;
9284                 pipe_config->pch_pfit.pos = I915_READ(PF_WIN_POS(crtc->pipe));
9285                 pipe_config->pch_pfit.size = I915_READ(PF_WIN_SZ(crtc->pipe));
9286
9287                 /* We currently do not free assignements of panel fitters on
9288                  * ivb/hsw (since we don't use the higher upscaling modes which
9289                  * differentiates them) so just WARN about this case for now. */
9290                 if (IS_GEN7(dev)) {
9291                         WARN_ON((tmp & PF_PIPE_SEL_MASK_IVB) !=
9292                                 PF_PIPE_SEL_IVB(crtc->pipe));
9293                 }
9294         }
9295 }
9296
9297 static void
9298 ironlake_get_initial_plane_config(struct intel_crtc *crtc,
9299                                   struct intel_initial_plane_config *plane_config)
9300 {
9301         struct drm_device *dev = crtc->base.dev;
9302         struct drm_i915_private *dev_priv = dev->dev_private;
9303         u32 val, base, offset;
9304         int pipe = crtc->pipe;
9305         int fourcc, pixel_format;
9306         unsigned int aligned_height;
9307         struct drm_framebuffer *fb;
9308         struct intel_framebuffer *intel_fb;
9309
9310         val = I915_READ(DSPCNTR(pipe));
9311         if (!(val & DISPLAY_PLANE_ENABLE))
9312                 return;
9313
9314         intel_fb = kzalloc(sizeof(*intel_fb), GFP_KERNEL);
9315         if (!intel_fb) {
9316                 DRM_DEBUG_KMS("failed to alloc fb\n");
9317                 return;
9318         }
9319
9320         fb = &intel_fb->base;
9321
9322         if (INTEL_INFO(dev)->gen >= 4) {
9323                 if (val & DISPPLANE_TILED) {
9324                         plane_config->tiling = I915_TILING_X;
9325                         fb->modifier[0] = I915_FORMAT_MOD_X_TILED;
9326                 }
9327         }
9328
9329         pixel_format = val & DISPPLANE_PIXFORMAT_MASK;
9330         fourcc = i9xx_format_to_fourcc(pixel_format);
9331         fb->pixel_format = fourcc;
9332         fb->bits_per_pixel = drm_format_plane_cpp(fourcc, 0) * 8;
9333
9334         base = I915_READ(DSPSURF(pipe)) & 0xfffff000;
9335         if (IS_HASWELL(dev) || IS_BROADWELL(dev)) {
9336                 offset = I915_READ(DSPOFFSET(pipe));
9337         } else {
9338                 if (plane_config->tiling)
9339                         offset = I915_READ(DSPTILEOFF(pipe));
9340                 else
9341                         offset = I915_READ(DSPLINOFF(pipe));
9342         }
9343         plane_config->base = base;
9344
9345         val = I915_READ(PIPESRC(pipe));
9346         fb->width = ((val >> 16) & 0xfff) + 1;
9347         fb->height = ((val >> 0) & 0xfff) + 1;
9348
9349         val = I915_READ(DSPSTRIDE(pipe));
9350         fb->pitches[0] = val & 0xffffffc0;
9351
9352         aligned_height = intel_fb_align_height(dev, fb->height,
9353                                                fb->pixel_format,
9354                                                fb->modifier[0]);
9355
9356         plane_config->size = fb->pitches[0] * aligned_height;
9357
9358         DRM_DEBUG_KMS("pipe %c with fb: size=%dx%d@%d, offset=%x, pitch %d, size 0x%x\n",
9359                       pipe_name(pipe), fb->width, fb->height,
9360                       fb->bits_per_pixel, base, fb->pitches[0],
9361                       plane_config->size);
9362
9363         plane_config->fb = intel_fb;
9364 }
9365
9366 static bool ironlake_get_pipe_config(struct intel_crtc *crtc,
9367                                      struct intel_crtc_state *pipe_config)
9368 {
9369         struct drm_device *dev = crtc->base.dev;
9370         struct drm_i915_private *dev_priv = dev->dev_private;
9371         uint32_t tmp;
9372
9373         if (!intel_display_power_is_enabled(dev_priv,
9374                                             POWER_DOMAIN_PIPE(crtc->pipe)))
9375                 return false;
9376
9377         pipe_config->cpu_transcoder = (enum transcoder) crtc->pipe;
9378         pipe_config->shared_dpll = DPLL_ID_PRIVATE;
9379
9380         tmp = I915_READ(PIPECONF(crtc->pipe));
9381         if (!(tmp & PIPECONF_ENABLE))
9382                 return false;
9383
9384         switch (tmp & PIPECONF_BPC_MASK) {
9385         case PIPECONF_6BPC:
9386                 pipe_config->pipe_bpp = 18;
9387                 break;
9388         case PIPECONF_8BPC:
9389                 pipe_config->pipe_bpp = 24;
9390                 break;
9391         case PIPECONF_10BPC:
9392                 pipe_config->pipe_bpp = 30;
9393                 break;
9394         case PIPECONF_12BPC:
9395                 pipe_config->pipe_bpp = 36;
9396                 break;
9397         default:
9398                 break;
9399         }
9400
9401         if (tmp & PIPECONF_COLOR_RANGE_SELECT)
9402                 pipe_config->limited_color_range = true;
9403
9404         if (I915_READ(PCH_TRANSCONF(crtc->pipe)) & TRANS_ENABLE) {
9405                 struct intel_shared_dpll *pll;
9406
9407                 pipe_config->has_pch_encoder = true;
9408
9409                 tmp = I915_READ(FDI_RX_CTL(crtc->pipe));
9410                 pipe_config->fdi_lanes = ((FDI_DP_PORT_WIDTH_MASK & tmp) >>
9411                                           FDI_DP_PORT_WIDTH_SHIFT) + 1;
9412
9413                 ironlake_get_fdi_m_n_config(crtc, pipe_config);
9414
9415                 if (HAS_PCH_IBX(dev_priv->dev)) {
9416                         pipe_config->shared_dpll =
9417                                 (enum intel_dpll_id) crtc->pipe;
9418                 } else {
9419                         tmp = I915_READ(PCH_DPLL_SEL);
9420                         if (tmp & TRANS_DPLLB_SEL(crtc->pipe))
9421                                 pipe_config->shared_dpll = DPLL_ID_PCH_PLL_B;
9422                         else
9423                                 pipe_config->shared_dpll = DPLL_ID_PCH_PLL_A;
9424                 }
9425
9426                 pll = &dev_priv->shared_dplls[pipe_config->shared_dpll];
9427
9428                 WARN_ON(!pll->get_hw_state(dev_priv, pll,
9429                                            &pipe_config->dpll_hw_state));
9430
9431                 tmp = pipe_config->dpll_hw_state.dpll;
9432                 pipe_config->pixel_multiplier =
9433                         ((tmp & PLL_REF_SDVO_HDMI_MULTIPLIER_MASK)
9434                          >> PLL_REF_SDVO_HDMI_MULTIPLIER_SHIFT) + 1;
9435
9436                 ironlake_pch_clock_get(crtc, pipe_config);
9437         } else {
9438                 pipe_config->pixel_multiplier = 1;
9439         }
9440
9441         intel_get_pipe_timings(crtc, pipe_config);
9442
9443         ironlake_get_pfit_config(crtc, pipe_config);
9444
9445         return true;
9446 }
9447
9448 static void assert_can_disable_lcpll(struct drm_i915_private *dev_priv)
9449 {
9450         struct drm_device *dev = dev_priv->dev;
9451         struct intel_crtc *crtc;
9452
9453         for_each_intel_crtc(dev, crtc)
9454                 I915_STATE_WARN(crtc->active, "CRTC for pipe %c enabled\n",
9455                      pipe_name(crtc->pipe));
9456
9457         I915_STATE_WARN(I915_READ(HSW_PWR_WELL_DRIVER), "Power well on\n");
9458         I915_STATE_WARN(I915_READ(SPLL_CTL) & SPLL_PLL_ENABLE, "SPLL enabled\n");
9459         I915_STATE_WARN(I915_READ(WRPLL_CTL(0)) & WRPLL_PLL_ENABLE, "WRPLL1 enabled\n");
9460         I915_STATE_WARN(I915_READ(WRPLL_CTL(1)) & WRPLL_PLL_ENABLE, "WRPLL2 enabled\n");
9461         I915_STATE_WARN(I915_READ(PCH_PP_STATUS) & PP_ON, "Panel power on\n");
9462         I915_STATE_WARN(I915_READ(BLC_PWM_CPU_CTL2) & BLM_PWM_ENABLE,
9463              "CPU PWM1 enabled\n");
9464         if (IS_HASWELL(dev))
9465                 I915_STATE_WARN(I915_READ(HSW_BLC_PWM2_CTL) & BLM_PWM_ENABLE,
9466                      "CPU PWM2 enabled\n");
9467         I915_STATE_WARN(I915_READ(BLC_PWM_PCH_CTL1) & BLM_PCH_PWM_ENABLE,
9468              "PCH PWM1 enabled\n");
9469         I915_STATE_WARN(I915_READ(UTIL_PIN_CTL) & UTIL_PIN_ENABLE,
9470              "Utility pin enabled\n");
9471         I915_STATE_WARN(I915_READ(PCH_GTC_CTL) & PCH_GTC_ENABLE, "PCH GTC enabled\n");
9472
9473         /*
9474          * In theory we can still leave IRQs enabled, as long as only the HPD
9475          * interrupts remain enabled. We used to check for that, but since it's
9476          * gen-specific and since we only disable LCPLL after we fully disable
9477          * the interrupts, the check below should be enough.
9478          */
9479         I915_STATE_WARN(intel_irqs_enabled(dev_priv), "IRQs enabled\n");
9480 }
9481
9482 static uint32_t hsw_read_dcomp(struct drm_i915_private *dev_priv)
9483 {
9484         struct drm_device *dev = dev_priv->dev;
9485
9486         if (IS_HASWELL(dev))
9487                 return I915_READ(D_COMP_HSW);
9488         else
9489                 return I915_READ(D_COMP_BDW);
9490 }
9491
9492 static void hsw_write_dcomp(struct drm_i915_private *dev_priv, uint32_t val)
9493 {
9494         struct drm_device *dev = dev_priv->dev;
9495
9496         if (IS_HASWELL(dev)) {
9497                 mutex_lock(&dev_priv->rps.hw_lock);
9498                 if (sandybridge_pcode_write(dev_priv, GEN6_PCODE_WRITE_D_COMP,
9499                                             val))
9500                         DRM_ERROR("Failed to write to D_COMP\n");
9501                 mutex_unlock(&dev_priv->rps.hw_lock);
9502         } else {
9503                 I915_WRITE(D_COMP_BDW, val);
9504                 POSTING_READ(D_COMP_BDW);
9505         }
9506 }
9507
9508 /*
9509  * This function implements pieces of two sequences from BSpec:
9510  * - Sequence for display software to disable LCPLL
9511  * - Sequence for display software to allow package C8+
9512  * The steps implemented here are just the steps that actually touch the LCPLL
9513  * register. Callers should take care of disabling all the display engine
9514  * functions, doing the mode unset, fixing interrupts, etc.
9515  */
9516 static void hsw_disable_lcpll(struct drm_i915_private *dev_priv,
9517                               bool switch_to_fclk, bool allow_power_down)
9518 {
9519         uint32_t val;
9520
9521         assert_can_disable_lcpll(dev_priv);
9522
9523         val = I915_READ(LCPLL_CTL);
9524
9525         if (switch_to_fclk) {
9526                 val |= LCPLL_CD_SOURCE_FCLK;
9527                 I915_WRITE(LCPLL_CTL, val);
9528
9529                 if (wait_for_atomic_us(I915_READ(LCPLL_CTL) &
9530                                        LCPLL_CD_SOURCE_FCLK_DONE, 1))
9531                         DRM_ERROR("Switching to FCLK failed\n");
9532
9533                 val = I915_READ(LCPLL_CTL);
9534         }
9535
9536         val |= LCPLL_PLL_DISABLE;
9537         I915_WRITE(LCPLL_CTL, val);
9538         POSTING_READ(LCPLL_CTL);
9539
9540         if (wait_for((I915_READ(LCPLL_CTL) & LCPLL_PLL_LOCK) == 0, 1))
9541                 DRM_ERROR("LCPLL still locked\n");
9542
9543         val = hsw_read_dcomp(dev_priv);
9544         val |= D_COMP_COMP_DISABLE;
9545         hsw_write_dcomp(dev_priv, val);
9546         ndelay(100);
9547
9548         if (wait_for((hsw_read_dcomp(dev_priv) & D_COMP_RCOMP_IN_PROGRESS) == 0,
9549                      1))
9550                 DRM_ERROR("D_COMP RCOMP still in progress\n");
9551
9552         if (allow_power_down) {
9553                 val = I915_READ(LCPLL_CTL);
9554                 val |= LCPLL_POWER_DOWN_ALLOW;
9555                 I915_WRITE(LCPLL_CTL, val);
9556                 POSTING_READ(LCPLL_CTL);
9557         }
9558 }
9559
9560 /*
9561  * Fully restores LCPLL, disallowing power down and switching back to LCPLL
9562  * source.
9563  */
9564 static void hsw_restore_lcpll(struct drm_i915_private *dev_priv)
9565 {
9566         uint32_t val;
9567
9568         val = I915_READ(LCPLL_CTL);
9569
9570         if ((val & (LCPLL_PLL_LOCK | LCPLL_PLL_DISABLE | LCPLL_CD_SOURCE_FCLK |
9571                     LCPLL_POWER_DOWN_ALLOW)) == LCPLL_PLL_LOCK)
9572                 return;
9573
9574         /*
9575          * Make sure we're not on PC8 state before disabling PC8, otherwise
9576          * we'll hang the machine. To prevent PC8 state, just enable force_wake.
9577          */
9578         intel_uncore_forcewake_get(dev_priv, FORCEWAKE_ALL);
9579
9580         if (val & LCPLL_POWER_DOWN_ALLOW) {
9581                 val &= ~LCPLL_POWER_DOWN_ALLOW;
9582                 I915_WRITE(LCPLL_CTL, val);
9583                 POSTING_READ(LCPLL_CTL);
9584         }
9585
9586         val = hsw_read_dcomp(dev_priv);
9587         val |= D_COMP_COMP_FORCE;
9588         val &= ~D_COMP_COMP_DISABLE;
9589         hsw_write_dcomp(dev_priv, val);
9590
9591         val = I915_READ(LCPLL_CTL);
9592         val &= ~LCPLL_PLL_DISABLE;
9593         I915_WRITE(LCPLL_CTL, val);
9594
9595         if (wait_for(I915_READ(LCPLL_CTL) & LCPLL_PLL_LOCK, 5))
9596                 DRM_ERROR("LCPLL not locked yet\n");
9597
9598         if (val & LCPLL_CD_SOURCE_FCLK) {
9599                 val = I915_READ(LCPLL_CTL);
9600                 val &= ~LCPLL_CD_SOURCE_FCLK;
9601                 I915_WRITE(LCPLL_CTL, val);
9602
9603                 if (wait_for_atomic_us((I915_READ(LCPLL_CTL) &
9604                                         LCPLL_CD_SOURCE_FCLK_DONE) == 0, 1))
9605                         DRM_ERROR("Switching back to LCPLL failed\n");
9606         }
9607
9608         intel_uncore_forcewake_put(dev_priv, FORCEWAKE_ALL);
9609         intel_update_cdclk(dev_priv->dev);
9610 }
9611
9612 /*
9613  * Package states C8 and deeper are really deep PC states that can only be
9614  * reached when all the devices on the system allow it, so even if the graphics
9615  * device allows PC8+, it doesn't mean the system will actually get to these
9616  * states. Our driver only allows PC8+ when going into runtime PM.
9617  *
9618  * The requirements for PC8+ are that all the outputs are disabled, the power
9619  * well is disabled and most interrupts are disabled, and these are also
9620  * requirements for runtime PM. When these conditions are met, we manually do
9621  * the other conditions: disable the interrupts, clocks and switch LCPLL refclk
9622  * to Fclk. If we're in PC8+ and we get an non-hotplug interrupt, we can hard
9623  * hang the machine.
9624  *
9625  * When we really reach PC8 or deeper states (not just when we allow it) we lose
9626  * the state of some registers, so when we come back from PC8+ we need to
9627  * restore this state. We don't get into PC8+ if we're not in RC6, so we don't
9628  * need to take care of the registers kept by RC6. Notice that this happens even
9629  * if we don't put the device in PCI D3 state (which is what currently happens
9630  * because of the runtime PM support).
9631  *
9632  * For more, read "Display Sequences for Package C8" on the hardware
9633  * documentation.
9634  */
9635 void hsw_enable_pc8(struct drm_i915_private *dev_priv)
9636 {
9637         struct drm_device *dev = dev_priv->dev;
9638         uint32_t val;
9639
9640         DRM_DEBUG_KMS("Enabling package C8+\n");
9641
9642         if (HAS_PCH_LPT_LP(dev)) {
9643                 val = I915_READ(SOUTH_DSPCLK_GATE_D);
9644                 val &= ~PCH_LP_PARTITION_LEVEL_DISABLE;
9645                 I915_WRITE(SOUTH_DSPCLK_GATE_D, val);
9646         }
9647
9648         lpt_disable_clkout_dp(dev);
9649         hsw_disable_lcpll(dev_priv, true, true);
9650 }
9651
9652 void hsw_disable_pc8(struct drm_i915_private *dev_priv)
9653 {
9654         struct drm_device *dev = dev_priv->dev;
9655         uint32_t val;
9656
9657         DRM_DEBUG_KMS("Disabling package C8+\n");
9658
9659         hsw_restore_lcpll(dev_priv);
9660         lpt_init_pch_refclk(dev);
9661
9662         if (HAS_PCH_LPT_LP(dev)) {
9663                 val = I915_READ(SOUTH_DSPCLK_GATE_D);
9664                 val |= PCH_LP_PARTITION_LEVEL_DISABLE;
9665                 I915_WRITE(SOUTH_DSPCLK_GATE_D, val);
9666         }
9667
9668         intel_prepare_ddi(dev);
9669 }
9670
9671 static void broxton_modeset_commit_cdclk(struct drm_atomic_state *old_state)
9672 {
9673         struct drm_device *dev = old_state->dev;
9674         unsigned int req_cdclk = to_intel_atomic_state(old_state)->cdclk;
9675
9676         broxton_set_cdclk(dev, req_cdclk);
9677 }
9678
9679 /* compute the max rate for new configuration */
9680 static int ilk_max_pixel_rate(struct drm_atomic_state *state)
9681 {
9682         struct intel_crtc *intel_crtc;
9683         struct intel_crtc_state *crtc_state;
9684         int max_pixel_rate = 0;
9685
9686         for_each_intel_crtc(state->dev, intel_crtc) {
9687                 int pixel_rate;
9688
9689                 crtc_state = intel_atomic_get_crtc_state(state, intel_crtc);
9690                 if (IS_ERR(crtc_state))
9691                         return PTR_ERR(crtc_state);
9692
9693                 if (!crtc_state->base.enable)
9694                         continue;
9695
9696                 pixel_rate = ilk_pipe_pixel_rate(crtc_state);
9697
9698                 /* pixel rate mustn't exceed 95% of cdclk with IPS on BDW */
9699                 if (IS_BROADWELL(state->dev) && crtc_state->ips_enabled)
9700                         pixel_rate = DIV_ROUND_UP(pixel_rate * 100, 95);
9701
9702                 max_pixel_rate = max(max_pixel_rate, pixel_rate);
9703         }
9704
9705         return max_pixel_rate;
9706 }
9707
9708 static void broadwell_set_cdclk(struct drm_device *dev, int cdclk)
9709 {
9710         struct drm_i915_private *dev_priv = dev->dev_private;
9711         uint32_t val, data;
9712         int ret;
9713
9714         if (WARN((I915_READ(LCPLL_CTL) &
9715                   (LCPLL_PLL_DISABLE | LCPLL_PLL_LOCK |
9716                    LCPLL_CD_CLOCK_DISABLE | LCPLL_ROOT_CD_CLOCK_DISABLE |
9717                    LCPLL_CD2X_CLOCK_DISABLE | LCPLL_POWER_DOWN_ALLOW |
9718                    LCPLL_CD_SOURCE_FCLK)) != LCPLL_PLL_LOCK,
9719                  "trying to change cdclk frequency with cdclk not enabled\n"))
9720                 return;
9721
9722         mutex_lock(&dev_priv->rps.hw_lock);
9723         ret = sandybridge_pcode_write(dev_priv,
9724                                       BDW_PCODE_DISPLAY_FREQ_CHANGE_REQ, 0x0);
9725         mutex_unlock(&dev_priv->rps.hw_lock);
9726         if (ret) {
9727                 DRM_ERROR("failed to inform pcode about cdclk change\n");
9728                 return;
9729         }
9730
9731         val = I915_READ(LCPLL_CTL);
9732         val |= LCPLL_CD_SOURCE_FCLK;
9733         I915_WRITE(LCPLL_CTL, val);
9734
9735         if (wait_for_atomic_us(I915_READ(LCPLL_CTL) &
9736                                LCPLL_CD_SOURCE_FCLK_DONE, 1))
9737                 DRM_ERROR("Switching to FCLK failed\n");
9738
9739         val = I915_READ(LCPLL_CTL);
9740         val &= ~LCPLL_CLK_FREQ_MASK;
9741
9742         switch (cdclk) {
9743         case 450000:
9744                 val |= LCPLL_CLK_FREQ_450;
9745                 data = 0;
9746                 break;
9747         case 540000:
9748                 val |= LCPLL_CLK_FREQ_54O_BDW;
9749                 data = 1;
9750                 break;
9751         case 337500:
9752                 val |= LCPLL_CLK_FREQ_337_5_BDW;
9753                 data = 2;
9754                 break;
9755         case 675000:
9756                 val |= LCPLL_CLK_FREQ_675_BDW;
9757                 data = 3;
9758                 break;
9759         default:
9760                 WARN(1, "invalid cdclk frequency\n");
9761                 return;
9762         }
9763
9764         I915_WRITE(LCPLL_CTL, val);
9765
9766         val = I915_READ(LCPLL_CTL);
9767         val &= ~LCPLL_CD_SOURCE_FCLK;
9768         I915_WRITE(LCPLL_CTL, val);
9769
9770         if (wait_for_atomic_us((I915_READ(LCPLL_CTL) &
9771                                 LCPLL_CD_SOURCE_FCLK_DONE) == 0, 1))
9772                 DRM_ERROR("Switching back to LCPLL failed\n");
9773
9774         mutex_lock(&dev_priv->rps.hw_lock);
9775         sandybridge_pcode_write(dev_priv, HSW_PCODE_DE_WRITE_FREQ_REQ, data);
9776         mutex_unlock(&dev_priv->rps.hw_lock);
9777
9778         intel_update_cdclk(dev);
9779
9780         WARN(cdclk != dev_priv->cdclk_freq,
9781              "cdclk requested %d kHz but got %d kHz\n",
9782              cdclk, dev_priv->cdclk_freq);
9783 }
9784
9785 static int broadwell_modeset_calc_cdclk(struct drm_atomic_state *state)
9786 {
9787         struct drm_i915_private *dev_priv = to_i915(state->dev);
9788         int max_pixclk = ilk_max_pixel_rate(state);
9789         int cdclk;
9790
9791         /*
9792          * FIXME should also account for plane ratio
9793          * once 64bpp pixel formats are supported.
9794          */
9795         if (max_pixclk > 540000)
9796                 cdclk = 675000;
9797         else if (max_pixclk > 450000)
9798                 cdclk = 540000;
9799         else if (max_pixclk > 337500)
9800                 cdclk = 450000;
9801         else
9802                 cdclk = 337500;
9803
9804         if (cdclk > dev_priv->max_cdclk_freq) {
9805                 DRM_DEBUG_KMS("requested cdclk (%d kHz) exceeds max (%d kHz)\n",
9806                               cdclk, dev_priv->max_cdclk_freq);
9807                 return -EINVAL;
9808         }
9809
9810         to_intel_atomic_state(state)->cdclk = cdclk;
9811
9812         return 0;
9813 }
9814
9815 static void broadwell_modeset_commit_cdclk(struct drm_atomic_state *old_state)
9816 {
9817         struct drm_device *dev = old_state->dev;
9818         unsigned int req_cdclk = to_intel_atomic_state(old_state)->cdclk;
9819
9820         broadwell_set_cdclk(dev, req_cdclk);
9821 }
9822
9823 static int haswell_crtc_compute_clock(struct intel_crtc *crtc,
9824                                       struct intel_crtc_state *crtc_state)
9825 {
9826         if (!intel_ddi_pll_select(crtc, crtc_state))
9827                 return -EINVAL;
9828
9829         crtc->lowfreq_avail = false;
9830
9831         return 0;
9832 }
9833
9834 static void bxt_get_ddi_pll(struct drm_i915_private *dev_priv,
9835                                 enum port port,
9836                                 struct intel_crtc_state *pipe_config)
9837 {
9838         switch (port) {
9839         case PORT_A:
9840                 pipe_config->ddi_pll_sel = SKL_DPLL0;
9841                 pipe_config->shared_dpll = DPLL_ID_SKL_DPLL1;
9842                 break;
9843         case PORT_B:
9844                 pipe_config->ddi_pll_sel = SKL_DPLL1;
9845                 pipe_config->shared_dpll = DPLL_ID_SKL_DPLL2;
9846                 break;
9847         case PORT_C:
9848                 pipe_config->ddi_pll_sel = SKL_DPLL2;
9849                 pipe_config->shared_dpll = DPLL_ID_SKL_DPLL3;
9850                 break;
9851         default:
9852                 DRM_ERROR("Incorrect port type\n");
9853         }
9854 }
9855
9856 static void skylake_get_ddi_pll(struct drm_i915_private *dev_priv,
9857                                 enum port port,
9858                                 struct intel_crtc_state *pipe_config)
9859 {
9860         u32 temp, dpll_ctl1;
9861
9862         temp = I915_READ(DPLL_CTRL2) & DPLL_CTRL2_DDI_CLK_SEL_MASK(port);
9863         pipe_config->ddi_pll_sel = temp >> (port * 3 + 1);
9864
9865         switch (pipe_config->ddi_pll_sel) {
9866         case SKL_DPLL0:
9867                 /*
9868                  * On SKL the eDP DPLL (DPLL0 as we don't use SSC) is not part
9869                  * of the shared DPLL framework and thus needs to be read out
9870                  * separately
9871                  */
9872                 dpll_ctl1 = I915_READ(DPLL_CTRL1);
9873                 pipe_config->dpll_hw_state.ctrl1 = dpll_ctl1 & 0x3f;
9874                 break;
9875         case SKL_DPLL1:
9876                 pipe_config->shared_dpll = DPLL_ID_SKL_DPLL1;
9877                 break;
9878         case SKL_DPLL2:
9879                 pipe_config->shared_dpll = DPLL_ID_SKL_DPLL2;
9880                 break;
9881         case SKL_DPLL3:
9882                 pipe_config->shared_dpll = DPLL_ID_SKL_DPLL3;
9883                 break;
9884         }
9885 }
9886
9887 static void haswell_get_ddi_pll(struct drm_i915_private *dev_priv,
9888                                 enum port port,
9889                                 struct intel_crtc_state *pipe_config)
9890 {
9891         pipe_config->ddi_pll_sel = I915_READ(PORT_CLK_SEL(port));
9892
9893         switch (pipe_config->ddi_pll_sel) {
9894         case PORT_CLK_SEL_WRPLL1:
9895                 pipe_config->shared_dpll = DPLL_ID_WRPLL1;
9896                 break;
9897         case PORT_CLK_SEL_WRPLL2:
9898                 pipe_config->shared_dpll = DPLL_ID_WRPLL2;
9899                 break;
9900         case PORT_CLK_SEL_SPLL:
9901                 pipe_config->shared_dpll = DPLL_ID_SPLL;
9902                 break;
9903         }
9904 }
9905
9906 static void haswell_get_ddi_port_state(struct intel_crtc *crtc,
9907                                        struct intel_crtc_state *pipe_config)
9908 {
9909         struct drm_device *dev = crtc->base.dev;
9910         struct drm_i915_private *dev_priv = dev->dev_private;
9911         struct intel_shared_dpll *pll;
9912         enum port port;
9913         uint32_t tmp;
9914
9915         tmp = I915_READ(TRANS_DDI_FUNC_CTL(pipe_config->cpu_transcoder));
9916
9917         port = (tmp & TRANS_DDI_PORT_MASK) >> TRANS_DDI_PORT_SHIFT;
9918
9919         if (IS_SKYLAKE(dev) || IS_KABYLAKE(dev))
9920                 skylake_get_ddi_pll(dev_priv, port, pipe_config);
9921         else if (IS_BROXTON(dev))
9922                 bxt_get_ddi_pll(dev_priv, port, pipe_config);
9923         else
9924                 haswell_get_ddi_pll(dev_priv, port, pipe_config);
9925
9926         if (pipe_config->shared_dpll >= 0) {
9927                 pll = &dev_priv->shared_dplls[pipe_config->shared_dpll];
9928
9929                 WARN_ON(!pll->get_hw_state(dev_priv, pll,
9930                                            &pipe_config->dpll_hw_state));
9931         }
9932
9933         /*
9934          * Haswell has only FDI/PCH transcoder A. It is which is connected to
9935          * DDI E. So just check whether this pipe is wired to DDI E and whether
9936          * the PCH transcoder is on.
9937          */
9938         if (INTEL_INFO(dev)->gen < 9 &&
9939             (port == PORT_E) && I915_READ(LPT_TRANSCONF) & TRANS_ENABLE) {
9940                 pipe_config->has_pch_encoder = true;
9941
9942                 tmp = I915_READ(FDI_RX_CTL(PIPE_A));
9943                 pipe_config->fdi_lanes = ((FDI_DP_PORT_WIDTH_MASK & tmp) >>
9944                                           FDI_DP_PORT_WIDTH_SHIFT) + 1;
9945
9946                 ironlake_get_fdi_m_n_config(crtc, pipe_config);
9947         }
9948 }
9949
9950 static bool haswell_get_pipe_config(struct intel_crtc *crtc,
9951                                     struct intel_crtc_state *pipe_config)
9952 {
9953         struct drm_device *dev = crtc->base.dev;
9954         struct drm_i915_private *dev_priv = dev->dev_private;
9955         enum intel_display_power_domain pfit_domain;
9956         uint32_t tmp;
9957
9958         if (!intel_display_power_is_enabled(dev_priv,
9959                                          POWER_DOMAIN_PIPE(crtc->pipe)))
9960                 return false;
9961
9962         pipe_config->cpu_transcoder = (enum transcoder) crtc->pipe;
9963         pipe_config->shared_dpll = DPLL_ID_PRIVATE;
9964
9965         tmp = I915_READ(TRANS_DDI_FUNC_CTL(TRANSCODER_EDP));
9966         if (tmp & TRANS_DDI_FUNC_ENABLE) {
9967                 enum pipe trans_edp_pipe;
9968                 switch (tmp & TRANS_DDI_EDP_INPUT_MASK) {
9969                 default:
9970                         WARN(1, "unknown pipe linked to edp transcoder\n");
9971                 case TRANS_DDI_EDP_INPUT_A_ONOFF:
9972                 case TRANS_DDI_EDP_INPUT_A_ON:
9973                         trans_edp_pipe = PIPE_A;
9974                         break;
9975                 case TRANS_DDI_EDP_INPUT_B_ONOFF:
9976                         trans_edp_pipe = PIPE_B;
9977                         break;
9978                 case TRANS_DDI_EDP_INPUT_C_ONOFF:
9979                         trans_edp_pipe = PIPE_C;
9980                         break;
9981                 }
9982
9983                 if (trans_edp_pipe == crtc->pipe)
9984                         pipe_config->cpu_transcoder = TRANSCODER_EDP;
9985         }
9986
9987         if (!intel_display_power_is_enabled(dev_priv,
9988                         POWER_DOMAIN_TRANSCODER(pipe_config->cpu_transcoder)))
9989                 return false;
9990
9991         tmp = I915_READ(PIPECONF(pipe_config->cpu_transcoder));
9992         if (!(tmp & PIPECONF_ENABLE))
9993                 return false;
9994
9995         haswell_get_ddi_port_state(crtc, pipe_config);
9996
9997         intel_get_pipe_timings(crtc, pipe_config);
9998
9999         if (INTEL_INFO(dev)->gen >= 9) {
10000                 skl_init_scalers(dev, crtc, pipe_config);
10001         }
10002
10003         pfit_domain = POWER_DOMAIN_PIPE_PANEL_FITTER(crtc->pipe);
10004
10005         if (INTEL_INFO(dev)->gen >= 9) {
10006                 pipe_config->scaler_state.scaler_id = -1;
10007                 pipe_config->scaler_state.scaler_users &= ~(1 << SKL_CRTC_INDEX);
10008         }
10009
10010         if (intel_display_power_is_enabled(dev_priv, pfit_domain)) {
10011                 if (INTEL_INFO(dev)->gen >= 9)
10012                         skylake_get_pfit_config(crtc, pipe_config);
10013                 else
10014                         ironlake_get_pfit_config(crtc, pipe_config);
10015         }
10016
10017         if (IS_HASWELL(dev))
10018                 pipe_config->ips_enabled = hsw_crtc_supports_ips(crtc) &&
10019                         (I915_READ(IPS_CTL) & IPS_ENABLE);
10020
10021         if (pipe_config->cpu_transcoder != TRANSCODER_EDP) {
10022                 pipe_config->pixel_multiplier =
10023                         I915_READ(PIPE_MULT(pipe_config->cpu_transcoder)) + 1;
10024         } else {
10025                 pipe_config->pixel_multiplier = 1;
10026         }
10027
10028         return true;
10029 }
10030
10031 static void i845_update_cursor(struct drm_crtc *crtc, u32 base, bool on)
10032 {
10033         struct drm_device *dev = crtc->dev;
10034         struct drm_i915_private *dev_priv = dev->dev_private;
10035         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
10036         uint32_t cntl = 0, size = 0;
10037
10038         if (on) {
10039                 unsigned int width = intel_crtc->base.cursor->state->crtc_w;
10040                 unsigned int height = intel_crtc->base.cursor->state->crtc_h;
10041                 unsigned int stride = roundup_pow_of_two(width) * 4;
10042
10043                 switch (stride) {
10044                 default:
10045                         WARN_ONCE(1, "Invalid cursor width/stride, width=%u, stride=%u\n",
10046                                   width, stride);
10047                         stride = 256;
10048                         /* fallthrough */
10049                 case 256:
10050                 case 512:
10051                 case 1024:
10052                 case 2048:
10053                         break;
10054                 }
10055
10056                 cntl |= CURSOR_ENABLE |
10057                         CURSOR_GAMMA_ENABLE |
10058                         CURSOR_FORMAT_ARGB |
10059                         CURSOR_STRIDE(stride);
10060
10061                 size = (height << 12) | width;
10062         }
10063
10064         if (intel_crtc->cursor_cntl != 0 &&
10065             (intel_crtc->cursor_base != base ||
10066              intel_crtc->cursor_size != size ||
10067              intel_crtc->cursor_cntl != cntl)) {
10068                 /* On these chipsets we can only modify the base/size/stride
10069                  * whilst the cursor is disabled.
10070                  */
10071                 I915_WRITE(CURCNTR(PIPE_A), 0);
10072                 POSTING_READ(CURCNTR(PIPE_A));
10073                 intel_crtc->cursor_cntl = 0;
10074         }
10075
10076         if (intel_crtc->cursor_base != base) {
10077                 I915_WRITE(CURBASE(PIPE_A), base);
10078                 intel_crtc->cursor_base = base;
10079         }
10080
10081         if (intel_crtc->cursor_size != size) {
10082                 I915_WRITE(CURSIZE, size);
10083                 intel_crtc->cursor_size = size;
10084         }
10085
10086         if (intel_crtc->cursor_cntl != cntl) {
10087                 I915_WRITE(CURCNTR(PIPE_A), cntl);
10088                 POSTING_READ(CURCNTR(PIPE_A));
10089                 intel_crtc->cursor_cntl = cntl;
10090         }
10091 }
10092
10093 static void i9xx_update_cursor(struct drm_crtc *crtc, u32 base, bool on)
10094 {
10095         struct drm_device *dev = crtc->dev;
10096         struct drm_i915_private *dev_priv = dev->dev_private;
10097         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
10098         int pipe = intel_crtc->pipe;
10099         uint32_t cntl = 0;
10100
10101         if (on) {
10102                 cntl = MCURSOR_GAMMA_ENABLE;
10103                 switch (intel_crtc->base.cursor->state->crtc_w) {
10104                         case 64:
10105                                 cntl |= CURSOR_MODE_64_ARGB_AX;
10106                                 break;
10107                         case 128:
10108                                 cntl |= CURSOR_MODE_128_ARGB_AX;
10109                                 break;
10110                         case 256:
10111                                 cntl |= CURSOR_MODE_256_ARGB_AX;
10112                                 break;
10113                         default:
10114                                 MISSING_CASE(intel_crtc->base.cursor->state->crtc_w);
10115                                 return;
10116                 }
10117                 cntl |= pipe << 28; /* Connect to correct pipe */
10118
10119                 if (HAS_DDI(dev))
10120                         cntl |= CURSOR_PIPE_CSC_ENABLE;
10121         }
10122
10123         if (crtc->cursor->state->rotation == BIT(DRM_ROTATE_180))
10124                 cntl |= CURSOR_ROTATE_180;
10125
10126         if (intel_crtc->cursor_cntl != cntl) {
10127                 I915_WRITE(CURCNTR(pipe), cntl);
10128                 POSTING_READ(CURCNTR(pipe));
10129                 intel_crtc->cursor_cntl = cntl;
10130         }
10131
10132         /* and commit changes on next vblank */
10133         I915_WRITE(CURBASE(pipe), base);
10134         POSTING_READ(CURBASE(pipe));
10135
10136         intel_crtc->cursor_base = base;
10137 }
10138
10139 /* If no-part of the cursor is visible on the framebuffer, then the GPU may hang... */
10140 static void intel_crtc_update_cursor(struct drm_crtc *crtc,
10141                                      bool on)
10142 {
10143         struct drm_device *dev = crtc->dev;
10144         struct drm_i915_private *dev_priv = dev->dev_private;
10145         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
10146         int pipe = intel_crtc->pipe;
10147         struct drm_plane_state *cursor_state = crtc->cursor->state;
10148         int x = cursor_state->crtc_x;
10149         int y = cursor_state->crtc_y;
10150         u32 base = 0, pos = 0;
10151
10152         base = intel_crtc->cursor_addr;
10153
10154         if (x >= intel_crtc->config->pipe_src_w)
10155                 on = false;
10156
10157         if (y >= intel_crtc->config->pipe_src_h)
10158                 on = false;
10159
10160         if (x < 0) {
10161                 if (x + cursor_state->crtc_w <= 0)
10162                         on = false;
10163
10164                 pos |= CURSOR_POS_SIGN << CURSOR_X_SHIFT;
10165                 x = -x;
10166         }
10167         pos |= x << CURSOR_X_SHIFT;
10168
10169         if (y < 0) {
10170                 if (y + cursor_state->crtc_h <= 0)
10171                         on = false;
10172
10173                 pos |= CURSOR_POS_SIGN << CURSOR_Y_SHIFT;
10174                 y = -y;
10175         }
10176         pos |= y << CURSOR_Y_SHIFT;
10177
10178         I915_WRITE(CURPOS(pipe), pos);
10179
10180         /* ILK+ do this automagically */
10181         if (HAS_GMCH_DISPLAY(dev) &&
10182             crtc->cursor->state->rotation == BIT(DRM_ROTATE_180)) {
10183                 base += (cursor_state->crtc_h *
10184                          cursor_state->crtc_w - 1) * 4;
10185         }
10186
10187         if (IS_845G(dev) || IS_I865G(dev))
10188                 i845_update_cursor(crtc, base, on);
10189         else
10190                 i9xx_update_cursor(crtc, base, on);
10191 }
10192
10193 static bool cursor_size_ok(struct drm_device *dev,
10194                            uint32_t width, uint32_t height)
10195 {
10196         if (width == 0 || height == 0)
10197                 return false;
10198
10199         /*
10200          * 845g/865g are special in that they are only limited by
10201          * the width of their cursors, the height is arbitrary up to
10202          * the precision of the register. Everything else requires
10203          * square cursors, limited to a few power-of-two sizes.
10204          */
10205         if (IS_845G(dev) || IS_I865G(dev)) {
10206                 if ((width & 63) != 0)
10207                         return false;
10208
10209                 if (width > (IS_845G(dev) ? 64 : 512))
10210                         return false;
10211
10212                 if (height > 1023)
10213                         return false;
10214         } else {
10215                 switch (width | height) {
10216                 case 256:
10217                 case 128:
10218                         if (IS_GEN2(dev))
10219                                 return false;
10220                 case 64:
10221                         break;
10222                 default:
10223                         return false;
10224                 }
10225         }
10226
10227         return true;
10228 }
10229
10230 static void intel_crtc_gamma_set(struct drm_crtc *crtc, u16 *red, u16 *green,
10231                                  u16 *blue, uint32_t start, uint32_t size)
10232 {
10233         int end = (start + size > 256) ? 256 : start + size, i;
10234         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
10235
10236         for (i = start; i < end; i++) {
10237                 intel_crtc->lut_r[i] = red[i] >> 8;
10238                 intel_crtc->lut_g[i] = green[i] >> 8;
10239                 intel_crtc->lut_b[i] = blue[i] >> 8;
10240         }
10241
10242         intel_crtc_load_lut(crtc);
10243 }
10244
10245 /* VESA 640x480x72Hz mode to set on the pipe */
10246 static struct drm_display_mode load_detect_mode = {
10247         DRM_MODE("640x480", DRM_MODE_TYPE_DEFAULT, 31500, 640, 664,
10248                  704, 832, 0, 480, 489, 491, 520, 0, DRM_MODE_FLAG_NHSYNC | DRM_MODE_FLAG_NVSYNC),
10249 };
10250
10251 struct drm_framebuffer *
10252 __intel_framebuffer_create(struct drm_device *dev,
10253                            struct drm_mode_fb_cmd2 *mode_cmd,
10254                            struct drm_i915_gem_object *obj)
10255 {
10256         struct intel_framebuffer *intel_fb;
10257         int ret;
10258
10259         intel_fb = kzalloc(sizeof(*intel_fb), GFP_KERNEL);
10260         if (!intel_fb)
10261                 return ERR_PTR(-ENOMEM);
10262
10263         ret = intel_framebuffer_init(dev, intel_fb, mode_cmd, obj);
10264         if (ret)
10265                 goto err;
10266
10267         return &intel_fb->base;
10268
10269 err:
10270         kfree(intel_fb);
10271         return ERR_PTR(ret);
10272 }
10273
10274 static struct drm_framebuffer *
10275 intel_framebuffer_create(struct drm_device *dev,
10276                          struct drm_mode_fb_cmd2 *mode_cmd,
10277                          struct drm_i915_gem_object *obj)
10278 {
10279         struct drm_framebuffer *fb;
10280         int ret;
10281
10282         ret = i915_mutex_lock_interruptible(dev);
10283         if (ret)
10284                 return ERR_PTR(ret);
10285         fb = __intel_framebuffer_create(dev, mode_cmd, obj);
10286         mutex_unlock(&dev->struct_mutex);
10287
10288         return fb;
10289 }
10290
10291 static u32
10292 intel_framebuffer_pitch_for_width(int width, int bpp)
10293 {
10294         u32 pitch = DIV_ROUND_UP(width * bpp, 8);
10295         return ALIGN(pitch, 64);
10296 }
10297
10298 static u32
10299 intel_framebuffer_size_for_mode(struct drm_display_mode *mode, int bpp)
10300 {
10301         u32 pitch = intel_framebuffer_pitch_for_width(mode->hdisplay, bpp);
10302         return PAGE_ALIGN(pitch * mode->vdisplay);
10303 }
10304
10305 static struct drm_framebuffer *
10306 intel_framebuffer_create_for_mode(struct drm_device *dev,
10307                                   struct drm_display_mode *mode,
10308                                   int depth, int bpp)
10309 {
10310         struct drm_framebuffer *fb;
10311         struct drm_i915_gem_object *obj;
10312         struct drm_mode_fb_cmd2 mode_cmd = { 0 };
10313
10314         obj = i915_gem_alloc_object(dev,
10315                                     intel_framebuffer_size_for_mode(mode, bpp));
10316         if (obj == NULL)
10317                 return ERR_PTR(-ENOMEM);
10318
10319         mode_cmd.width = mode->hdisplay;
10320         mode_cmd.height = mode->vdisplay;
10321         mode_cmd.pitches[0] = intel_framebuffer_pitch_for_width(mode_cmd.width,
10322                                                                 bpp);
10323         mode_cmd.pixel_format = drm_mode_legacy_fb_format(bpp, depth);
10324
10325         fb = intel_framebuffer_create(dev, &mode_cmd, obj);
10326         if (IS_ERR(fb))
10327                 drm_gem_object_unreference_unlocked(&obj->base);
10328
10329         return fb;
10330 }
10331
10332 static struct drm_framebuffer *
10333 mode_fits_in_fbdev(struct drm_device *dev,
10334                    struct drm_display_mode *mode)
10335 {
10336 #ifdef CONFIG_DRM_FBDEV_EMULATION
10337         struct drm_i915_private *dev_priv = dev->dev_private;
10338         struct drm_i915_gem_object *obj;
10339         struct drm_framebuffer *fb;
10340
10341         if (!dev_priv->fbdev)
10342                 return NULL;
10343
10344         if (!dev_priv->fbdev->fb)
10345                 return NULL;
10346
10347         obj = dev_priv->fbdev->fb->obj;
10348         BUG_ON(!obj);
10349
10350         fb = &dev_priv->fbdev->fb->base;
10351         if (fb->pitches[0] < intel_framebuffer_pitch_for_width(mode->hdisplay,
10352                                                                fb->bits_per_pixel))
10353                 return NULL;
10354
10355         if (obj->base.size < mode->vdisplay * fb->pitches[0])
10356                 return NULL;
10357
10358         return fb;
10359 #else
10360         return NULL;
10361 #endif
10362 }
10363
10364 static int intel_modeset_setup_plane_state(struct drm_atomic_state *state,
10365                                            struct drm_crtc *crtc,
10366                                            struct drm_display_mode *mode,
10367                                            struct drm_framebuffer *fb,
10368                                            int x, int y)
10369 {
10370         struct drm_plane_state *plane_state;
10371         int hdisplay, vdisplay;
10372         int ret;
10373
10374         plane_state = drm_atomic_get_plane_state(state, crtc->primary);
10375         if (IS_ERR(plane_state))
10376                 return PTR_ERR(plane_state);
10377
10378         if (mode)
10379                 drm_crtc_get_hv_timing(mode, &hdisplay, &vdisplay);
10380         else
10381                 hdisplay = vdisplay = 0;
10382
10383         ret = drm_atomic_set_crtc_for_plane(plane_state, fb ? crtc : NULL);
10384         if (ret)
10385                 return ret;
10386         drm_atomic_set_fb_for_plane(plane_state, fb);
10387         plane_state->crtc_x = 0;
10388         plane_state->crtc_y = 0;
10389         plane_state->crtc_w = hdisplay;
10390         plane_state->crtc_h = vdisplay;
10391         plane_state->src_x = x << 16;
10392         plane_state->src_y = y << 16;
10393         plane_state->src_w = hdisplay << 16;
10394         plane_state->src_h = vdisplay << 16;
10395
10396         return 0;
10397 }
10398
10399 bool intel_get_load_detect_pipe(struct drm_connector *connector,
10400                                 struct drm_display_mode *mode,
10401                                 struct intel_load_detect_pipe *old,
10402                                 struct drm_modeset_acquire_ctx *ctx)
10403 {
10404         struct intel_crtc *intel_crtc;
10405         struct intel_encoder *intel_encoder =
10406                 intel_attached_encoder(connector);
10407         struct drm_crtc *possible_crtc;
10408         struct drm_encoder *encoder = &intel_encoder->base;
10409         struct drm_crtc *crtc = NULL;
10410         struct drm_device *dev = encoder->dev;
10411         struct drm_framebuffer *fb;
10412         struct drm_mode_config *config = &dev->mode_config;
10413         struct drm_atomic_state *state = NULL;
10414         struct drm_connector_state *connector_state;
10415         struct intel_crtc_state *crtc_state;
10416         int ret, i = -1;
10417
10418         DRM_DEBUG_KMS("[CONNECTOR:%d:%s], [ENCODER:%d:%s]\n",
10419                       connector->base.id, connector->name,
10420                       encoder->base.id, encoder->name);
10421
10422 retry:
10423         ret = drm_modeset_lock(&config->connection_mutex, ctx);
10424         if (ret)
10425                 goto fail;
10426
10427         /*
10428          * Algorithm gets a little messy:
10429          *
10430          *   - if the connector already has an assigned crtc, use it (but make
10431          *     sure it's on first)
10432          *
10433          *   - try to find the first unused crtc that can drive this connector,
10434          *     and use that if we find one
10435          */
10436
10437         /* See if we already have a CRTC for this connector */
10438         if (encoder->crtc) {
10439                 crtc = encoder->crtc;
10440
10441                 ret = drm_modeset_lock(&crtc->mutex, ctx);
10442                 if (ret)
10443                         goto fail;
10444                 ret = drm_modeset_lock(&crtc->primary->mutex, ctx);
10445                 if (ret)
10446                         goto fail;
10447
10448                 old->dpms_mode = connector->dpms;
10449                 old->load_detect_temp = false;
10450
10451                 /* Make sure the crtc and connector are running */
10452                 if (connector->dpms != DRM_MODE_DPMS_ON)
10453                         connector->funcs->dpms(connector, DRM_MODE_DPMS_ON);
10454
10455                 return true;
10456         }
10457
10458         /* Find an unused one (if possible) */
10459         for_each_crtc(dev, possible_crtc) {
10460                 i++;
10461                 if (!(encoder->possible_crtcs & (1 << i)))
10462                         continue;
10463                 if (possible_crtc->state->enable)
10464                         continue;
10465
10466                 crtc = possible_crtc;
10467                 break;
10468         }
10469
10470         /*
10471          * If we didn't find an unused CRTC, don't use any.
10472          */
10473         if (!crtc) {
10474                 DRM_DEBUG_KMS("no pipe available for load-detect\n");
10475                 goto fail;
10476         }
10477
10478         ret = drm_modeset_lock(&crtc->mutex, ctx);
10479         if (ret)
10480                 goto fail;
10481         ret = drm_modeset_lock(&crtc->primary->mutex, ctx);
10482         if (ret)
10483                 goto fail;
10484
10485         intel_crtc = to_intel_crtc(crtc);
10486         old->dpms_mode = connector->dpms;
10487         old->load_detect_temp = true;
10488         old->release_fb = NULL;
10489
10490         state = drm_atomic_state_alloc(dev);
10491         if (!state)
10492                 return false;
10493
10494         state->acquire_ctx = ctx;
10495
10496         connector_state = drm_atomic_get_connector_state(state, connector);
10497         if (IS_ERR(connector_state)) {
10498                 ret = PTR_ERR(connector_state);
10499                 goto fail;
10500         }
10501
10502         connector_state->crtc = crtc;
10503         connector_state->best_encoder = &intel_encoder->base;
10504
10505         crtc_state = intel_atomic_get_crtc_state(state, intel_crtc);
10506         if (IS_ERR(crtc_state)) {
10507                 ret = PTR_ERR(crtc_state);
10508                 goto fail;
10509         }
10510
10511         crtc_state->base.active = crtc_state->base.enable = true;
10512
10513         if (!mode)
10514                 mode = &load_detect_mode;
10515
10516         /* We need a framebuffer large enough to accommodate all accesses
10517          * that the plane may generate whilst we perform load detection.
10518          * We can not rely on the fbcon either being present (we get called
10519          * during its initialisation to detect all boot displays, or it may
10520          * not even exist) or that it is large enough to satisfy the
10521          * requested mode.
10522          */
10523         fb = mode_fits_in_fbdev(dev, mode);
10524         if (fb == NULL) {
10525                 DRM_DEBUG_KMS("creating tmp fb for load-detection\n");
10526                 fb = intel_framebuffer_create_for_mode(dev, mode, 24, 32);
10527                 old->release_fb = fb;
10528         } else
10529                 DRM_DEBUG_KMS("reusing fbdev for load-detection framebuffer\n");
10530         if (IS_ERR(fb)) {
10531                 DRM_DEBUG_KMS("failed to allocate framebuffer for load-detection\n");
10532                 goto fail;
10533         }
10534
10535         ret = intel_modeset_setup_plane_state(state, crtc, mode, fb, 0, 0);
10536         if (ret)
10537                 goto fail;
10538
10539         drm_mode_copy(&crtc_state->base.mode, mode);
10540
10541         if (drm_atomic_commit(state)) {
10542                 DRM_DEBUG_KMS("failed to set mode on load-detect pipe\n");
10543                 if (old->release_fb)
10544                         old->release_fb->funcs->destroy(old->release_fb);
10545                 goto fail;
10546         }
10547         crtc->primary->crtc = crtc;
10548
10549         /* let the connector get through one full cycle before testing */
10550         intel_wait_for_vblank(dev, intel_crtc->pipe);
10551         return true;
10552
10553 fail:
10554         drm_atomic_state_free(state);
10555         state = NULL;
10556
10557         if (ret == -EDEADLK) {
10558                 drm_modeset_backoff(ctx);
10559                 goto retry;
10560         }
10561
10562         return false;
10563 }
10564
10565 void intel_release_load_detect_pipe(struct drm_connector *connector,
10566                                     struct intel_load_detect_pipe *old,
10567                                     struct drm_modeset_acquire_ctx *ctx)
10568 {
10569         struct drm_device *dev = connector->dev;
10570         struct intel_encoder *intel_encoder =
10571                 intel_attached_encoder(connector);
10572         struct drm_encoder *encoder = &intel_encoder->base;
10573         struct drm_crtc *crtc = encoder->crtc;
10574         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
10575         struct drm_atomic_state *state;
10576         struct drm_connector_state *connector_state;
10577         struct intel_crtc_state *crtc_state;
10578         int ret;
10579
10580         DRM_DEBUG_KMS("[CONNECTOR:%d:%s], [ENCODER:%d:%s]\n",
10581                       connector->base.id, connector->name,
10582                       encoder->base.id, encoder->name);
10583
10584         if (old->load_detect_temp) {
10585                 state = drm_atomic_state_alloc(dev);
10586                 if (!state)
10587                         goto fail;
10588
10589                 state->acquire_ctx = ctx;
10590
10591                 connector_state = drm_atomic_get_connector_state(state, connector);
10592                 if (IS_ERR(connector_state))
10593                         goto fail;
10594
10595                 crtc_state = intel_atomic_get_crtc_state(state, intel_crtc);
10596                 if (IS_ERR(crtc_state))
10597                         goto fail;
10598
10599                 connector_state->best_encoder = NULL;
10600                 connector_state->crtc = NULL;
10601
10602                 crtc_state->base.enable = crtc_state->base.active = false;
10603
10604                 ret = intel_modeset_setup_plane_state(state, crtc, NULL, NULL,
10605                                                       0, 0);
10606                 if (ret)
10607                         goto fail;
10608
10609                 ret = drm_atomic_commit(state);
10610                 if (ret)
10611                         goto fail;
10612
10613                 if (old->release_fb) {
10614                         drm_framebuffer_unregister_private(old->release_fb);
10615                         drm_framebuffer_unreference(old->release_fb);
10616                 }
10617
10618                 return;
10619         }
10620
10621         /* Switch crtc and encoder back off if necessary */
10622         if (old->dpms_mode != DRM_MODE_DPMS_ON)
10623                 connector->funcs->dpms(connector, old->dpms_mode);
10624
10625         return;
10626 fail:
10627         DRM_DEBUG_KMS("Couldn't release load detect pipe.\n");
10628         drm_atomic_state_free(state);
10629 }
10630
10631 static int i9xx_pll_refclk(struct drm_device *dev,
10632                            const struct intel_crtc_state *pipe_config)
10633 {
10634         struct drm_i915_private *dev_priv = dev->dev_private;
10635         u32 dpll = pipe_config->dpll_hw_state.dpll;
10636
10637         if ((dpll & PLL_REF_INPUT_MASK) == PLLB_REF_INPUT_SPREADSPECTRUMIN)
10638                 return dev_priv->vbt.lvds_ssc_freq;
10639         else if (HAS_PCH_SPLIT(dev))
10640                 return 120000;
10641         else if (!IS_GEN2(dev))
10642                 return 96000;
10643         else
10644                 return 48000;
10645 }
10646
10647 /* Returns the clock of the currently programmed mode of the given pipe. */
10648 static void i9xx_crtc_clock_get(struct intel_crtc *crtc,
10649                                 struct intel_crtc_state *pipe_config)
10650 {
10651         struct drm_device *dev = crtc->base.dev;
10652         struct drm_i915_private *dev_priv = dev->dev_private;
10653         int pipe = pipe_config->cpu_transcoder;
10654         u32 dpll = pipe_config->dpll_hw_state.dpll;
10655         u32 fp;
10656         intel_clock_t clock;
10657         int port_clock;
10658         int refclk = i9xx_pll_refclk(dev, pipe_config);
10659
10660         if ((dpll & DISPLAY_RATE_SELECT_FPA1) == 0)
10661                 fp = pipe_config->dpll_hw_state.fp0;
10662         else
10663                 fp = pipe_config->dpll_hw_state.fp1;
10664
10665         clock.m1 = (fp & FP_M1_DIV_MASK) >> FP_M1_DIV_SHIFT;
10666         if (IS_PINEVIEW(dev)) {
10667                 clock.n = ffs((fp & FP_N_PINEVIEW_DIV_MASK) >> FP_N_DIV_SHIFT) - 1;
10668                 clock.m2 = (fp & FP_M2_PINEVIEW_DIV_MASK) >> FP_M2_DIV_SHIFT;
10669         } else {
10670                 clock.n = (fp & FP_N_DIV_MASK) >> FP_N_DIV_SHIFT;
10671                 clock.m2 = (fp & FP_M2_DIV_MASK) >> FP_M2_DIV_SHIFT;
10672         }
10673
10674         if (!IS_GEN2(dev)) {
10675                 if (IS_PINEVIEW(dev))
10676                         clock.p1 = ffs((dpll & DPLL_FPA01_P1_POST_DIV_MASK_PINEVIEW) >>
10677                                 DPLL_FPA01_P1_POST_DIV_SHIFT_PINEVIEW);
10678                 else
10679                         clock.p1 = ffs((dpll & DPLL_FPA01_P1_POST_DIV_MASK) >>
10680                                DPLL_FPA01_P1_POST_DIV_SHIFT);
10681
10682                 switch (dpll & DPLL_MODE_MASK) {
10683                 case DPLLB_MODE_DAC_SERIAL:
10684                         clock.p2 = dpll & DPLL_DAC_SERIAL_P2_CLOCK_DIV_5 ?
10685                                 5 : 10;
10686                         break;
10687                 case DPLLB_MODE_LVDS:
10688                         clock.p2 = dpll & DPLLB_LVDS_P2_CLOCK_DIV_7 ?
10689                                 7 : 14;
10690                         break;
10691                 default:
10692                         DRM_DEBUG_KMS("Unknown DPLL mode %08x in programmed "
10693                                   "mode\n", (int)(dpll & DPLL_MODE_MASK));
10694                         return;
10695                 }
10696
10697                 if (IS_PINEVIEW(dev))
10698                         port_clock = pnv_calc_dpll_params(refclk, &clock);
10699                 else
10700                         port_clock = i9xx_calc_dpll_params(refclk, &clock);
10701         } else {
10702                 u32 lvds = IS_I830(dev) ? 0 : I915_READ(LVDS);
10703                 bool is_lvds = (pipe == 1) && (lvds & LVDS_PORT_EN);
10704
10705                 if (is_lvds) {
10706                         clock.p1 = ffs((dpll & DPLL_FPA01_P1_POST_DIV_MASK_I830_LVDS) >>
10707                                        DPLL_FPA01_P1_POST_DIV_SHIFT);
10708
10709                         if (lvds & LVDS_CLKB_POWER_UP)
10710                                 clock.p2 = 7;
10711                         else
10712                                 clock.p2 = 14;
10713                 } else {
10714                         if (dpll & PLL_P1_DIVIDE_BY_TWO)
10715                                 clock.p1 = 2;
10716                         else {
10717                                 clock.p1 = ((dpll & DPLL_FPA01_P1_POST_DIV_MASK_I830) >>
10718                                             DPLL_FPA01_P1_POST_DIV_SHIFT) + 2;
10719                         }
10720                         if (dpll & PLL_P2_DIVIDE_BY_4)
10721                                 clock.p2 = 4;
10722                         else
10723                                 clock.p2 = 2;
10724                 }
10725
10726                 port_clock = i9xx_calc_dpll_params(refclk, &clock);
10727         }
10728
10729         /*
10730          * This value includes pixel_multiplier. We will use
10731          * port_clock to compute adjusted_mode.crtc_clock in the
10732          * encoder's get_config() function.
10733          */
10734         pipe_config->port_clock = port_clock;
10735 }
10736
10737 int intel_dotclock_calculate(int link_freq,
10738                              const struct intel_link_m_n *m_n)
10739 {
10740         /*
10741          * The calculation for the data clock is:
10742          * pixel_clock = ((m/n)*(link_clock * nr_lanes))/bpp
10743          * But we want to avoid losing precison if possible, so:
10744          * pixel_clock = ((m * link_clock * nr_lanes)/(n*bpp))
10745          *
10746          * and the link clock is simpler:
10747          * link_clock = (m * link_clock) / n
10748          */
10749
10750         if (!m_n->link_n)
10751                 return 0;
10752
10753         return div_u64((u64)m_n->link_m * link_freq, m_n->link_n);
10754 }
10755
10756 static void ironlake_pch_clock_get(struct intel_crtc *crtc,
10757                                    struct intel_crtc_state *pipe_config)
10758 {
10759         struct drm_device *dev = crtc->base.dev;
10760
10761         /* read out port_clock from the DPLL */
10762         i9xx_crtc_clock_get(crtc, pipe_config);
10763
10764         /*
10765          * This value does not include pixel_multiplier.
10766          * We will check that port_clock and adjusted_mode.crtc_clock
10767          * agree once we know their relationship in the encoder's
10768          * get_config() function.
10769          */
10770         pipe_config->base.adjusted_mode.crtc_clock =
10771                 intel_dotclock_calculate(intel_fdi_link_freq(dev) * 10000,
10772                                          &pipe_config->fdi_m_n);
10773 }
10774
10775 /** Returns the currently programmed mode of the given pipe. */
10776 struct drm_display_mode *intel_crtc_mode_get(struct drm_device *dev,
10777                                              struct drm_crtc *crtc)
10778 {
10779         struct drm_i915_private *dev_priv = dev->dev_private;
10780         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
10781         enum transcoder cpu_transcoder = intel_crtc->config->cpu_transcoder;
10782         struct drm_display_mode *mode;
10783         struct intel_crtc_state pipe_config;
10784         int htot = I915_READ(HTOTAL(cpu_transcoder));
10785         int hsync = I915_READ(HSYNC(cpu_transcoder));
10786         int vtot = I915_READ(VTOTAL(cpu_transcoder));
10787         int vsync = I915_READ(VSYNC(cpu_transcoder));
10788         enum pipe pipe = intel_crtc->pipe;
10789
10790         mode = kzalloc(sizeof(*mode), GFP_KERNEL);
10791         if (!mode)
10792                 return NULL;
10793
10794         /*
10795          * Construct a pipe_config sufficient for getting the clock info
10796          * back out of crtc_clock_get.
10797          *
10798          * Note, if LVDS ever uses a non-1 pixel multiplier, we'll need
10799          * to use a real value here instead.
10800          */
10801         pipe_config.cpu_transcoder = (enum transcoder) pipe;
10802         pipe_config.pixel_multiplier = 1;
10803         pipe_config.dpll_hw_state.dpll = I915_READ(DPLL(pipe));
10804         pipe_config.dpll_hw_state.fp0 = I915_READ(FP0(pipe));
10805         pipe_config.dpll_hw_state.fp1 = I915_READ(FP1(pipe));
10806         i9xx_crtc_clock_get(intel_crtc, &pipe_config);
10807
10808         mode->clock = pipe_config.port_clock / pipe_config.pixel_multiplier;
10809         mode->hdisplay = (htot & 0xffff) + 1;
10810         mode->htotal = ((htot & 0xffff0000) >> 16) + 1;
10811         mode->hsync_start = (hsync & 0xffff) + 1;
10812         mode->hsync_end = ((hsync & 0xffff0000) >> 16) + 1;
10813         mode->vdisplay = (vtot & 0xffff) + 1;
10814         mode->vtotal = ((vtot & 0xffff0000) >> 16) + 1;
10815         mode->vsync_start = (vsync & 0xffff) + 1;
10816         mode->vsync_end = ((vsync & 0xffff0000) >> 16) + 1;
10817
10818         drm_mode_set_name(mode);
10819
10820         return mode;
10821 }
10822
10823 void intel_mark_busy(struct drm_device *dev)
10824 {
10825         struct drm_i915_private *dev_priv = dev->dev_private;
10826
10827         if (dev_priv->mm.busy)
10828                 return;
10829
10830         intel_runtime_pm_get(dev_priv);
10831         i915_update_gfx_val(dev_priv);
10832         if (INTEL_INFO(dev)->gen >= 6)
10833                 gen6_rps_busy(dev_priv);
10834         dev_priv->mm.busy = true;
10835 }
10836
10837 void intel_mark_idle(struct drm_device *dev)
10838 {
10839         struct drm_i915_private *dev_priv = dev->dev_private;
10840
10841         if (!dev_priv->mm.busy)
10842                 return;
10843
10844         dev_priv->mm.busy = false;
10845
10846         if (INTEL_INFO(dev)->gen >= 6)
10847                 gen6_rps_idle(dev->dev_private);
10848
10849         intel_runtime_pm_put(dev_priv);
10850 }
10851
10852 static void intel_crtc_destroy(struct drm_crtc *crtc)
10853 {
10854         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
10855         struct drm_device *dev = crtc->dev;
10856         struct intel_unpin_work *work;
10857
10858         spin_lock_irq(&dev->event_lock);
10859         work = intel_crtc->unpin_work;
10860         intel_crtc->unpin_work = NULL;
10861         spin_unlock_irq(&dev->event_lock);
10862
10863         if (work) {
10864                 cancel_work_sync(&work->work);
10865                 kfree(work);
10866         }
10867
10868         drm_crtc_cleanup(crtc);
10869
10870         kfree(intel_crtc);
10871 }
10872
10873 static void intel_unpin_work_fn(struct work_struct *__work)
10874 {
10875         struct intel_unpin_work *work =
10876                 container_of(__work, struct intel_unpin_work, work);
10877         struct intel_crtc *crtc = to_intel_crtc(work->crtc);
10878         struct drm_device *dev = crtc->base.dev;
10879         struct drm_plane *primary = crtc->base.primary;
10880
10881         mutex_lock(&dev->struct_mutex);
10882         intel_unpin_fb_obj(work->old_fb, primary->state);
10883         drm_gem_object_unreference(&work->pending_flip_obj->base);
10884
10885         if (work->flip_queued_req)
10886                 i915_gem_request_assign(&work->flip_queued_req, NULL);
10887         mutex_unlock(&dev->struct_mutex);
10888
10889         intel_frontbuffer_flip_complete(dev, to_intel_plane(primary)->frontbuffer_bit);
10890         drm_framebuffer_unreference(work->old_fb);
10891
10892         BUG_ON(atomic_read(&crtc->unpin_work_count) == 0);
10893         atomic_dec(&crtc->unpin_work_count);
10894
10895         kfree(work);
10896 }
10897
10898 static void do_intel_finish_page_flip(struct drm_device *dev,
10899                                       struct drm_crtc *crtc)
10900 {
10901         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
10902         struct intel_unpin_work *work;
10903         unsigned long flags;
10904
10905         /* Ignore early vblank irqs */
10906         if (intel_crtc == NULL)
10907                 return;
10908
10909         /*
10910          * This is called both by irq handlers and the reset code (to complete
10911          * lost pageflips) so needs the full irqsave spinlocks.
10912          */
10913         spin_lock_irqsave(&dev->event_lock, flags);
10914         work = intel_crtc->unpin_work;
10915
10916         /* Ensure we don't miss a work->pending update ... */
10917         smp_rmb();
10918
10919         if (work == NULL || atomic_read(&work->pending) < INTEL_FLIP_COMPLETE) {
10920                 spin_unlock_irqrestore(&dev->event_lock, flags);
10921                 return;
10922         }
10923
10924         page_flip_completed(intel_crtc);
10925
10926         spin_unlock_irqrestore(&dev->event_lock, flags);
10927 }
10928
10929 void intel_finish_page_flip(struct drm_device *dev, int pipe)
10930 {
10931         struct drm_i915_private *dev_priv = dev->dev_private;
10932         struct drm_crtc *crtc = dev_priv->pipe_to_crtc_mapping[pipe];
10933
10934         do_intel_finish_page_flip(dev, crtc);
10935 }
10936
10937 void intel_finish_page_flip_plane(struct drm_device *dev, int plane)
10938 {
10939         struct drm_i915_private *dev_priv = dev->dev_private;
10940         struct drm_crtc *crtc = dev_priv->plane_to_crtc_mapping[plane];
10941
10942         do_intel_finish_page_flip(dev, crtc);
10943 }
10944
10945 /* Is 'a' after or equal to 'b'? */
10946 static bool g4x_flip_count_after_eq(u32 a, u32 b)
10947 {
10948         return !((a - b) & 0x80000000);
10949 }
10950
10951 static bool page_flip_finished(struct intel_crtc *crtc)
10952 {
10953         struct drm_device *dev = crtc->base.dev;
10954         struct drm_i915_private *dev_priv = dev->dev_private;
10955
10956         if (i915_reset_in_progress(&dev_priv->gpu_error) ||
10957             crtc->reset_counter != atomic_read(&dev_priv->gpu_error.reset_counter))
10958                 return true;
10959
10960         /*
10961          * The relevant registers doen't exist on pre-ctg.
10962          * As the flip done interrupt doesn't trigger for mmio
10963          * flips on gmch platforms, a flip count check isn't
10964          * really needed there. But since ctg has the registers,
10965          * include it in the check anyway.
10966          */
10967         if (INTEL_INFO(dev)->gen < 5 && !IS_G4X(dev))
10968                 return true;
10969
10970         /*
10971          * A DSPSURFLIVE check isn't enough in case the mmio and CS flips
10972          * used the same base address. In that case the mmio flip might
10973          * have completed, but the CS hasn't even executed the flip yet.
10974          *
10975          * A flip count check isn't enough as the CS might have updated
10976          * the base address just after start of vblank, but before we
10977          * managed to process the interrupt. This means we'd complete the
10978          * CS flip too soon.
10979          *
10980          * Combining both checks should get us a good enough result. It may
10981          * still happen that the CS flip has been executed, but has not
10982          * yet actually completed. But in case the base address is the same
10983          * anyway, we don't really care.
10984          */
10985         return (I915_READ(DSPSURFLIVE(crtc->plane)) & ~0xfff) ==
10986                 crtc->unpin_work->gtt_offset &&
10987                 g4x_flip_count_after_eq(I915_READ(PIPE_FLIPCOUNT_G4X(crtc->pipe)),
10988                                     crtc->unpin_work->flip_count);
10989 }
10990
10991 void intel_prepare_page_flip(struct drm_device *dev, int plane)
10992 {
10993         struct drm_i915_private *dev_priv = dev->dev_private;
10994         struct intel_crtc *intel_crtc =
10995                 to_intel_crtc(dev_priv->plane_to_crtc_mapping[plane]);
10996         unsigned long flags;
10997
10998
10999         /*
11000          * This is called both by irq handlers and the reset code (to complete
11001          * lost pageflips) so needs the full irqsave spinlocks.
11002          *
11003          * NB: An MMIO update of the plane base pointer will also
11004          * generate a page-flip completion irq, i.e. every modeset
11005          * is also accompanied by a spurious intel_prepare_page_flip().
11006          */
11007         spin_lock_irqsave(&dev->event_lock, flags);
11008         if (intel_crtc->unpin_work && page_flip_finished(intel_crtc))
11009                 atomic_inc_not_zero(&intel_crtc->unpin_work->pending);
11010         spin_unlock_irqrestore(&dev->event_lock, flags);
11011 }
11012
11013 static inline void intel_mark_page_flip_active(struct intel_unpin_work *work)
11014 {
11015         /* Ensure that the work item is consistent when activating it ... */
11016         smp_wmb();
11017         atomic_set(&work->pending, INTEL_FLIP_PENDING);
11018         /* and that it is marked active as soon as the irq could fire. */
11019         smp_wmb();
11020 }
11021
11022 static int intel_gen2_queue_flip(struct drm_device *dev,
11023                                  struct drm_crtc *crtc,
11024                                  struct drm_framebuffer *fb,
11025                                  struct drm_i915_gem_object *obj,
11026                                  struct drm_i915_gem_request *req,
11027                                  uint32_t flags)
11028 {
11029         struct intel_engine_cs *ring = req->ring;
11030         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
11031         u32 flip_mask;
11032         int ret;
11033
11034         ret = intel_ring_begin(req, 6);
11035         if (ret)
11036                 return ret;
11037
11038         /* Can't queue multiple flips, so wait for the previous
11039          * one to finish before executing the next.
11040          */
11041         if (intel_crtc->plane)
11042                 flip_mask = MI_WAIT_FOR_PLANE_B_FLIP;
11043         else
11044                 flip_mask = MI_WAIT_FOR_PLANE_A_FLIP;
11045         intel_ring_emit(ring, MI_WAIT_FOR_EVENT | flip_mask);
11046         intel_ring_emit(ring, MI_NOOP);
11047         intel_ring_emit(ring, MI_DISPLAY_FLIP |
11048                         MI_DISPLAY_FLIP_PLANE(intel_crtc->plane));
11049         intel_ring_emit(ring, fb->pitches[0]);
11050         intel_ring_emit(ring, intel_crtc->unpin_work->gtt_offset);
11051         intel_ring_emit(ring, 0); /* aux display base address, unused */
11052
11053         intel_mark_page_flip_active(intel_crtc->unpin_work);
11054         return 0;
11055 }
11056
11057 static int intel_gen3_queue_flip(struct drm_device *dev,
11058                                  struct drm_crtc *crtc,
11059                                  struct drm_framebuffer *fb,
11060                                  struct drm_i915_gem_object *obj,
11061                                  struct drm_i915_gem_request *req,
11062                                  uint32_t flags)
11063 {
11064         struct intel_engine_cs *ring = req->ring;
11065         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
11066         u32 flip_mask;
11067         int ret;
11068
11069         ret = intel_ring_begin(req, 6);
11070         if (ret)
11071                 return ret;
11072
11073         if (intel_crtc->plane)
11074                 flip_mask = MI_WAIT_FOR_PLANE_B_FLIP;
11075         else
11076                 flip_mask = MI_WAIT_FOR_PLANE_A_FLIP;
11077         intel_ring_emit(ring, MI_WAIT_FOR_EVENT | flip_mask);
11078         intel_ring_emit(ring, MI_NOOP);
11079         intel_ring_emit(ring, MI_DISPLAY_FLIP_I915 |
11080                         MI_DISPLAY_FLIP_PLANE(intel_crtc->plane));
11081         intel_ring_emit(ring, fb->pitches[0]);
11082         intel_ring_emit(ring, intel_crtc->unpin_work->gtt_offset);
11083         intel_ring_emit(ring, MI_NOOP);
11084
11085         intel_mark_page_flip_active(intel_crtc->unpin_work);
11086         return 0;
11087 }
11088
11089 static int intel_gen4_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 *ring = req->ring;
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         /* i965+ uses the linear or tiled offsets from the
11107          * Display Registers (which do not change across a page-flip)
11108          * so we need only reprogram the base address.
11109          */
11110         intel_ring_emit(ring, MI_DISPLAY_FLIP |
11111                         MI_DISPLAY_FLIP_PLANE(intel_crtc->plane));
11112         intel_ring_emit(ring, fb->pitches[0]);
11113         intel_ring_emit(ring, intel_crtc->unpin_work->gtt_offset |
11114                         obj->tiling_mode);
11115
11116         /* XXX Enabling the panel-fitter across page-flip is so far
11117          * untested on non-native modes, so ignore it for now.
11118          * pf = I915_READ(pipe == 0 ? PFA_CTL_1 : PFB_CTL_1) & PF_ENABLE;
11119          */
11120         pf = 0;
11121         pipesrc = I915_READ(PIPESRC(intel_crtc->pipe)) & 0x0fff0fff;
11122         intel_ring_emit(ring, pf | pipesrc);
11123
11124         intel_mark_page_flip_active(intel_crtc->unpin_work);
11125         return 0;
11126 }
11127
11128 static int intel_gen6_queue_flip(struct drm_device *dev,
11129                                  struct drm_crtc *crtc,
11130                                  struct drm_framebuffer *fb,
11131                                  struct drm_i915_gem_object *obj,
11132                                  struct drm_i915_gem_request *req,
11133                                  uint32_t flags)
11134 {
11135         struct intel_engine_cs *ring = req->ring;
11136         struct drm_i915_private *dev_priv = dev->dev_private;
11137         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
11138         uint32_t pf, pipesrc;
11139         int ret;
11140
11141         ret = intel_ring_begin(req, 4);
11142         if (ret)
11143                 return ret;
11144
11145         intel_ring_emit(ring, MI_DISPLAY_FLIP |
11146                         MI_DISPLAY_FLIP_PLANE(intel_crtc->plane));
11147         intel_ring_emit(ring, fb->pitches[0] | obj->tiling_mode);
11148         intel_ring_emit(ring, intel_crtc->unpin_work->gtt_offset);
11149
11150         /* Contrary to the suggestions in the documentation,
11151          * "Enable Panel Fitter" does not seem to be required when page
11152          * flipping with a non-native mode, and worse causes a normal
11153          * modeset to fail.
11154          * pf = I915_READ(PF_CTL(intel_crtc->pipe)) & PF_ENABLE;
11155          */
11156         pf = 0;
11157         pipesrc = I915_READ(PIPESRC(intel_crtc->pipe)) & 0x0fff0fff;
11158         intel_ring_emit(ring, pf | pipesrc);
11159
11160         intel_mark_page_flip_active(intel_crtc->unpin_work);
11161         return 0;
11162 }
11163
11164 static int intel_gen7_queue_flip(struct drm_device *dev,
11165                                  struct drm_crtc *crtc,
11166                                  struct drm_framebuffer *fb,
11167                                  struct drm_i915_gem_object *obj,
11168                                  struct drm_i915_gem_request *req,
11169                                  uint32_t flags)
11170 {
11171         struct intel_engine_cs *ring = req->ring;
11172         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
11173         uint32_t plane_bit = 0;
11174         int len, ret;
11175
11176         switch (intel_crtc->plane) {
11177         case PLANE_A:
11178                 plane_bit = MI_DISPLAY_FLIP_IVB_PLANE_A;
11179                 break;
11180         case PLANE_B:
11181                 plane_bit = MI_DISPLAY_FLIP_IVB_PLANE_B;
11182                 break;
11183         case PLANE_C:
11184                 plane_bit = MI_DISPLAY_FLIP_IVB_PLANE_C;
11185                 break;
11186         default:
11187                 WARN_ONCE(1, "unknown plane in flip command\n");
11188                 return -ENODEV;
11189         }
11190
11191         len = 4;
11192         if (ring->id == RCS) {
11193                 len += 6;
11194                 /*
11195                  * On Gen 8, SRM is now taking an extra dword to accommodate
11196                  * 48bits addresses, and we need a NOOP for the batch size to
11197                  * stay even.
11198                  */
11199                 if (IS_GEN8(dev))
11200                         len += 2;
11201         }
11202
11203         /*
11204          * BSpec MI_DISPLAY_FLIP for IVB:
11205          * "The full packet must be contained within the same cache line."
11206          *
11207          * Currently the LRI+SRM+MI_DISPLAY_FLIP all fit within the same
11208          * cacheline, if we ever start emitting more commands before
11209          * the MI_DISPLAY_FLIP we may need to first emit everything else,
11210          * then do the cacheline alignment, and finally emit the
11211          * MI_DISPLAY_FLIP.
11212          */
11213         ret = intel_ring_cacheline_align(req);
11214         if (ret)
11215                 return ret;
11216
11217         ret = intel_ring_begin(req, len);
11218         if (ret)
11219                 return ret;
11220
11221         /* Unmask the flip-done completion message. Note that the bspec says that
11222          * we should do this for both the BCS and RCS, and that we must not unmask
11223          * more than one flip event at any time (or ensure that one flip message
11224          * can be sent by waiting for flip-done prior to queueing new flips).
11225          * Experimentation says that BCS works despite DERRMR masking all
11226          * flip-done completion events and that unmasking all planes at once
11227          * for the RCS also doesn't appear to drop events. Setting the DERRMR
11228          * to zero does lead to lockups within MI_DISPLAY_FLIP.
11229          */
11230         if (ring->id == RCS) {
11231                 intel_ring_emit(ring, MI_LOAD_REGISTER_IMM(1));
11232                 intel_ring_emit_reg(ring, DERRMR);
11233                 intel_ring_emit(ring, ~(DERRMR_PIPEA_PRI_FLIP_DONE |
11234                                         DERRMR_PIPEB_PRI_FLIP_DONE |
11235                                         DERRMR_PIPEC_PRI_FLIP_DONE));
11236                 if (IS_GEN8(dev))
11237                         intel_ring_emit(ring, MI_STORE_REGISTER_MEM_GEN8 |
11238                                               MI_SRM_LRM_GLOBAL_GTT);
11239                 else
11240                         intel_ring_emit(ring, MI_STORE_REGISTER_MEM |
11241                                               MI_SRM_LRM_GLOBAL_GTT);
11242                 intel_ring_emit_reg(ring, DERRMR);
11243                 intel_ring_emit(ring, ring->scratch.gtt_offset + 256);
11244                 if (IS_GEN8(dev)) {
11245                         intel_ring_emit(ring, 0);
11246                         intel_ring_emit(ring, MI_NOOP);
11247                 }
11248         }
11249
11250         intel_ring_emit(ring, MI_DISPLAY_FLIP_I915 | plane_bit);
11251         intel_ring_emit(ring, (fb->pitches[0] | obj->tiling_mode));
11252         intel_ring_emit(ring, intel_crtc->unpin_work->gtt_offset);
11253         intel_ring_emit(ring, (MI_NOOP));
11254
11255         intel_mark_page_flip_active(intel_crtc->unpin_work);
11256         return 0;
11257 }
11258
11259 static bool use_mmio_flip(struct intel_engine_cs *ring,
11260                           struct drm_i915_gem_object *obj)
11261 {
11262         /*
11263          * This is not being used for older platforms, because
11264          * non-availability of flip done interrupt forces us to use
11265          * CS flips. Older platforms derive flip done using some clever
11266          * tricks involving the flip_pending status bits and vblank irqs.
11267          * So using MMIO flips there would disrupt this mechanism.
11268          */
11269
11270         if (ring == NULL)
11271                 return true;
11272
11273         if (INTEL_INFO(ring->dev)->gen < 5)
11274                 return false;
11275
11276         if (i915.use_mmio_flip < 0)
11277                 return false;
11278         else if (i915.use_mmio_flip > 0)
11279                 return true;
11280         else if (i915.enable_execlists)
11281                 return true;
11282         else if (obj->base.dma_buf &&
11283                  !reservation_object_test_signaled_rcu(obj->base.dma_buf->resv,
11284                                                        false))
11285                 return true;
11286         else
11287                 return ring != i915_gem_request_get_ring(obj->last_write_req);
11288 }
11289
11290 static void skl_do_mmio_flip(struct intel_crtc *intel_crtc,
11291                              unsigned int rotation,
11292                              struct intel_unpin_work *work)
11293 {
11294         struct drm_device *dev = intel_crtc->base.dev;
11295         struct drm_i915_private *dev_priv = dev->dev_private;
11296         struct drm_framebuffer *fb = intel_crtc->base.primary->fb;
11297         const enum pipe pipe = intel_crtc->pipe;
11298         u32 ctl, stride, tile_height;
11299
11300         ctl = I915_READ(PLANE_CTL(pipe, 0));
11301         ctl &= ~PLANE_CTL_TILED_MASK;
11302         switch (fb->modifier[0]) {
11303         case DRM_FORMAT_MOD_NONE:
11304                 break;
11305         case I915_FORMAT_MOD_X_TILED:
11306                 ctl |= PLANE_CTL_TILED_X;
11307                 break;
11308         case I915_FORMAT_MOD_Y_TILED:
11309                 ctl |= PLANE_CTL_TILED_Y;
11310                 break;
11311         case I915_FORMAT_MOD_Yf_TILED:
11312                 ctl |= PLANE_CTL_TILED_YF;
11313                 break;
11314         default:
11315                 MISSING_CASE(fb->modifier[0]);
11316         }
11317
11318         /*
11319          * The stride is either expressed as a multiple of 64 bytes chunks for
11320          * linear buffers or in number of tiles for tiled buffers.
11321          */
11322         if (intel_rotation_90_or_270(rotation)) {
11323                 /* stride = Surface height in tiles */
11324                 tile_height = intel_tile_height(dev, fb->pixel_format,
11325                                                 fb->modifier[0], 0);
11326                 stride = DIV_ROUND_UP(fb->height, tile_height);
11327         } else {
11328                 stride = fb->pitches[0] /
11329                                 intel_fb_stride_alignment(dev, fb->modifier[0],
11330                                                           fb->pixel_format);
11331         }
11332
11333         /*
11334          * Both PLANE_CTL and PLANE_STRIDE are not updated on vblank but on
11335          * PLANE_SURF updates, the update is then guaranteed to be atomic.
11336          */
11337         I915_WRITE(PLANE_CTL(pipe, 0), ctl);
11338         I915_WRITE(PLANE_STRIDE(pipe, 0), stride);
11339
11340         I915_WRITE(PLANE_SURF(pipe, 0), work->gtt_offset);
11341         POSTING_READ(PLANE_SURF(pipe, 0));
11342 }
11343
11344 static void ilk_do_mmio_flip(struct intel_crtc *intel_crtc,
11345                              struct intel_unpin_work *work)
11346 {
11347         struct drm_device *dev = intel_crtc->base.dev;
11348         struct drm_i915_private *dev_priv = dev->dev_private;
11349         struct intel_framebuffer *intel_fb =
11350                 to_intel_framebuffer(intel_crtc->base.primary->fb);
11351         struct drm_i915_gem_object *obj = intel_fb->obj;
11352         i915_reg_t reg = DSPCNTR(intel_crtc->plane);
11353         u32 dspcntr;
11354
11355         dspcntr = I915_READ(reg);
11356
11357         if (obj->tiling_mode != I915_TILING_NONE)
11358                 dspcntr |= DISPPLANE_TILED;
11359         else
11360                 dspcntr &= ~DISPPLANE_TILED;
11361
11362         I915_WRITE(reg, dspcntr);
11363
11364         I915_WRITE(DSPSURF(intel_crtc->plane), work->gtt_offset);
11365         POSTING_READ(DSPSURF(intel_crtc->plane));
11366 }
11367
11368 /*
11369  * XXX: This is the temporary way to update the plane registers until we get
11370  * around to using the usual plane update functions for MMIO flips
11371  */
11372 static void intel_do_mmio_flip(struct intel_mmio_flip *mmio_flip)
11373 {
11374         struct intel_crtc *crtc = mmio_flip->crtc;
11375         struct intel_unpin_work *work;
11376
11377         spin_lock_irq(&crtc->base.dev->event_lock);
11378         work = crtc->unpin_work;
11379         spin_unlock_irq(&crtc->base.dev->event_lock);
11380         if (work == NULL)
11381                 return;
11382
11383         intel_mark_page_flip_active(work);
11384
11385         intel_pipe_update_start(crtc);
11386
11387         if (INTEL_INFO(mmio_flip->i915)->gen >= 9)
11388                 skl_do_mmio_flip(crtc, mmio_flip->rotation, work);
11389         else
11390                 /* use_mmio_flip() retricts MMIO flips to ilk+ */
11391                 ilk_do_mmio_flip(crtc, work);
11392
11393         intel_pipe_update_end(crtc);
11394 }
11395
11396 static void intel_mmio_flip_work_func(struct work_struct *work)
11397 {
11398         struct intel_mmio_flip *mmio_flip =
11399                 container_of(work, struct intel_mmio_flip, work);
11400         struct intel_framebuffer *intel_fb =
11401                 to_intel_framebuffer(mmio_flip->crtc->base.primary->fb);
11402         struct drm_i915_gem_object *obj = intel_fb->obj;
11403
11404         if (mmio_flip->req) {
11405                 WARN_ON(__i915_wait_request(mmio_flip->req,
11406                                             mmio_flip->crtc->reset_counter,
11407                                             false, NULL,
11408                                             &mmio_flip->i915->rps.mmioflips));
11409                 i915_gem_request_unreference__unlocked(mmio_flip->req);
11410         }
11411
11412         /* For framebuffer backed by dmabuf, wait for fence */
11413         if (obj->base.dma_buf)
11414                 WARN_ON(reservation_object_wait_timeout_rcu(obj->base.dma_buf->resv,
11415                                                             false, false,
11416                                                             MAX_SCHEDULE_TIMEOUT) < 0);
11417
11418         intel_do_mmio_flip(mmio_flip);
11419         kfree(mmio_flip);
11420 }
11421
11422 static int intel_queue_mmio_flip(struct drm_device *dev,
11423                                  struct drm_crtc *crtc,
11424                                  struct drm_i915_gem_object *obj)
11425 {
11426         struct intel_mmio_flip *mmio_flip;
11427
11428         mmio_flip = kmalloc(sizeof(*mmio_flip), GFP_KERNEL);
11429         if (mmio_flip == NULL)
11430                 return -ENOMEM;
11431
11432         mmio_flip->i915 = to_i915(dev);
11433         mmio_flip->req = i915_gem_request_reference(obj->last_write_req);
11434         mmio_flip->crtc = to_intel_crtc(crtc);
11435         mmio_flip->rotation = crtc->primary->state->rotation;
11436
11437         INIT_WORK(&mmio_flip->work, intel_mmio_flip_work_func);
11438         schedule_work(&mmio_flip->work);
11439
11440         return 0;
11441 }
11442
11443 static int intel_default_queue_flip(struct drm_device *dev,
11444                                     struct drm_crtc *crtc,
11445                                     struct drm_framebuffer *fb,
11446                                     struct drm_i915_gem_object *obj,
11447                                     struct drm_i915_gem_request *req,
11448                                     uint32_t flags)
11449 {
11450         return -ENODEV;
11451 }
11452
11453 static bool __intel_pageflip_stall_check(struct drm_device *dev,
11454                                          struct drm_crtc *crtc)
11455 {
11456         struct drm_i915_private *dev_priv = dev->dev_private;
11457         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
11458         struct intel_unpin_work *work = intel_crtc->unpin_work;
11459         u32 addr;
11460
11461         if (atomic_read(&work->pending) >= INTEL_FLIP_COMPLETE)
11462                 return true;
11463
11464         if (atomic_read(&work->pending) < INTEL_FLIP_PENDING)
11465                 return false;
11466
11467         if (!work->enable_stall_check)
11468                 return false;
11469
11470         if (work->flip_ready_vblank == 0) {
11471                 if (work->flip_queued_req &&
11472                     !i915_gem_request_completed(work->flip_queued_req, true))
11473                         return false;
11474
11475                 work->flip_ready_vblank = drm_crtc_vblank_count(crtc);
11476         }
11477
11478         if (drm_crtc_vblank_count(crtc) - work->flip_ready_vblank < 3)
11479                 return false;
11480
11481         /* Potential stall - if we see that the flip has happened,
11482          * assume a missed interrupt. */
11483         if (INTEL_INFO(dev)->gen >= 4)
11484                 addr = I915_HI_DISPBASE(I915_READ(DSPSURF(intel_crtc->plane)));
11485         else
11486                 addr = I915_READ(DSPADDR(intel_crtc->plane));
11487
11488         /* There is a potential issue here with a false positive after a flip
11489          * to the same address. We could address this by checking for a
11490          * non-incrementing frame counter.
11491          */
11492         return addr == work->gtt_offset;
11493 }
11494
11495 void intel_check_page_flip(struct drm_device *dev, int pipe)
11496 {
11497         struct drm_i915_private *dev_priv = dev->dev_private;
11498         struct drm_crtc *crtc = dev_priv->pipe_to_crtc_mapping[pipe];
11499         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
11500         struct intel_unpin_work *work;
11501
11502         WARN_ON(!in_interrupt());
11503
11504         if (crtc == NULL)
11505                 return;
11506
11507         spin_lock(&dev->event_lock);
11508         work = intel_crtc->unpin_work;
11509         if (work != NULL && __intel_pageflip_stall_check(dev, crtc)) {
11510                 WARN_ONCE(1, "Kicking stuck page flip: queued at %d, now %d\n",
11511                          work->flip_queued_vblank, drm_vblank_count(dev, pipe));
11512                 page_flip_completed(intel_crtc);
11513                 work = NULL;
11514         }
11515         if (work != NULL &&
11516             drm_vblank_count(dev, pipe) - work->flip_queued_vblank > 1)
11517                 intel_queue_rps_boost_for_request(dev, work->flip_queued_req);
11518         spin_unlock(&dev->event_lock);
11519 }
11520
11521 static int intel_crtc_page_flip(struct drm_crtc *crtc,
11522                                 struct drm_framebuffer *fb,
11523                                 struct drm_pending_vblank_event *event,
11524                                 uint32_t page_flip_flags)
11525 {
11526         struct drm_device *dev = crtc->dev;
11527         struct drm_i915_private *dev_priv = dev->dev_private;
11528         struct drm_framebuffer *old_fb = crtc->primary->fb;
11529         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
11530         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
11531         struct drm_plane *primary = crtc->primary;
11532         enum pipe pipe = intel_crtc->pipe;
11533         struct intel_unpin_work *work;
11534         struct intel_engine_cs *ring;
11535         bool mmio_flip;
11536         struct drm_i915_gem_request *request = NULL;
11537         int ret;
11538
11539         /*
11540          * drm_mode_page_flip_ioctl() should already catch this, but double
11541          * check to be safe.  In the future we may enable pageflipping from
11542          * a disabled primary plane.
11543          */
11544         if (WARN_ON(intel_fb_obj(old_fb) == NULL))
11545                 return -EBUSY;
11546
11547         /* Can't change pixel format via MI display flips. */
11548         if (fb->pixel_format != crtc->primary->fb->pixel_format)
11549                 return -EINVAL;
11550
11551         /*
11552          * TILEOFF/LINOFF registers can't be changed via MI display flips.
11553          * Note that pitch changes could also affect these register.
11554          */
11555         if (INTEL_INFO(dev)->gen > 3 &&
11556             (fb->offsets[0] != crtc->primary->fb->offsets[0] ||
11557              fb->pitches[0] != crtc->primary->fb->pitches[0]))
11558                 return -EINVAL;
11559
11560         if (i915_terminally_wedged(&dev_priv->gpu_error))
11561                 goto out_hang;
11562
11563         work = kzalloc(sizeof(*work), GFP_KERNEL);
11564         if (work == NULL)
11565                 return -ENOMEM;
11566
11567         work->event = event;
11568         work->crtc = crtc;
11569         work->old_fb = old_fb;
11570         INIT_WORK(&work->work, intel_unpin_work_fn);
11571
11572         ret = drm_crtc_vblank_get(crtc);
11573         if (ret)
11574                 goto free_work;
11575
11576         /* We borrow the event spin lock for protecting unpin_work */
11577         spin_lock_irq(&dev->event_lock);
11578         if (intel_crtc->unpin_work) {
11579                 /* Before declaring the flip queue wedged, check if
11580                  * the hardware completed the operation behind our backs.
11581                  */
11582                 if (__intel_pageflip_stall_check(dev, crtc)) {
11583                         DRM_DEBUG_DRIVER("flip queue: previous flip completed, continuing\n");
11584                         page_flip_completed(intel_crtc);
11585                 } else {
11586                         DRM_DEBUG_DRIVER("flip queue: crtc already busy\n");
11587                         spin_unlock_irq(&dev->event_lock);
11588
11589                         drm_crtc_vblank_put(crtc);
11590                         kfree(work);
11591                         return -EBUSY;
11592                 }
11593         }
11594         intel_crtc->unpin_work = work;
11595         spin_unlock_irq(&dev->event_lock);
11596
11597         if (atomic_read(&intel_crtc->unpin_work_count) >= 2)
11598                 flush_workqueue(dev_priv->wq);
11599
11600         /* Reference the objects for the scheduled work. */
11601         drm_framebuffer_reference(work->old_fb);
11602         drm_gem_object_reference(&obj->base);
11603
11604         crtc->primary->fb = fb;
11605         update_state_fb(crtc->primary);
11606
11607         work->pending_flip_obj = obj;
11608
11609         ret = i915_mutex_lock_interruptible(dev);
11610         if (ret)
11611                 goto cleanup;
11612
11613         atomic_inc(&intel_crtc->unpin_work_count);
11614         intel_crtc->reset_counter = atomic_read(&dev_priv->gpu_error.reset_counter);
11615
11616         if (INTEL_INFO(dev)->gen >= 5 || IS_G4X(dev))
11617                 work->flip_count = I915_READ(PIPE_FLIPCOUNT_G4X(pipe)) + 1;
11618
11619         if (IS_VALLEYVIEW(dev) || IS_CHERRYVIEW(dev)) {
11620                 ring = &dev_priv->ring[BCS];
11621                 if (obj->tiling_mode != intel_fb_obj(work->old_fb)->tiling_mode)
11622                         /* vlv: DISPLAY_FLIP fails to change tiling */
11623                         ring = NULL;
11624         } else if (IS_IVYBRIDGE(dev) || IS_HASWELL(dev)) {
11625                 ring = &dev_priv->ring[BCS];
11626         } else if (INTEL_INFO(dev)->gen >= 7) {
11627                 ring = i915_gem_request_get_ring(obj->last_write_req);
11628                 if (ring == NULL || ring->id != RCS)
11629                         ring = &dev_priv->ring[BCS];
11630         } else {
11631                 ring = &dev_priv->ring[RCS];
11632         }
11633
11634         mmio_flip = use_mmio_flip(ring, obj);
11635
11636         /* When using CS flips, we want to emit semaphores between rings.
11637          * However, when using mmio flips we will create a task to do the
11638          * synchronisation, so all we want here is to pin the framebuffer
11639          * into the display plane and skip any waits.
11640          */
11641         if (!mmio_flip) {
11642                 ret = i915_gem_object_sync(obj, ring, &request);
11643                 if (ret)
11644                         goto cleanup_pending;
11645         }
11646
11647         ret = intel_pin_and_fence_fb_obj(crtc->primary, fb,
11648                                          crtc->primary->state);
11649         if (ret)
11650                 goto cleanup_pending;
11651
11652         work->gtt_offset = intel_plane_obj_offset(to_intel_plane(primary),
11653                                                   obj, 0);
11654         work->gtt_offset += intel_crtc->dspaddr_offset;
11655
11656         if (mmio_flip) {
11657                 ret = intel_queue_mmio_flip(dev, crtc, obj);
11658                 if (ret)
11659                         goto cleanup_unpin;
11660
11661                 i915_gem_request_assign(&work->flip_queued_req,
11662                                         obj->last_write_req);
11663         } else {
11664                 if (!request) {
11665                         ret = i915_gem_request_alloc(ring, ring->default_context, &request);
11666                         if (ret)
11667                                 goto cleanup_unpin;
11668                 }
11669
11670                 ret = dev_priv->display.queue_flip(dev, crtc, fb, obj, request,
11671                                                    page_flip_flags);
11672                 if (ret)
11673                         goto cleanup_unpin;
11674
11675                 i915_gem_request_assign(&work->flip_queued_req, request);
11676         }
11677
11678         if (request)
11679                 i915_add_request_no_flush(request);
11680
11681         work->flip_queued_vblank = drm_crtc_vblank_count(crtc);
11682         work->enable_stall_check = true;
11683
11684         i915_gem_track_fb(intel_fb_obj(work->old_fb), obj,
11685                           to_intel_plane(primary)->frontbuffer_bit);
11686         mutex_unlock(&dev->struct_mutex);
11687
11688         intel_fbc_deactivate(intel_crtc);
11689         intel_frontbuffer_flip_prepare(dev,
11690                                        to_intel_plane(primary)->frontbuffer_bit);
11691
11692         trace_i915_flip_request(intel_crtc->plane, obj);
11693
11694         return 0;
11695
11696 cleanup_unpin:
11697         intel_unpin_fb_obj(fb, crtc->primary->state);
11698 cleanup_pending:
11699         if (request)
11700                 i915_gem_request_cancel(request);
11701         atomic_dec(&intel_crtc->unpin_work_count);
11702         mutex_unlock(&dev->struct_mutex);
11703 cleanup:
11704         crtc->primary->fb = old_fb;
11705         update_state_fb(crtc->primary);
11706
11707         drm_gem_object_unreference_unlocked(&obj->base);
11708         drm_framebuffer_unreference(work->old_fb);
11709
11710         spin_lock_irq(&dev->event_lock);
11711         intel_crtc->unpin_work = NULL;
11712         spin_unlock_irq(&dev->event_lock);
11713
11714         drm_crtc_vblank_put(crtc);
11715 free_work:
11716         kfree(work);
11717
11718         if (ret == -EIO) {
11719                 struct drm_atomic_state *state;
11720                 struct drm_plane_state *plane_state;
11721
11722 out_hang:
11723                 state = drm_atomic_state_alloc(dev);
11724                 if (!state)
11725                         return -ENOMEM;
11726                 state->acquire_ctx = drm_modeset_legacy_acquire_ctx(crtc);
11727
11728 retry:
11729                 plane_state = drm_atomic_get_plane_state(state, primary);
11730                 ret = PTR_ERR_OR_ZERO(plane_state);
11731                 if (!ret) {
11732                         drm_atomic_set_fb_for_plane(plane_state, fb);
11733
11734                         ret = drm_atomic_set_crtc_for_plane(plane_state, crtc);
11735                         if (!ret)
11736                                 ret = drm_atomic_commit(state);
11737                 }
11738
11739                 if (ret == -EDEADLK) {
11740                         drm_modeset_backoff(state->acquire_ctx);
11741                         drm_atomic_state_clear(state);
11742                         goto retry;
11743                 }
11744
11745                 if (ret)
11746                         drm_atomic_state_free(state);
11747
11748                 if (ret == 0 && event) {
11749                         spin_lock_irq(&dev->event_lock);
11750                         drm_send_vblank_event(dev, pipe, event);
11751                         spin_unlock_irq(&dev->event_lock);
11752                 }
11753         }
11754         return ret;
11755 }
11756
11757
11758 /**
11759  * intel_wm_need_update - Check whether watermarks need updating
11760  * @plane: drm plane
11761  * @state: new plane state
11762  *
11763  * Check current plane state versus the new one to determine whether
11764  * watermarks need to be recalculated.
11765  *
11766  * Returns true or false.
11767  */
11768 static bool intel_wm_need_update(struct drm_plane *plane,
11769                                  struct drm_plane_state *state)
11770 {
11771         struct intel_plane_state *new = to_intel_plane_state(state);
11772         struct intel_plane_state *cur = to_intel_plane_state(plane->state);
11773
11774         /* Update watermarks on tiling or size changes. */
11775         if (new->visible != cur->visible)
11776                 return true;
11777
11778         if (!cur->base.fb || !new->base.fb)
11779                 return false;
11780
11781         if (cur->base.fb->modifier[0] != new->base.fb->modifier[0] ||
11782             cur->base.rotation != new->base.rotation ||
11783             drm_rect_width(&new->src) != drm_rect_width(&cur->src) ||
11784             drm_rect_height(&new->src) != drm_rect_height(&cur->src) ||
11785             drm_rect_width(&new->dst) != drm_rect_width(&cur->dst) ||
11786             drm_rect_height(&new->dst) != drm_rect_height(&cur->dst))
11787                 return true;
11788
11789         return false;
11790 }
11791
11792 static bool needs_scaling(struct intel_plane_state *state)
11793 {
11794         int src_w = drm_rect_width(&state->src) >> 16;
11795         int src_h = drm_rect_height(&state->src) >> 16;
11796         int dst_w = drm_rect_width(&state->dst);
11797         int dst_h = drm_rect_height(&state->dst);
11798
11799         return (src_w != dst_w || src_h != dst_h);
11800 }
11801
11802 int intel_plane_atomic_calc_changes(struct drm_crtc_state *crtc_state,
11803                                     struct drm_plane_state *plane_state)
11804 {
11805         struct intel_crtc_state *pipe_config = to_intel_crtc_state(crtc_state);
11806         struct drm_crtc *crtc = crtc_state->crtc;
11807         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
11808         struct drm_plane *plane = plane_state->plane;
11809         struct drm_device *dev = crtc->dev;
11810         struct drm_i915_private *dev_priv = dev->dev_private;
11811         struct intel_plane_state *old_plane_state =
11812                 to_intel_plane_state(plane->state);
11813         int idx = intel_crtc->base.base.id, ret;
11814         int i = drm_plane_index(plane);
11815         bool mode_changed = needs_modeset(crtc_state);
11816         bool was_crtc_enabled = crtc->state->active;
11817         bool is_crtc_enabled = crtc_state->active;
11818         bool turn_off, turn_on, visible, was_visible;
11819         struct drm_framebuffer *fb = plane_state->fb;
11820
11821         if (crtc_state && INTEL_INFO(dev)->gen >= 9 &&
11822             plane->type != DRM_PLANE_TYPE_CURSOR) {
11823                 ret = skl_update_scaler_plane(
11824                         to_intel_crtc_state(crtc_state),
11825                         to_intel_plane_state(plane_state));
11826                 if (ret)
11827                         return ret;
11828         }
11829
11830         was_visible = old_plane_state->visible;
11831         visible = to_intel_plane_state(plane_state)->visible;
11832
11833         if (!was_crtc_enabled && WARN_ON(was_visible))
11834                 was_visible = false;
11835
11836         if (!is_crtc_enabled && WARN_ON(visible))
11837                 visible = false;
11838
11839         if (!was_visible && !visible)
11840                 return 0;
11841
11842         turn_off = was_visible && (!visible || mode_changed);
11843         turn_on = visible && (!was_visible || mode_changed);
11844
11845         DRM_DEBUG_ATOMIC("[CRTC:%i] has [PLANE:%i] with fb %i\n", idx,
11846                          plane->base.id, fb ? fb->base.id : -1);
11847
11848         DRM_DEBUG_ATOMIC("[PLANE:%i] visible %i -> %i, off %i, on %i, ms %i\n",
11849                          plane->base.id, was_visible, visible,
11850                          turn_off, turn_on, mode_changed);
11851
11852         if (turn_on || turn_off) {
11853                 pipe_config->wm_changed = true;
11854
11855                 /* must disable cxsr around plane enable/disable */
11856                 if (plane->type != DRM_PLANE_TYPE_CURSOR) {
11857                         if (is_crtc_enabled)
11858                                 intel_crtc->atomic.wait_vblank = true;
11859                         pipe_config->disable_cxsr = true;
11860                 }
11861         } else if (intel_wm_need_update(plane, plane_state)) {
11862                 pipe_config->wm_changed = true;
11863         }
11864
11865         if (visible || was_visible)
11866                 intel_crtc->atomic.fb_bits |=
11867                         to_intel_plane(plane)->frontbuffer_bit;
11868
11869         switch (plane->type) {
11870         case DRM_PLANE_TYPE_PRIMARY:
11871                 intel_crtc->atomic.pre_disable_primary = turn_off;
11872                 intel_crtc->atomic.post_enable_primary = turn_on;
11873
11874                 if (turn_off) {
11875                         /*
11876                          * FIXME: Actually if we will still have any other
11877                          * plane enabled on the pipe we could let IPS enabled
11878                          * still, but for now lets consider that when we make
11879                          * primary invisible by setting DSPCNTR to 0 on
11880                          * update_primary_plane function IPS needs to be
11881                          * disable.
11882                          */
11883                         intel_crtc->atomic.disable_ips = true;
11884
11885                         intel_crtc->atomic.disable_fbc = true;
11886                 }
11887
11888                 /*
11889                  * FBC does not work on some platforms for rotated
11890                  * planes, so disable it when rotation is not 0 and
11891                  * update it when rotation is set back to 0.
11892                  *
11893                  * FIXME: This is redundant with the fbc update done in
11894                  * the primary plane enable function except that that
11895                  * one is done too late. We eventually need to unify
11896                  * this.
11897                  */
11898
11899                 if (visible &&
11900                     INTEL_INFO(dev)->gen <= 4 && !IS_G4X(dev) &&
11901                     dev_priv->fbc.crtc == intel_crtc &&
11902                     plane_state->rotation != BIT(DRM_ROTATE_0))
11903                         intel_crtc->atomic.disable_fbc = true;
11904
11905                 /*
11906                  * BDW signals flip done immediately if the plane
11907                  * is disabled, even if the plane enable is already
11908                  * armed to occur at the next vblank :(
11909                  */
11910                 if (turn_on && IS_BROADWELL(dev))
11911                         intel_crtc->atomic.wait_vblank = true;
11912
11913                 intel_crtc->atomic.update_fbc |= visible || mode_changed;
11914                 break;
11915         case DRM_PLANE_TYPE_CURSOR:
11916                 break;
11917         case DRM_PLANE_TYPE_OVERLAY:
11918                 /*
11919                  * WaCxSRDisabledForSpriteScaling:ivb
11920                  *
11921                  * cstate->update_wm was already set above, so this flag will
11922                  * take effect when we commit and program watermarks.
11923                  */
11924                 if (IS_IVYBRIDGE(dev) &&
11925                     needs_scaling(to_intel_plane_state(plane_state)) &&
11926                     !needs_scaling(old_plane_state)) {
11927                         to_intel_crtc_state(crtc_state)->disable_lp_wm = true;
11928                 } else if (turn_off && !mode_changed) {
11929                         intel_crtc->atomic.wait_vblank = true;
11930                         intel_crtc->atomic.update_sprite_watermarks |=
11931                                 1 << i;
11932                 }
11933
11934                 break;
11935         }
11936         return 0;
11937 }
11938
11939 static bool encoders_cloneable(const struct intel_encoder *a,
11940                                const struct intel_encoder *b)
11941 {
11942         /* masks could be asymmetric, so check both ways */
11943         return a == b || (a->cloneable & (1 << b->type) &&
11944                           b->cloneable & (1 << a->type));
11945 }
11946
11947 static bool check_single_encoder_cloning(struct drm_atomic_state *state,
11948                                          struct intel_crtc *crtc,
11949                                          struct intel_encoder *encoder)
11950 {
11951         struct intel_encoder *source_encoder;
11952         struct drm_connector *connector;
11953         struct drm_connector_state *connector_state;
11954         int i;
11955
11956         for_each_connector_in_state(state, connector, connector_state, i) {
11957                 if (connector_state->crtc != &crtc->base)
11958                         continue;
11959
11960                 source_encoder =
11961                         to_intel_encoder(connector_state->best_encoder);
11962                 if (!encoders_cloneable(encoder, source_encoder))
11963                         return false;
11964         }
11965
11966         return true;
11967 }
11968
11969 static bool check_encoder_cloning(struct drm_atomic_state *state,
11970                                   struct intel_crtc *crtc)
11971 {
11972         struct intel_encoder *encoder;
11973         struct drm_connector *connector;
11974         struct drm_connector_state *connector_state;
11975         int i;
11976
11977         for_each_connector_in_state(state, connector, connector_state, i) {
11978                 if (connector_state->crtc != &crtc->base)
11979                         continue;
11980
11981                 encoder = to_intel_encoder(connector_state->best_encoder);
11982                 if (!check_single_encoder_cloning(state, crtc, encoder))
11983                         return false;
11984         }
11985
11986         return true;
11987 }
11988
11989 static int intel_crtc_atomic_check(struct drm_crtc *crtc,
11990                                    struct drm_crtc_state *crtc_state)
11991 {
11992         struct drm_device *dev = crtc->dev;
11993         struct drm_i915_private *dev_priv = dev->dev_private;
11994         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
11995         struct intel_crtc_state *pipe_config =
11996                 to_intel_crtc_state(crtc_state);
11997         struct drm_atomic_state *state = crtc_state->state;
11998         int ret;
11999         bool mode_changed = needs_modeset(crtc_state);
12000
12001         if (mode_changed && !check_encoder_cloning(state, intel_crtc)) {
12002                 DRM_DEBUG_KMS("rejecting invalid cloning configuration\n");
12003                 return -EINVAL;
12004         }
12005
12006         if (mode_changed && !crtc_state->active)
12007                 pipe_config->wm_changed = true;
12008
12009         if (mode_changed && crtc_state->enable &&
12010             dev_priv->display.crtc_compute_clock &&
12011             !WARN_ON(pipe_config->shared_dpll != DPLL_ID_PRIVATE)) {
12012                 ret = dev_priv->display.crtc_compute_clock(intel_crtc,
12013                                                            pipe_config);
12014                 if (ret)
12015                         return ret;
12016         }
12017
12018         ret = 0;
12019         if (dev_priv->display.compute_pipe_wm) {
12020                 ret = dev_priv->display.compute_pipe_wm(intel_crtc, state);
12021                 if (ret)
12022                         return ret;
12023         }
12024
12025         if (INTEL_INFO(dev)->gen >= 9) {
12026                 if (mode_changed)
12027                         ret = skl_update_scaler_crtc(pipe_config);
12028
12029                 if (!ret)
12030                         ret = intel_atomic_setup_scalers(dev, intel_crtc,
12031                                                          pipe_config);
12032         }
12033
12034         return ret;
12035 }
12036
12037 static const struct drm_crtc_helper_funcs intel_helper_funcs = {
12038         .mode_set_base_atomic = intel_pipe_set_base_atomic,
12039         .load_lut = intel_crtc_load_lut,
12040         .atomic_begin = intel_begin_crtc_commit,
12041         .atomic_flush = intel_finish_crtc_commit,
12042         .atomic_check = intel_crtc_atomic_check,
12043 };
12044
12045 static void intel_modeset_update_connector_atomic_state(struct drm_device *dev)
12046 {
12047         struct intel_connector *connector;
12048
12049         for_each_intel_connector(dev, connector) {
12050                 if (connector->base.encoder) {
12051                         connector->base.state->best_encoder =
12052                                 connector->base.encoder;
12053                         connector->base.state->crtc =
12054                                 connector->base.encoder->crtc;
12055                 } else {
12056                         connector->base.state->best_encoder = NULL;
12057                         connector->base.state->crtc = NULL;
12058                 }
12059         }
12060 }
12061
12062 static void
12063 connected_sink_compute_bpp(struct intel_connector *connector,
12064                            struct intel_crtc_state *pipe_config)
12065 {
12066         int bpp = pipe_config->pipe_bpp;
12067
12068         DRM_DEBUG_KMS("[CONNECTOR:%d:%s] checking for sink bpp constrains\n",
12069                 connector->base.base.id,
12070                 connector->base.name);
12071
12072         /* Don't use an invalid EDID bpc value */
12073         if (connector->base.display_info.bpc &&
12074             connector->base.display_info.bpc * 3 < bpp) {
12075                 DRM_DEBUG_KMS("clamping display bpp (was %d) to EDID reported max of %d\n",
12076                               bpp, connector->base.display_info.bpc*3);
12077                 pipe_config->pipe_bpp = connector->base.display_info.bpc*3;
12078         }
12079
12080         /* Clamp bpp to 8 on screens without EDID 1.4 */
12081         if (connector->base.display_info.bpc == 0 && bpp > 24) {
12082                 DRM_DEBUG_KMS("clamping display bpp (was %d) to default limit of 24\n",
12083                               bpp);
12084                 pipe_config->pipe_bpp = 24;
12085         }
12086 }
12087
12088 static int
12089 compute_baseline_pipe_bpp(struct intel_crtc *crtc,
12090                           struct intel_crtc_state *pipe_config)
12091 {
12092         struct drm_device *dev = crtc->base.dev;
12093         struct drm_atomic_state *state;
12094         struct drm_connector *connector;
12095         struct drm_connector_state *connector_state;
12096         int bpp, i;
12097
12098         if ((IS_G4X(dev) || IS_VALLEYVIEW(dev) || IS_CHERRYVIEW(dev)))
12099                 bpp = 10*3;
12100         else if (INTEL_INFO(dev)->gen >= 5)
12101                 bpp = 12*3;
12102         else
12103                 bpp = 8*3;
12104
12105
12106         pipe_config->pipe_bpp = bpp;
12107
12108         state = pipe_config->base.state;
12109
12110         /* Clamp display bpp to EDID value */
12111         for_each_connector_in_state(state, connector, connector_state, i) {
12112                 if (connector_state->crtc != &crtc->base)
12113                         continue;
12114
12115                 connected_sink_compute_bpp(to_intel_connector(connector),
12116                                            pipe_config);
12117         }
12118
12119         return bpp;
12120 }
12121
12122 static void intel_dump_crtc_timings(const struct drm_display_mode *mode)
12123 {
12124         DRM_DEBUG_KMS("crtc timings: %d %d %d %d %d %d %d %d %d, "
12125                         "type: 0x%x flags: 0x%x\n",
12126                 mode->crtc_clock,
12127                 mode->crtc_hdisplay, mode->crtc_hsync_start,
12128                 mode->crtc_hsync_end, mode->crtc_htotal,
12129                 mode->crtc_vdisplay, mode->crtc_vsync_start,
12130                 mode->crtc_vsync_end, mode->crtc_vtotal, mode->type, mode->flags);
12131 }
12132
12133 static void intel_dump_pipe_config(struct intel_crtc *crtc,
12134                                    struct intel_crtc_state *pipe_config,
12135                                    const char *context)
12136 {
12137         struct drm_device *dev = crtc->base.dev;
12138         struct drm_plane *plane;
12139         struct intel_plane *intel_plane;
12140         struct intel_plane_state *state;
12141         struct drm_framebuffer *fb;
12142
12143         DRM_DEBUG_KMS("[CRTC:%d]%s config %p for pipe %c\n", crtc->base.base.id,
12144                       context, pipe_config, pipe_name(crtc->pipe));
12145
12146         DRM_DEBUG_KMS("cpu_transcoder: %c\n", transcoder_name(pipe_config->cpu_transcoder));
12147         DRM_DEBUG_KMS("pipe bpp: %i, dithering: %i\n",
12148                       pipe_config->pipe_bpp, pipe_config->dither);
12149         DRM_DEBUG_KMS("fdi/pch: %i, lanes: %i, gmch_m: %u, gmch_n: %u, link_m: %u, link_n: %u, tu: %u\n",
12150                       pipe_config->has_pch_encoder,
12151                       pipe_config->fdi_lanes,
12152                       pipe_config->fdi_m_n.gmch_m, pipe_config->fdi_m_n.gmch_n,
12153                       pipe_config->fdi_m_n.link_m, pipe_config->fdi_m_n.link_n,
12154                       pipe_config->fdi_m_n.tu);
12155         DRM_DEBUG_KMS("dp: %i, lanes: %i, gmch_m: %u, gmch_n: %u, link_m: %u, link_n: %u, tu: %u\n",
12156                       pipe_config->has_dp_encoder,
12157                       pipe_config->lane_count,
12158                       pipe_config->dp_m_n.gmch_m, pipe_config->dp_m_n.gmch_n,
12159                       pipe_config->dp_m_n.link_m, pipe_config->dp_m_n.link_n,
12160                       pipe_config->dp_m_n.tu);
12161
12162         DRM_DEBUG_KMS("dp: %i, lanes: %i, gmch_m2: %u, gmch_n2: %u, link_m2: %u, link_n2: %u, tu2: %u\n",
12163                       pipe_config->has_dp_encoder,
12164                       pipe_config->lane_count,
12165                       pipe_config->dp_m2_n2.gmch_m,
12166                       pipe_config->dp_m2_n2.gmch_n,
12167                       pipe_config->dp_m2_n2.link_m,
12168                       pipe_config->dp_m2_n2.link_n,
12169                       pipe_config->dp_m2_n2.tu);
12170
12171         DRM_DEBUG_KMS("audio: %i, infoframes: %i\n",
12172                       pipe_config->has_audio,
12173                       pipe_config->has_infoframe);
12174
12175         DRM_DEBUG_KMS("requested mode:\n");
12176         drm_mode_debug_printmodeline(&pipe_config->base.mode);
12177         DRM_DEBUG_KMS("adjusted mode:\n");
12178         drm_mode_debug_printmodeline(&pipe_config->base.adjusted_mode);
12179         intel_dump_crtc_timings(&pipe_config->base.adjusted_mode);
12180         DRM_DEBUG_KMS("port clock: %d\n", pipe_config->port_clock);
12181         DRM_DEBUG_KMS("pipe src size: %dx%d\n",
12182                       pipe_config->pipe_src_w, pipe_config->pipe_src_h);
12183         DRM_DEBUG_KMS("num_scalers: %d, scaler_users: 0x%x, scaler_id: %d\n",
12184                       crtc->num_scalers,
12185                       pipe_config->scaler_state.scaler_users,
12186                       pipe_config->scaler_state.scaler_id);
12187         DRM_DEBUG_KMS("gmch pfit: control: 0x%08x, ratios: 0x%08x, lvds border: 0x%08x\n",
12188                       pipe_config->gmch_pfit.control,
12189                       pipe_config->gmch_pfit.pgm_ratios,
12190                       pipe_config->gmch_pfit.lvds_border_bits);
12191         DRM_DEBUG_KMS("pch pfit: pos: 0x%08x, size: 0x%08x, %s\n",
12192                       pipe_config->pch_pfit.pos,
12193                       pipe_config->pch_pfit.size,
12194                       pipe_config->pch_pfit.enabled ? "enabled" : "disabled");
12195         DRM_DEBUG_KMS("ips: %i\n", pipe_config->ips_enabled);
12196         DRM_DEBUG_KMS("double wide: %i\n", pipe_config->double_wide);
12197
12198         if (IS_BROXTON(dev)) {
12199                 DRM_DEBUG_KMS("ddi_pll_sel: %u; dpll_hw_state: ebb0: 0x%x, ebb4: 0x%x,"
12200                               "pll0: 0x%x, pll1: 0x%x, pll2: 0x%x, pll3: 0x%x, "
12201                               "pll6: 0x%x, pll8: 0x%x, pll9: 0x%x, pll10: 0x%x, pcsdw12: 0x%x\n",
12202                               pipe_config->ddi_pll_sel,
12203                               pipe_config->dpll_hw_state.ebb0,
12204                               pipe_config->dpll_hw_state.ebb4,
12205                               pipe_config->dpll_hw_state.pll0,
12206                               pipe_config->dpll_hw_state.pll1,
12207                               pipe_config->dpll_hw_state.pll2,
12208                               pipe_config->dpll_hw_state.pll3,
12209                               pipe_config->dpll_hw_state.pll6,
12210                               pipe_config->dpll_hw_state.pll8,
12211                               pipe_config->dpll_hw_state.pll9,
12212                               pipe_config->dpll_hw_state.pll10,
12213                               pipe_config->dpll_hw_state.pcsdw12);
12214         } else if (IS_SKYLAKE(dev) || IS_KABYLAKE(dev)) {
12215                 DRM_DEBUG_KMS("ddi_pll_sel: %u; dpll_hw_state: "
12216                               "ctrl1: 0x%x, cfgcr1: 0x%x, cfgcr2: 0x%x\n",
12217                               pipe_config->ddi_pll_sel,
12218                               pipe_config->dpll_hw_state.ctrl1,
12219                               pipe_config->dpll_hw_state.cfgcr1,
12220                               pipe_config->dpll_hw_state.cfgcr2);
12221         } else if (HAS_DDI(dev)) {
12222                 DRM_DEBUG_KMS("ddi_pll_sel: %u; dpll_hw_state: wrpll: 0x%x spll: 0x%x\n",
12223                               pipe_config->ddi_pll_sel,
12224                               pipe_config->dpll_hw_state.wrpll,
12225                               pipe_config->dpll_hw_state.spll);
12226         } else {
12227                 DRM_DEBUG_KMS("dpll_hw_state: dpll: 0x%x, dpll_md: 0x%x, "
12228                               "fp0: 0x%x, fp1: 0x%x\n",
12229                               pipe_config->dpll_hw_state.dpll,
12230                               pipe_config->dpll_hw_state.dpll_md,
12231                               pipe_config->dpll_hw_state.fp0,
12232                               pipe_config->dpll_hw_state.fp1);
12233         }
12234
12235         DRM_DEBUG_KMS("planes on this crtc\n");
12236         list_for_each_entry(plane, &dev->mode_config.plane_list, head) {
12237                 intel_plane = to_intel_plane(plane);
12238                 if (intel_plane->pipe != crtc->pipe)
12239                         continue;
12240
12241                 state = to_intel_plane_state(plane->state);
12242                 fb = state->base.fb;
12243                 if (!fb) {
12244                         DRM_DEBUG_KMS("%s PLANE:%d plane: %u.%u idx: %d "
12245                                 "disabled, scaler_id = %d\n",
12246                                 plane->type == DRM_PLANE_TYPE_CURSOR ? "CURSOR" : "STANDARD",
12247                                 plane->base.id, intel_plane->pipe,
12248                                 (crtc->base.primary == plane) ? 0 : intel_plane->plane + 1,
12249                                 drm_plane_index(plane), state->scaler_id);
12250                         continue;
12251                 }
12252
12253                 DRM_DEBUG_KMS("%s PLANE:%d plane: %u.%u idx: %d enabled",
12254                         plane->type == DRM_PLANE_TYPE_CURSOR ? "CURSOR" : "STANDARD",
12255                         plane->base.id, intel_plane->pipe,
12256                         crtc->base.primary == plane ? 0 : intel_plane->plane + 1,
12257                         drm_plane_index(plane));
12258                 DRM_DEBUG_KMS("\tFB:%d, fb = %ux%u format = 0x%x",
12259                         fb->base.id, fb->width, fb->height, fb->pixel_format);
12260                 DRM_DEBUG_KMS("\tscaler:%d src (%u, %u) %ux%u dst (%u, %u) %ux%u\n",
12261                         state->scaler_id,
12262                         state->src.x1 >> 16, state->src.y1 >> 16,
12263                         drm_rect_width(&state->src) >> 16,
12264                         drm_rect_height(&state->src) >> 16,
12265                         state->dst.x1, state->dst.y1,
12266                         drm_rect_width(&state->dst), drm_rect_height(&state->dst));
12267         }
12268 }
12269
12270 static bool check_digital_port_conflicts(struct drm_atomic_state *state)
12271 {
12272         struct drm_device *dev = state->dev;
12273         struct intel_encoder *encoder;
12274         struct drm_connector *connector;
12275         struct drm_connector_state *connector_state;
12276         unsigned int used_ports = 0;
12277         int i;
12278
12279         /*
12280          * Walk the connector list instead of the encoder
12281          * list to detect the problem on ddi platforms
12282          * where there's just one encoder per digital port.
12283          */
12284         for_each_connector_in_state(state, connector, connector_state, i) {
12285                 if (!connector_state->best_encoder)
12286                         continue;
12287
12288                 encoder = to_intel_encoder(connector_state->best_encoder);
12289
12290                 WARN_ON(!connector_state->crtc);
12291
12292                 switch (encoder->type) {
12293                         unsigned int port_mask;
12294                 case INTEL_OUTPUT_UNKNOWN:
12295                         if (WARN_ON(!HAS_DDI(dev)))
12296                                 break;
12297                 case INTEL_OUTPUT_DISPLAYPORT:
12298                 case INTEL_OUTPUT_HDMI:
12299                 case INTEL_OUTPUT_EDP:
12300                         port_mask = 1 << enc_to_dig_port(&encoder->base)->port;
12301
12302                         /* the same port mustn't appear more than once */
12303                         if (used_ports & port_mask)
12304                                 return false;
12305
12306                         used_ports |= port_mask;
12307                 default:
12308                         break;
12309                 }
12310         }
12311
12312         return true;
12313 }
12314
12315 static void
12316 clear_intel_crtc_state(struct intel_crtc_state *crtc_state)
12317 {
12318         struct drm_crtc_state tmp_state;
12319         struct intel_crtc_scaler_state scaler_state;
12320         struct intel_dpll_hw_state dpll_hw_state;
12321         enum intel_dpll_id shared_dpll;
12322         uint32_t ddi_pll_sel;
12323         bool force_thru;
12324
12325         /* FIXME: before the switch to atomic started, a new pipe_config was
12326          * kzalloc'd. Code that depends on any field being zero should be
12327          * fixed, so that the crtc_state can be safely duplicated. For now,
12328          * only fields that are know to not cause problems are preserved. */
12329
12330         tmp_state = crtc_state->base;
12331         scaler_state = crtc_state->scaler_state;
12332         shared_dpll = crtc_state->shared_dpll;
12333         dpll_hw_state = crtc_state->dpll_hw_state;
12334         ddi_pll_sel = crtc_state->ddi_pll_sel;
12335         force_thru = crtc_state->pch_pfit.force_thru;
12336
12337         memset(crtc_state, 0, sizeof *crtc_state);
12338
12339         crtc_state->base = tmp_state;
12340         crtc_state->scaler_state = scaler_state;
12341         crtc_state->shared_dpll = shared_dpll;
12342         crtc_state->dpll_hw_state = dpll_hw_state;
12343         crtc_state->ddi_pll_sel = ddi_pll_sel;
12344         crtc_state->pch_pfit.force_thru = force_thru;
12345 }
12346
12347 static int
12348 intel_modeset_pipe_config(struct drm_crtc *crtc,
12349                           struct intel_crtc_state *pipe_config)
12350 {
12351         struct drm_atomic_state *state = pipe_config->base.state;
12352         struct intel_encoder *encoder;
12353         struct drm_connector *connector;
12354         struct drm_connector_state *connector_state;
12355         int base_bpp, ret = -EINVAL;
12356         int i;
12357         bool retry = true;
12358
12359         clear_intel_crtc_state(pipe_config);
12360
12361         pipe_config->cpu_transcoder =
12362                 (enum transcoder) to_intel_crtc(crtc)->pipe;
12363
12364         /*
12365          * Sanitize sync polarity flags based on requested ones. If neither
12366          * positive or negative polarity is requested, treat this as meaning
12367          * negative polarity.
12368          */
12369         if (!(pipe_config->base.adjusted_mode.flags &
12370               (DRM_MODE_FLAG_PHSYNC | DRM_MODE_FLAG_NHSYNC)))
12371                 pipe_config->base.adjusted_mode.flags |= DRM_MODE_FLAG_NHSYNC;
12372
12373         if (!(pipe_config->base.adjusted_mode.flags &
12374               (DRM_MODE_FLAG_PVSYNC | DRM_MODE_FLAG_NVSYNC)))
12375                 pipe_config->base.adjusted_mode.flags |= DRM_MODE_FLAG_NVSYNC;
12376
12377         base_bpp = compute_baseline_pipe_bpp(to_intel_crtc(crtc),
12378                                              pipe_config);
12379         if (base_bpp < 0)
12380                 goto fail;
12381
12382         /*
12383          * Determine the real pipe dimensions. Note that stereo modes can
12384          * increase the actual pipe size due to the frame doubling and
12385          * insertion of additional space for blanks between the frame. This
12386          * is stored in the crtc timings. We use the requested mode to do this
12387          * computation to clearly distinguish it from the adjusted mode, which
12388          * can be changed by the connectors in the below retry loop.
12389          */
12390         drm_crtc_get_hv_timing(&pipe_config->base.mode,
12391                                &pipe_config->pipe_src_w,
12392                                &pipe_config->pipe_src_h);
12393
12394 encoder_retry:
12395         /* Ensure the port clock defaults are reset when retrying. */
12396         pipe_config->port_clock = 0;
12397         pipe_config->pixel_multiplier = 1;
12398
12399         /* Fill in default crtc timings, allow encoders to overwrite them. */
12400         drm_mode_set_crtcinfo(&pipe_config->base.adjusted_mode,
12401                               CRTC_STEREO_DOUBLE);
12402
12403         /* Pass our mode to the connectors and the CRTC to give them a chance to
12404          * adjust it according to limitations or connector properties, and also
12405          * a chance to reject the mode entirely.
12406          */
12407         for_each_connector_in_state(state, connector, connector_state, i) {
12408                 if (connector_state->crtc != crtc)
12409                         continue;
12410
12411                 encoder = to_intel_encoder(connector_state->best_encoder);
12412
12413                 if (!(encoder->compute_config(encoder, pipe_config))) {
12414                         DRM_DEBUG_KMS("Encoder config failure\n");
12415                         goto fail;
12416                 }
12417         }
12418
12419         /* Set default port clock if not overwritten by the encoder. Needs to be
12420          * done afterwards in case the encoder adjusts the mode. */
12421         if (!pipe_config->port_clock)
12422                 pipe_config->port_clock = pipe_config->base.adjusted_mode.crtc_clock
12423                         * pipe_config->pixel_multiplier;
12424
12425         ret = intel_crtc_compute_config(to_intel_crtc(crtc), pipe_config);
12426         if (ret < 0) {
12427                 DRM_DEBUG_KMS("CRTC fixup failed\n");
12428                 goto fail;
12429         }
12430
12431         if (ret == RETRY) {
12432                 if (WARN(!retry, "loop in pipe configuration computation\n")) {
12433                         ret = -EINVAL;
12434                         goto fail;
12435                 }
12436
12437                 DRM_DEBUG_KMS("CRTC bw constrained, retrying\n");
12438                 retry = false;
12439                 goto encoder_retry;
12440         }
12441
12442         /* Dithering seems to not pass-through bits correctly when it should, so
12443          * only enable it on 6bpc panels. */
12444         pipe_config->dither = pipe_config->pipe_bpp == 6*3;
12445         DRM_DEBUG_KMS("hw max bpp: %i, pipe bpp: %i, dithering: %i\n",
12446                       base_bpp, pipe_config->pipe_bpp, pipe_config->dither);
12447
12448 fail:
12449         return ret;
12450 }
12451
12452 static void
12453 intel_modeset_update_crtc_state(struct drm_atomic_state *state)
12454 {
12455         struct drm_crtc *crtc;
12456         struct drm_crtc_state *crtc_state;
12457         int i;
12458
12459         /* Double check state. */
12460         for_each_crtc_in_state(state, crtc, crtc_state, i) {
12461                 to_intel_crtc(crtc)->config = to_intel_crtc_state(crtc->state);
12462
12463                 /* Update hwmode for vblank functions */
12464                 if (crtc->state->active)
12465                         crtc->hwmode = crtc->state->adjusted_mode;
12466                 else
12467                         crtc->hwmode.crtc_clock = 0;
12468
12469                 /*
12470                  * Update legacy state to satisfy fbc code. This can
12471                  * be removed when fbc uses the atomic state.
12472                  */
12473                 if (drm_atomic_get_existing_plane_state(state, crtc->primary)) {
12474                         struct drm_plane_state *plane_state = crtc->primary->state;
12475
12476                         crtc->primary->fb = plane_state->fb;
12477                         crtc->x = plane_state->src_x >> 16;
12478                         crtc->y = plane_state->src_y >> 16;
12479                 }
12480         }
12481 }
12482
12483 static bool intel_fuzzy_clock_check(int clock1, int clock2)
12484 {
12485         int diff;
12486
12487         if (clock1 == clock2)
12488                 return true;
12489
12490         if (!clock1 || !clock2)
12491                 return false;
12492
12493         diff = abs(clock1 - clock2);
12494
12495         if (((((diff + clock1 + clock2) * 100)) / (clock1 + clock2)) < 105)
12496                 return true;
12497
12498         return false;
12499 }
12500
12501 #define for_each_intel_crtc_masked(dev, mask, intel_crtc) \
12502         list_for_each_entry((intel_crtc), \
12503                             &(dev)->mode_config.crtc_list, \
12504                             base.head) \
12505                 for_each_if (mask & (1 <<(intel_crtc)->pipe))
12506
12507 static bool
12508 intel_compare_m_n(unsigned int m, unsigned int n,
12509                   unsigned int m2, unsigned int n2,
12510                   bool exact)
12511 {
12512         if (m == m2 && n == n2)
12513                 return true;
12514
12515         if (exact || !m || !n || !m2 || !n2)
12516                 return false;
12517
12518         BUILD_BUG_ON(DATA_LINK_M_N_MASK > INT_MAX);
12519
12520         if (m > m2) {
12521                 while (m > m2) {
12522                         m2 <<= 1;
12523                         n2 <<= 1;
12524                 }
12525         } else if (m < m2) {
12526                 while (m < m2) {
12527                         m <<= 1;
12528                         n <<= 1;
12529                 }
12530         }
12531
12532         return m == m2 && n == n2;
12533 }
12534
12535 static bool
12536 intel_compare_link_m_n(const struct intel_link_m_n *m_n,
12537                        struct intel_link_m_n *m2_n2,
12538                        bool adjust)
12539 {
12540         if (m_n->tu == m2_n2->tu &&
12541             intel_compare_m_n(m_n->gmch_m, m_n->gmch_n,
12542                               m2_n2->gmch_m, m2_n2->gmch_n, !adjust) &&
12543             intel_compare_m_n(m_n->link_m, m_n->link_n,
12544                               m2_n2->link_m, m2_n2->link_n, !adjust)) {
12545                 if (adjust)
12546                         *m2_n2 = *m_n;
12547
12548                 return true;
12549         }
12550
12551         return false;
12552 }
12553
12554 static bool
12555 intel_pipe_config_compare(struct drm_device *dev,
12556                           struct intel_crtc_state *current_config,
12557                           struct intel_crtc_state *pipe_config,
12558                           bool adjust)
12559 {
12560         bool ret = true;
12561
12562 #define INTEL_ERR_OR_DBG_KMS(fmt, ...) \
12563         do { \
12564                 if (!adjust) \
12565                         DRM_ERROR(fmt, ##__VA_ARGS__); \
12566                 else \
12567                         DRM_DEBUG_KMS(fmt, ##__VA_ARGS__); \
12568         } while (0)
12569
12570 #define PIPE_CONF_CHECK_X(name) \
12571         if (current_config->name != pipe_config->name) { \
12572                 INTEL_ERR_OR_DBG_KMS("mismatch in " #name " " \
12573                           "(expected 0x%08x, found 0x%08x)\n", \
12574                           current_config->name, \
12575                           pipe_config->name); \
12576                 ret = false; \
12577         }
12578
12579 #define PIPE_CONF_CHECK_I(name) \
12580         if (current_config->name != pipe_config->name) { \
12581                 INTEL_ERR_OR_DBG_KMS("mismatch in " #name " " \
12582                           "(expected %i, found %i)\n", \
12583                           current_config->name, \
12584                           pipe_config->name); \
12585                 ret = false; \
12586         }
12587
12588 #define PIPE_CONF_CHECK_M_N(name) \
12589         if (!intel_compare_link_m_n(&current_config->name, \
12590                                     &pipe_config->name,\
12591                                     adjust)) { \
12592                 INTEL_ERR_OR_DBG_KMS("mismatch in " #name " " \
12593                           "(expected tu %i gmch %i/%i link %i/%i, " \
12594                           "found tu %i, gmch %i/%i link %i/%i)\n", \
12595                           current_config->name.tu, \
12596                           current_config->name.gmch_m, \
12597                           current_config->name.gmch_n, \
12598                           current_config->name.link_m, \
12599                           current_config->name.link_n, \
12600                           pipe_config->name.tu, \
12601                           pipe_config->name.gmch_m, \
12602                           pipe_config->name.gmch_n, \
12603                           pipe_config->name.link_m, \
12604                           pipe_config->name.link_n); \
12605                 ret = false; \
12606         }
12607
12608 #define PIPE_CONF_CHECK_M_N_ALT(name, alt_name) \
12609         if (!intel_compare_link_m_n(&current_config->name, \
12610                                     &pipe_config->name, adjust) && \
12611             !intel_compare_link_m_n(&current_config->alt_name, \
12612                                     &pipe_config->name, adjust)) { \
12613                 INTEL_ERR_OR_DBG_KMS("mismatch in " #name " " \
12614                           "(expected tu %i gmch %i/%i link %i/%i, " \
12615                           "or tu %i gmch %i/%i link %i/%i, " \
12616                           "found tu %i, gmch %i/%i link %i/%i)\n", \
12617                           current_config->name.tu, \
12618                           current_config->name.gmch_m, \
12619                           current_config->name.gmch_n, \
12620                           current_config->name.link_m, \
12621                           current_config->name.link_n, \
12622                           current_config->alt_name.tu, \
12623                           current_config->alt_name.gmch_m, \
12624                           current_config->alt_name.gmch_n, \
12625                           current_config->alt_name.link_m, \
12626                           current_config->alt_name.link_n, \
12627                           pipe_config->name.tu, \
12628                           pipe_config->name.gmch_m, \
12629                           pipe_config->name.gmch_n, \
12630                           pipe_config->name.link_m, \
12631                           pipe_config->name.link_n); \
12632                 ret = false; \
12633         }
12634
12635 /* This is required for BDW+ where there is only one set of registers for
12636  * switching between high and low RR.
12637  * This macro can be used whenever a comparison has to be made between one
12638  * hw state and multiple sw state variables.
12639  */
12640 #define PIPE_CONF_CHECK_I_ALT(name, alt_name) \
12641         if ((current_config->name != pipe_config->name) && \
12642                 (current_config->alt_name != pipe_config->name)) { \
12643                         INTEL_ERR_OR_DBG_KMS("mismatch in " #name " " \
12644                                   "(expected %i or %i, found %i)\n", \
12645                                   current_config->name, \
12646                                   current_config->alt_name, \
12647                                   pipe_config->name); \
12648                         ret = false; \
12649         }
12650
12651 #define PIPE_CONF_CHECK_FLAGS(name, mask)       \
12652         if ((current_config->name ^ pipe_config->name) & (mask)) { \
12653                 INTEL_ERR_OR_DBG_KMS("mismatch in " #name "(" #mask ") " \
12654                           "(expected %i, found %i)\n", \
12655                           current_config->name & (mask), \
12656                           pipe_config->name & (mask)); \
12657                 ret = false; \
12658         }
12659
12660 #define PIPE_CONF_CHECK_CLOCK_FUZZY(name) \
12661         if (!intel_fuzzy_clock_check(current_config->name, pipe_config->name)) { \
12662                 INTEL_ERR_OR_DBG_KMS("mismatch in " #name " " \
12663                           "(expected %i, found %i)\n", \
12664                           current_config->name, \
12665                           pipe_config->name); \
12666                 ret = false; \
12667         }
12668
12669 #define PIPE_CONF_QUIRK(quirk)  \
12670         ((current_config->quirks | pipe_config->quirks) & (quirk))
12671
12672         PIPE_CONF_CHECK_I(cpu_transcoder);
12673
12674         PIPE_CONF_CHECK_I(has_pch_encoder);
12675         PIPE_CONF_CHECK_I(fdi_lanes);
12676         PIPE_CONF_CHECK_M_N(fdi_m_n);
12677
12678         PIPE_CONF_CHECK_I(has_dp_encoder);
12679         PIPE_CONF_CHECK_I(lane_count);
12680
12681         if (INTEL_INFO(dev)->gen < 8) {
12682                 PIPE_CONF_CHECK_M_N(dp_m_n);
12683
12684                 if (current_config->has_drrs)
12685                         PIPE_CONF_CHECK_M_N(dp_m2_n2);
12686         } else
12687                 PIPE_CONF_CHECK_M_N_ALT(dp_m_n, dp_m2_n2);
12688
12689         PIPE_CONF_CHECK_I(has_dsi_encoder);
12690
12691         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hdisplay);
12692         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_htotal);
12693         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hblank_start);
12694         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hblank_end);
12695         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hsync_start);
12696         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hsync_end);
12697
12698         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vdisplay);
12699         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vtotal);
12700         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vblank_start);
12701         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vblank_end);
12702         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vsync_start);
12703         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vsync_end);
12704
12705         PIPE_CONF_CHECK_I(pixel_multiplier);
12706         PIPE_CONF_CHECK_I(has_hdmi_sink);
12707         if ((INTEL_INFO(dev)->gen < 8 && !IS_HASWELL(dev)) ||
12708             IS_VALLEYVIEW(dev) || IS_CHERRYVIEW(dev))
12709                 PIPE_CONF_CHECK_I(limited_color_range);
12710         PIPE_CONF_CHECK_I(has_infoframe);
12711
12712         PIPE_CONF_CHECK_I(has_audio);
12713
12714         PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
12715                               DRM_MODE_FLAG_INTERLACE);
12716
12717         if (!PIPE_CONF_QUIRK(PIPE_CONFIG_QUIRK_MODE_SYNC_FLAGS)) {
12718                 PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
12719                                       DRM_MODE_FLAG_PHSYNC);
12720                 PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
12721                                       DRM_MODE_FLAG_NHSYNC);
12722                 PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
12723                                       DRM_MODE_FLAG_PVSYNC);
12724                 PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
12725                                       DRM_MODE_FLAG_NVSYNC);
12726         }
12727
12728         PIPE_CONF_CHECK_X(gmch_pfit.control);
12729         /* pfit ratios are autocomputed by the hw on gen4+ */
12730         if (INTEL_INFO(dev)->gen < 4)
12731                 PIPE_CONF_CHECK_I(gmch_pfit.pgm_ratios);
12732         PIPE_CONF_CHECK_X(gmch_pfit.lvds_border_bits);
12733
12734         if (!adjust) {
12735                 PIPE_CONF_CHECK_I(pipe_src_w);
12736                 PIPE_CONF_CHECK_I(pipe_src_h);
12737
12738                 PIPE_CONF_CHECK_I(pch_pfit.enabled);
12739                 if (current_config->pch_pfit.enabled) {
12740                         PIPE_CONF_CHECK_X(pch_pfit.pos);
12741                         PIPE_CONF_CHECK_X(pch_pfit.size);
12742                 }
12743
12744                 PIPE_CONF_CHECK_I(scaler_state.scaler_id);
12745         }
12746
12747         /* BDW+ don't expose a synchronous way to read the state */
12748         if (IS_HASWELL(dev))
12749                 PIPE_CONF_CHECK_I(ips_enabled);
12750
12751         PIPE_CONF_CHECK_I(double_wide);
12752
12753         PIPE_CONF_CHECK_X(ddi_pll_sel);
12754
12755         PIPE_CONF_CHECK_I(shared_dpll);
12756         PIPE_CONF_CHECK_X(dpll_hw_state.dpll);
12757         PIPE_CONF_CHECK_X(dpll_hw_state.dpll_md);
12758         PIPE_CONF_CHECK_X(dpll_hw_state.fp0);
12759         PIPE_CONF_CHECK_X(dpll_hw_state.fp1);
12760         PIPE_CONF_CHECK_X(dpll_hw_state.wrpll);
12761         PIPE_CONF_CHECK_X(dpll_hw_state.spll);
12762         PIPE_CONF_CHECK_X(dpll_hw_state.ctrl1);
12763         PIPE_CONF_CHECK_X(dpll_hw_state.cfgcr1);
12764         PIPE_CONF_CHECK_X(dpll_hw_state.cfgcr2);
12765
12766         if (IS_G4X(dev) || INTEL_INFO(dev)->gen >= 5)
12767                 PIPE_CONF_CHECK_I(pipe_bpp);
12768
12769         PIPE_CONF_CHECK_CLOCK_FUZZY(base.adjusted_mode.crtc_clock);
12770         PIPE_CONF_CHECK_CLOCK_FUZZY(port_clock);
12771
12772 #undef PIPE_CONF_CHECK_X
12773 #undef PIPE_CONF_CHECK_I
12774 #undef PIPE_CONF_CHECK_I_ALT
12775 #undef PIPE_CONF_CHECK_FLAGS
12776 #undef PIPE_CONF_CHECK_CLOCK_FUZZY
12777 #undef PIPE_CONF_QUIRK
12778 #undef INTEL_ERR_OR_DBG_KMS
12779
12780         return ret;
12781 }
12782
12783 static void check_wm_state(struct drm_device *dev)
12784 {
12785         struct drm_i915_private *dev_priv = dev->dev_private;
12786         struct skl_ddb_allocation hw_ddb, *sw_ddb;
12787         struct intel_crtc *intel_crtc;
12788         int plane;
12789
12790         if (INTEL_INFO(dev)->gen < 9)
12791                 return;
12792
12793         skl_ddb_get_hw_state(dev_priv, &hw_ddb);
12794         sw_ddb = &dev_priv->wm.skl_hw.ddb;
12795
12796         for_each_intel_crtc(dev, intel_crtc) {
12797                 struct skl_ddb_entry *hw_entry, *sw_entry;
12798                 const enum pipe pipe = intel_crtc->pipe;
12799
12800                 if (!intel_crtc->active)
12801                         continue;
12802
12803                 /* planes */
12804                 for_each_plane(dev_priv, pipe, plane) {
12805                         hw_entry = &hw_ddb.plane[pipe][plane];
12806                         sw_entry = &sw_ddb->plane[pipe][plane];
12807
12808                         if (skl_ddb_entry_equal(hw_entry, sw_entry))
12809                                 continue;
12810
12811                         DRM_ERROR("mismatch in DDB state pipe %c plane %d "
12812                                   "(expected (%u,%u), found (%u,%u))\n",
12813                                   pipe_name(pipe), plane + 1,
12814                                   sw_entry->start, sw_entry->end,
12815                                   hw_entry->start, hw_entry->end);
12816                 }
12817
12818                 /* cursor */
12819                 hw_entry = &hw_ddb.plane[pipe][PLANE_CURSOR];
12820                 sw_entry = &sw_ddb->plane[pipe][PLANE_CURSOR];
12821
12822                 if (skl_ddb_entry_equal(hw_entry, sw_entry))
12823                         continue;
12824
12825                 DRM_ERROR("mismatch in DDB state pipe %c cursor "
12826                           "(expected (%u,%u), found (%u,%u))\n",
12827                           pipe_name(pipe),
12828                           sw_entry->start, sw_entry->end,
12829                           hw_entry->start, hw_entry->end);
12830         }
12831 }
12832
12833 static void
12834 check_connector_state(struct drm_device *dev,
12835                       struct drm_atomic_state *old_state)
12836 {
12837         struct drm_connector_state *old_conn_state;
12838         struct drm_connector *connector;
12839         int i;
12840
12841         for_each_connector_in_state(old_state, connector, old_conn_state, i) {
12842                 struct drm_encoder *encoder = connector->encoder;
12843                 struct drm_connector_state *state = connector->state;
12844
12845                 /* This also checks the encoder/connector hw state with the
12846                  * ->get_hw_state callbacks. */
12847                 intel_connector_check_state(to_intel_connector(connector));
12848
12849                 I915_STATE_WARN(state->best_encoder != encoder,
12850                      "connector's atomic encoder doesn't match legacy encoder\n");
12851         }
12852 }
12853
12854 static void
12855 check_encoder_state(struct drm_device *dev)
12856 {
12857         struct intel_encoder *encoder;
12858         struct intel_connector *connector;
12859
12860         for_each_intel_encoder(dev, encoder) {
12861                 bool enabled = false;
12862                 enum pipe pipe;
12863
12864                 DRM_DEBUG_KMS("[ENCODER:%d:%s]\n",
12865                               encoder->base.base.id,
12866                               encoder->base.name);
12867
12868                 for_each_intel_connector(dev, connector) {
12869                         if (connector->base.state->best_encoder != &encoder->base)
12870                                 continue;
12871                         enabled = true;
12872
12873                         I915_STATE_WARN(connector->base.state->crtc !=
12874                                         encoder->base.crtc,
12875                              "connector's crtc doesn't match encoder crtc\n");
12876                 }
12877
12878                 I915_STATE_WARN(!!encoder->base.crtc != enabled,
12879                      "encoder's enabled state mismatch "
12880                      "(expected %i, found %i)\n",
12881                      !!encoder->base.crtc, enabled);
12882
12883                 if (!encoder->base.crtc) {
12884                         bool active;
12885
12886                         active = encoder->get_hw_state(encoder, &pipe);
12887                         I915_STATE_WARN(active,
12888                              "encoder detached but still enabled on pipe %c.\n",
12889                              pipe_name(pipe));
12890                 }
12891         }
12892 }
12893
12894 static void
12895 check_crtc_state(struct drm_device *dev, struct drm_atomic_state *old_state)
12896 {
12897         struct drm_i915_private *dev_priv = dev->dev_private;
12898         struct intel_encoder *encoder;
12899         struct drm_crtc_state *old_crtc_state;
12900         struct drm_crtc *crtc;
12901         int i;
12902
12903         for_each_crtc_in_state(old_state, crtc, old_crtc_state, i) {
12904                 struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
12905                 struct intel_crtc_state *pipe_config, *sw_config;
12906                 bool active;
12907
12908                 if (!needs_modeset(crtc->state) &&
12909                     !to_intel_crtc_state(crtc->state)->update_pipe)
12910                         continue;
12911
12912                 __drm_atomic_helper_crtc_destroy_state(crtc, old_crtc_state);
12913                 pipe_config = to_intel_crtc_state(old_crtc_state);
12914                 memset(pipe_config, 0, sizeof(*pipe_config));
12915                 pipe_config->base.crtc = crtc;
12916                 pipe_config->base.state = old_state;
12917
12918                 DRM_DEBUG_KMS("[CRTC:%d]\n",
12919                               crtc->base.id);
12920
12921                 active = dev_priv->display.get_pipe_config(intel_crtc,
12922                                                            pipe_config);
12923
12924                 /* hw state is inconsistent with the pipe quirk */
12925                 if ((intel_crtc->pipe == PIPE_A && dev_priv->quirks & QUIRK_PIPEA_FORCE) ||
12926                     (intel_crtc->pipe == PIPE_B && dev_priv->quirks & QUIRK_PIPEB_FORCE))
12927                         active = crtc->state->active;
12928
12929                 I915_STATE_WARN(crtc->state->active != active,
12930                      "crtc active state doesn't match with hw state "
12931                      "(expected %i, found %i)\n", crtc->state->active, active);
12932
12933                 I915_STATE_WARN(intel_crtc->active != crtc->state->active,
12934                      "transitional active state does not match atomic hw state "
12935                      "(expected %i, found %i)\n", crtc->state->active, intel_crtc->active);
12936
12937                 for_each_encoder_on_crtc(dev, crtc, encoder) {
12938                         enum pipe pipe;
12939
12940                         active = encoder->get_hw_state(encoder, &pipe);
12941                         I915_STATE_WARN(active != crtc->state->active,
12942                                 "[ENCODER:%i] active %i with crtc active %i\n",
12943                                 encoder->base.base.id, active, crtc->state->active);
12944
12945                         I915_STATE_WARN(active && intel_crtc->pipe != pipe,
12946                                         "Encoder connected to wrong pipe %c\n",
12947                                         pipe_name(pipe));
12948
12949                         if (active)
12950                                 encoder->get_config(encoder, pipe_config);
12951                 }
12952
12953                 if (!crtc->state->active)
12954                         continue;
12955
12956                 sw_config = to_intel_crtc_state(crtc->state);
12957                 if (!intel_pipe_config_compare(dev, sw_config,
12958                                                pipe_config, false)) {
12959                         I915_STATE_WARN(1, "pipe state doesn't match!\n");
12960                         intel_dump_pipe_config(intel_crtc, pipe_config,
12961                                                "[hw state]");
12962                         intel_dump_pipe_config(intel_crtc, sw_config,
12963                                                "[sw state]");
12964                 }
12965         }
12966 }
12967
12968 static void
12969 check_shared_dpll_state(struct drm_device *dev)
12970 {
12971         struct drm_i915_private *dev_priv = dev->dev_private;
12972         struct intel_crtc *crtc;
12973         struct intel_dpll_hw_state dpll_hw_state;
12974         int i;
12975
12976         for (i = 0; i < dev_priv->num_shared_dpll; i++) {
12977                 struct intel_shared_dpll *pll = &dev_priv->shared_dplls[i];
12978                 int enabled_crtcs = 0, active_crtcs = 0;
12979                 bool active;
12980
12981                 memset(&dpll_hw_state, 0, sizeof(dpll_hw_state));
12982
12983                 DRM_DEBUG_KMS("%s\n", pll->name);
12984
12985                 active = pll->get_hw_state(dev_priv, pll, &dpll_hw_state);
12986
12987                 I915_STATE_WARN(pll->active > hweight32(pll->config.crtc_mask),
12988                      "more active pll users than references: %i vs %i\n",
12989                      pll->active, hweight32(pll->config.crtc_mask));
12990                 I915_STATE_WARN(pll->active && !pll->on,
12991                      "pll in active use but not on in sw tracking\n");
12992                 I915_STATE_WARN(pll->on && !pll->active,
12993                      "pll in on but not on in use in sw tracking\n");
12994                 I915_STATE_WARN(pll->on != active,
12995                      "pll on state mismatch (expected %i, found %i)\n",
12996                      pll->on, active);
12997
12998                 for_each_intel_crtc(dev, crtc) {
12999                         if (crtc->base.state->enable && intel_crtc_to_shared_dpll(crtc) == pll)
13000                                 enabled_crtcs++;
13001                         if (crtc->active && intel_crtc_to_shared_dpll(crtc) == pll)
13002                                 active_crtcs++;
13003                 }
13004                 I915_STATE_WARN(pll->active != active_crtcs,
13005                      "pll active crtcs mismatch (expected %i, found %i)\n",
13006                      pll->active, active_crtcs);
13007                 I915_STATE_WARN(hweight32(pll->config.crtc_mask) != enabled_crtcs,
13008                      "pll enabled crtcs mismatch (expected %i, found %i)\n",
13009                      hweight32(pll->config.crtc_mask), enabled_crtcs);
13010
13011                 I915_STATE_WARN(pll->on && memcmp(&pll->config.hw_state, &dpll_hw_state,
13012                                        sizeof(dpll_hw_state)),
13013                      "pll hw state mismatch\n");
13014         }
13015 }
13016
13017 static void
13018 intel_modeset_check_state(struct drm_device *dev,
13019                           struct drm_atomic_state *old_state)
13020 {
13021         check_wm_state(dev);
13022         check_connector_state(dev, old_state);
13023         check_encoder_state(dev);
13024         check_crtc_state(dev, old_state);
13025         check_shared_dpll_state(dev);
13026 }
13027
13028 void ironlake_check_encoder_dotclock(const struct intel_crtc_state *pipe_config,
13029                                      int dotclock)
13030 {
13031         /*
13032          * FDI already provided one idea for the dotclock.
13033          * Yell if the encoder disagrees.
13034          */
13035         WARN(!intel_fuzzy_clock_check(pipe_config->base.adjusted_mode.crtc_clock, dotclock),
13036              "FDI dotclock and encoder dotclock mismatch, fdi: %i, encoder: %i\n",
13037              pipe_config->base.adjusted_mode.crtc_clock, dotclock);
13038 }
13039
13040 static void update_scanline_offset(struct intel_crtc *crtc)
13041 {
13042         struct drm_device *dev = crtc->base.dev;
13043
13044         /*
13045          * The scanline counter increments at the leading edge of hsync.
13046          *
13047          * On most platforms it starts counting from vtotal-1 on the
13048          * first active line. That means the scanline counter value is
13049          * always one less than what we would expect. Ie. just after
13050          * start of vblank, which also occurs at start of hsync (on the
13051          * last active line), the scanline counter will read vblank_start-1.
13052          *
13053          * On gen2 the scanline counter starts counting from 1 instead
13054          * of vtotal-1, so we have to subtract one (or rather add vtotal-1
13055          * to keep the value positive), instead of adding one.
13056          *
13057          * On HSW+ the behaviour of the scanline counter depends on the output
13058          * type. For DP ports it behaves like most other platforms, but on HDMI
13059          * there's an extra 1 line difference. So we need to add two instead of
13060          * one to the value.
13061          */
13062         if (IS_GEN2(dev)) {
13063                 const struct drm_display_mode *adjusted_mode = &crtc->config->base.adjusted_mode;
13064                 int vtotal;
13065
13066                 vtotal = adjusted_mode->crtc_vtotal;
13067                 if (adjusted_mode->flags & DRM_MODE_FLAG_INTERLACE)
13068                         vtotal /= 2;
13069
13070                 crtc->scanline_offset = vtotal - 1;
13071         } else if (HAS_DDI(dev) &&
13072                    intel_pipe_has_type(crtc, INTEL_OUTPUT_HDMI)) {
13073                 crtc->scanline_offset = 2;
13074         } else
13075                 crtc->scanline_offset = 1;
13076 }
13077
13078 static void intel_modeset_clear_plls(struct drm_atomic_state *state)
13079 {
13080         struct drm_device *dev = state->dev;
13081         struct drm_i915_private *dev_priv = to_i915(dev);
13082         struct intel_shared_dpll_config *shared_dpll = NULL;
13083         struct intel_crtc *intel_crtc;
13084         struct intel_crtc_state *intel_crtc_state;
13085         struct drm_crtc *crtc;
13086         struct drm_crtc_state *crtc_state;
13087         int i;
13088
13089         if (!dev_priv->display.crtc_compute_clock)
13090                 return;
13091
13092         for_each_crtc_in_state(state, crtc, crtc_state, i) {
13093                 int dpll;
13094
13095                 intel_crtc = to_intel_crtc(crtc);
13096                 intel_crtc_state = to_intel_crtc_state(crtc_state);
13097                 dpll = intel_crtc_state->shared_dpll;
13098
13099                 if (!needs_modeset(crtc_state) || dpll == DPLL_ID_PRIVATE)
13100                         continue;
13101
13102                 intel_crtc_state->shared_dpll = DPLL_ID_PRIVATE;
13103
13104                 if (!shared_dpll)
13105                         shared_dpll = intel_atomic_get_shared_dpll_state(state);
13106
13107                 shared_dpll[dpll].crtc_mask &= ~(1 << intel_crtc->pipe);
13108         }
13109 }
13110
13111 /*
13112  * This implements the workaround described in the "notes" section of the mode
13113  * set sequence documentation. When going from no pipes or single pipe to
13114  * multiple pipes, and planes are enabled after the pipe, we need to wait at
13115  * least 2 vblanks on the first pipe before enabling planes on the second pipe.
13116  */
13117 static int haswell_mode_set_planes_workaround(struct drm_atomic_state *state)
13118 {
13119         struct drm_crtc_state *crtc_state;
13120         struct intel_crtc *intel_crtc;
13121         struct drm_crtc *crtc;
13122         struct intel_crtc_state *first_crtc_state = NULL;
13123         struct intel_crtc_state *other_crtc_state = NULL;
13124         enum pipe first_pipe = INVALID_PIPE, enabled_pipe = INVALID_PIPE;
13125         int i;
13126
13127         /* look at all crtc's that are going to be enabled in during modeset */
13128         for_each_crtc_in_state(state, crtc, crtc_state, i) {
13129                 intel_crtc = to_intel_crtc(crtc);
13130
13131                 if (!crtc_state->active || !needs_modeset(crtc_state))
13132                         continue;
13133
13134                 if (first_crtc_state) {
13135                         other_crtc_state = to_intel_crtc_state(crtc_state);
13136                         break;
13137                 } else {
13138                         first_crtc_state = to_intel_crtc_state(crtc_state);
13139                         first_pipe = intel_crtc->pipe;
13140                 }
13141         }
13142
13143         /* No workaround needed? */
13144         if (!first_crtc_state)
13145                 return 0;
13146
13147         /* w/a possibly needed, check how many crtc's are already enabled. */
13148         for_each_intel_crtc(state->dev, intel_crtc) {
13149                 struct intel_crtc_state *pipe_config;
13150
13151                 pipe_config = intel_atomic_get_crtc_state(state, intel_crtc);
13152                 if (IS_ERR(pipe_config))
13153                         return PTR_ERR(pipe_config);
13154
13155                 pipe_config->hsw_workaround_pipe = INVALID_PIPE;
13156
13157                 if (!pipe_config->base.active ||
13158                     needs_modeset(&pipe_config->base))
13159                         continue;
13160
13161                 /* 2 or more enabled crtcs means no need for w/a */
13162                 if (enabled_pipe != INVALID_PIPE)
13163                         return 0;
13164
13165                 enabled_pipe = intel_crtc->pipe;
13166         }
13167
13168         if (enabled_pipe != INVALID_PIPE)
13169                 first_crtc_state->hsw_workaround_pipe = enabled_pipe;
13170         else if (other_crtc_state)
13171                 other_crtc_state->hsw_workaround_pipe = first_pipe;
13172
13173         return 0;
13174 }
13175
13176 static int intel_modeset_all_pipes(struct drm_atomic_state *state)
13177 {
13178         struct drm_crtc *crtc;
13179         struct drm_crtc_state *crtc_state;
13180         int ret = 0;
13181
13182         /* add all active pipes to the state */
13183         for_each_crtc(state->dev, crtc) {
13184                 crtc_state = drm_atomic_get_crtc_state(state, crtc);
13185                 if (IS_ERR(crtc_state))
13186                         return PTR_ERR(crtc_state);
13187
13188                 if (!crtc_state->active || needs_modeset(crtc_state))
13189                         continue;
13190
13191                 crtc_state->mode_changed = true;
13192
13193                 ret = drm_atomic_add_affected_connectors(state, crtc);
13194                 if (ret)
13195                         break;
13196
13197                 ret = drm_atomic_add_affected_planes(state, crtc);
13198                 if (ret)
13199                         break;
13200         }
13201
13202         return ret;
13203 }
13204
13205 static int intel_modeset_checks(struct drm_atomic_state *state)
13206 {
13207         struct drm_device *dev = state->dev;
13208         struct drm_i915_private *dev_priv = dev->dev_private;
13209         int ret;
13210
13211         if (!check_digital_port_conflicts(state)) {
13212                 DRM_DEBUG_KMS("rejecting conflicting digital port configuration\n");
13213                 return -EINVAL;
13214         }
13215
13216         /*
13217          * See if the config requires any additional preparation, e.g.
13218          * to adjust global state with pipes off.  We need to do this
13219          * here so we can get the modeset_pipe updated config for the new
13220          * mode set on this crtc.  For other crtcs we need to use the
13221          * adjusted_mode bits in the crtc directly.
13222          */
13223         if (dev_priv->display.modeset_calc_cdclk) {
13224                 unsigned int cdclk;
13225
13226                 ret = dev_priv->display.modeset_calc_cdclk(state);
13227
13228                 cdclk = to_intel_atomic_state(state)->cdclk;
13229                 if (!ret && cdclk != dev_priv->cdclk_freq)
13230                         ret = intel_modeset_all_pipes(state);
13231
13232                 if (ret < 0)
13233                         return ret;
13234         } else
13235                 to_intel_atomic_state(state)->cdclk = dev_priv->cdclk_freq;
13236
13237         intel_modeset_clear_plls(state);
13238
13239         if (IS_HASWELL(dev))
13240                 return haswell_mode_set_planes_workaround(state);
13241
13242         return 0;
13243 }
13244
13245 /*
13246  * Handle calculation of various watermark data at the end of the atomic check
13247  * phase.  The code here should be run after the per-crtc and per-plane 'check'
13248  * handlers to ensure that all derived state has been updated.
13249  */
13250 static void calc_watermark_data(struct drm_atomic_state *state)
13251 {
13252         struct drm_device *dev = state->dev;
13253         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
13254         struct drm_crtc *crtc;
13255         struct drm_crtc_state *cstate;
13256         struct drm_plane *plane;
13257         struct drm_plane_state *pstate;
13258
13259         /*
13260          * Calculate watermark configuration details now that derived
13261          * plane/crtc state is all properly updated.
13262          */
13263         drm_for_each_crtc(crtc, dev) {
13264                 cstate = drm_atomic_get_existing_crtc_state(state, crtc) ?:
13265                         crtc->state;
13266
13267                 if (cstate->active)
13268                         intel_state->wm_config.num_pipes_active++;
13269         }
13270         drm_for_each_legacy_plane(plane, dev) {
13271                 pstate = drm_atomic_get_existing_plane_state(state, plane) ?:
13272                         plane->state;
13273
13274                 if (!to_intel_plane_state(pstate)->visible)
13275                         continue;
13276
13277                 intel_state->wm_config.sprites_enabled = true;
13278                 if (pstate->crtc_w != pstate->src_w >> 16 ||
13279                     pstate->crtc_h != pstate->src_h >> 16)
13280                         intel_state->wm_config.sprites_scaled = true;
13281         }
13282 }
13283
13284 /**
13285  * intel_atomic_check - validate state object
13286  * @dev: drm device
13287  * @state: state to validate
13288  */
13289 static int intel_atomic_check(struct drm_device *dev,
13290                               struct drm_atomic_state *state)
13291 {
13292         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
13293         struct drm_crtc *crtc;
13294         struct drm_crtc_state *crtc_state;
13295         int ret, i;
13296         bool any_ms = false;
13297
13298         ret = drm_atomic_helper_check_modeset(dev, state);
13299         if (ret)
13300                 return ret;
13301
13302         for_each_crtc_in_state(state, crtc, crtc_state, i) {
13303                 struct intel_crtc_state *pipe_config =
13304                         to_intel_crtc_state(crtc_state);
13305
13306                 memset(&to_intel_crtc(crtc)->atomic, 0,
13307                        sizeof(struct intel_crtc_atomic_commit));
13308
13309                 /* Catch I915_MODE_FLAG_INHERITED */
13310                 if (crtc_state->mode.private_flags != crtc->state->mode.private_flags)
13311                         crtc_state->mode_changed = true;
13312
13313                 if (!crtc_state->enable) {
13314                         if (needs_modeset(crtc_state))
13315                                 any_ms = true;
13316                         continue;
13317                 }
13318
13319                 if (!needs_modeset(crtc_state))
13320                         continue;
13321
13322                 /* FIXME: For only active_changed we shouldn't need to do any
13323                  * state recomputation at all. */
13324
13325                 ret = drm_atomic_add_affected_connectors(state, crtc);
13326                 if (ret)
13327                         return ret;
13328
13329                 ret = intel_modeset_pipe_config(crtc, pipe_config);
13330                 if (ret)
13331                         return ret;
13332
13333                 if (i915.fastboot &&
13334                     intel_pipe_config_compare(state->dev,
13335                                         to_intel_crtc_state(crtc->state),
13336                                         pipe_config, true)) {
13337                         crtc_state->mode_changed = false;
13338                         to_intel_crtc_state(crtc_state)->update_pipe = true;
13339                 }
13340
13341                 if (needs_modeset(crtc_state)) {
13342                         any_ms = true;
13343
13344                         ret = drm_atomic_add_affected_planes(state, crtc);
13345                         if (ret)
13346                                 return ret;
13347                 }
13348
13349                 intel_dump_pipe_config(to_intel_crtc(crtc), pipe_config,
13350                                        needs_modeset(crtc_state) ?
13351                                        "[modeset]" : "[fastset]");
13352         }
13353
13354         if (any_ms) {
13355                 ret = intel_modeset_checks(state);
13356
13357                 if (ret)
13358                         return ret;
13359         } else
13360                 intel_state->cdclk = to_i915(state->dev)->cdclk_freq;
13361
13362         ret = drm_atomic_helper_check_planes(state->dev, state);
13363         if (ret)
13364                 return ret;
13365
13366         calc_watermark_data(state);
13367
13368         return 0;
13369 }
13370
13371 static int intel_atomic_prepare_commit(struct drm_device *dev,
13372                                        struct drm_atomic_state *state,
13373                                        bool async)
13374 {
13375         struct drm_i915_private *dev_priv = dev->dev_private;
13376         struct drm_plane_state *plane_state;
13377         struct drm_crtc_state *crtc_state;
13378         struct drm_plane *plane;
13379         struct drm_crtc *crtc;
13380         int i, ret;
13381
13382         if (async) {
13383                 DRM_DEBUG_KMS("i915 does not yet support async commit\n");
13384                 return -EINVAL;
13385         }
13386
13387         for_each_crtc_in_state(state, crtc, crtc_state, i) {
13388                 ret = intel_crtc_wait_for_pending_flips(crtc);
13389                 if (ret)
13390                         return ret;
13391
13392                 if (atomic_read(&to_intel_crtc(crtc)->unpin_work_count) >= 2)
13393                         flush_workqueue(dev_priv->wq);
13394         }
13395
13396         ret = mutex_lock_interruptible(&dev->struct_mutex);
13397         if (ret)
13398                 return ret;
13399
13400         ret = drm_atomic_helper_prepare_planes(dev, state);
13401         if (!ret && !async && !i915_reset_in_progress(&dev_priv->gpu_error)) {
13402                 u32 reset_counter;
13403
13404                 reset_counter = atomic_read(&dev_priv->gpu_error.reset_counter);
13405                 mutex_unlock(&dev->struct_mutex);
13406
13407                 for_each_plane_in_state(state, plane, plane_state, i) {
13408                         struct intel_plane_state *intel_plane_state =
13409                                 to_intel_plane_state(plane_state);
13410
13411                         if (!intel_plane_state->wait_req)
13412                                 continue;
13413
13414                         ret = __i915_wait_request(intel_plane_state->wait_req,
13415                                                   reset_counter, true,
13416                                                   NULL, NULL);
13417
13418                         /* Swallow -EIO errors to allow updates during hw lockup. */
13419                         if (ret == -EIO)
13420                                 ret = 0;
13421
13422                         if (ret)
13423                                 break;
13424                 }
13425
13426                 if (!ret)
13427                         return 0;
13428
13429                 mutex_lock(&dev->struct_mutex);
13430                 drm_atomic_helper_cleanup_planes(dev, state);
13431         }
13432
13433         mutex_unlock(&dev->struct_mutex);
13434         return ret;
13435 }
13436
13437 /**
13438  * intel_atomic_commit - commit validated state object
13439  * @dev: DRM device
13440  * @state: the top-level driver state object
13441  * @async: asynchronous commit
13442  *
13443  * This function commits a top-level state object that has been validated
13444  * with drm_atomic_helper_check().
13445  *
13446  * FIXME:  Atomic modeset support for i915 is not yet complete.  At the moment
13447  * we can only handle plane-related operations and do not yet support
13448  * asynchronous commit.
13449  *
13450  * RETURNS
13451  * Zero for success or -errno.
13452  */
13453 static int intel_atomic_commit(struct drm_device *dev,
13454                                struct drm_atomic_state *state,
13455                                bool async)
13456 {
13457         struct drm_i915_private *dev_priv = dev->dev_private;
13458         struct drm_crtc_state *crtc_state;
13459         struct drm_crtc *crtc;
13460         int ret = 0;
13461         int i;
13462         bool any_ms = false;
13463
13464         ret = intel_atomic_prepare_commit(dev, state, async);
13465         if (ret) {
13466                 DRM_DEBUG_ATOMIC("Preparing state failed with %i\n", ret);
13467                 return ret;
13468         }
13469
13470         drm_atomic_helper_swap_state(dev, state);
13471         dev_priv->wm.config = to_intel_atomic_state(state)->wm_config;
13472
13473         for_each_crtc_in_state(state, crtc, crtc_state, i) {
13474                 struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
13475
13476                 if (!needs_modeset(crtc->state))
13477                         continue;
13478
13479                 any_ms = true;
13480                 intel_pre_plane_update(intel_crtc);
13481
13482                 if (crtc_state->active) {
13483                         intel_crtc_disable_planes(crtc, crtc_state->plane_mask);
13484                         dev_priv->display.crtc_disable(crtc);
13485                         intel_crtc->active = false;
13486                         intel_disable_shared_dpll(intel_crtc);
13487
13488                         /*
13489                          * Underruns don't always raise
13490                          * interrupts, so check manually.
13491                          */
13492                         intel_check_cpu_fifo_underruns(dev_priv);
13493                         intel_check_pch_fifo_underruns(dev_priv);
13494
13495                         if (!crtc->state->active)
13496                                 intel_update_watermarks(crtc);
13497                 }
13498         }
13499
13500         /* Only after disabling all output pipelines that will be changed can we
13501          * update the the output configuration. */
13502         intel_modeset_update_crtc_state(state);
13503
13504         if (any_ms) {
13505                 intel_shared_dpll_commit(state);
13506
13507                 drm_atomic_helper_update_legacy_modeset_state(state->dev, state);
13508                 modeset_update_crtc_power_domains(state);
13509         }
13510
13511         /* Now enable the clocks, plane, pipe, and connectors that we set up. */
13512         for_each_crtc_in_state(state, crtc, crtc_state, i) {
13513                 struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
13514                 bool modeset = needs_modeset(crtc->state);
13515                 bool update_pipe = !modeset &&
13516                         to_intel_crtc_state(crtc->state)->update_pipe;
13517                 unsigned long put_domains = 0;
13518
13519                 if (modeset)
13520                         intel_display_power_get(dev_priv, POWER_DOMAIN_MODESET);
13521
13522                 if (modeset && crtc->state->active) {
13523                         update_scanline_offset(to_intel_crtc(crtc));
13524                         dev_priv->display.crtc_enable(crtc);
13525                 }
13526
13527                 if (update_pipe) {
13528                         put_domains = modeset_get_crtc_power_domains(crtc);
13529
13530                         /* make sure intel_modeset_check_state runs */
13531                         any_ms = true;
13532                 }
13533
13534                 if (!modeset)
13535                         intel_pre_plane_update(intel_crtc);
13536
13537                 if (crtc->state->active &&
13538                     (crtc->state->planes_changed || update_pipe))
13539                         drm_atomic_helper_commit_planes_on_crtc(crtc_state);
13540
13541                 if (put_domains)
13542                         modeset_put_power_domains(dev_priv, put_domains);
13543
13544                 intel_post_plane_update(intel_crtc);
13545
13546                 if (modeset)
13547                         intel_display_power_put(dev_priv, POWER_DOMAIN_MODESET);
13548         }
13549
13550         /* FIXME: add subpixel order */
13551
13552         drm_atomic_helper_wait_for_vblanks(dev, state);
13553
13554         mutex_lock(&dev->struct_mutex);
13555         drm_atomic_helper_cleanup_planes(dev, state);
13556         mutex_unlock(&dev->struct_mutex);
13557
13558         if (any_ms)
13559                 intel_modeset_check_state(dev, state);
13560
13561         drm_atomic_state_free(state);
13562
13563         return 0;
13564 }
13565
13566 void intel_crtc_restore_mode(struct drm_crtc *crtc)
13567 {
13568         struct drm_device *dev = crtc->dev;
13569         struct drm_atomic_state *state;
13570         struct drm_crtc_state *crtc_state;
13571         int ret;
13572
13573         state = drm_atomic_state_alloc(dev);
13574         if (!state) {
13575                 DRM_DEBUG_KMS("[CRTC:%d] crtc restore failed, out of memory",
13576                               crtc->base.id);
13577                 return;
13578         }
13579
13580         state->acquire_ctx = drm_modeset_legacy_acquire_ctx(crtc);
13581
13582 retry:
13583         crtc_state = drm_atomic_get_crtc_state(state, crtc);
13584         ret = PTR_ERR_OR_ZERO(crtc_state);
13585         if (!ret) {
13586                 if (!crtc_state->active)
13587                         goto out;
13588
13589                 crtc_state->mode_changed = true;
13590                 ret = drm_atomic_commit(state);
13591         }
13592
13593         if (ret == -EDEADLK) {
13594                 drm_atomic_state_clear(state);
13595                 drm_modeset_backoff(state->acquire_ctx);
13596                 goto retry;
13597         }
13598
13599         if (ret)
13600 out:
13601                 drm_atomic_state_free(state);
13602 }
13603
13604 #undef for_each_intel_crtc_masked
13605
13606 static const struct drm_crtc_funcs intel_crtc_funcs = {
13607         .gamma_set = intel_crtc_gamma_set,
13608         .set_config = drm_atomic_helper_set_config,
13609         .destroy = intel_crtc_destroy,
13610         .page_flip = intel_crtc_page_flip,
13611         .atomic_duplicate_state = intel_crtc_duplicate_state,
13612         .atomic_destroy_state = intel_crtc_destroy_state,
13613 };
13614
13615 static bool ibx_pch_dpll_get_hw_state(struct drm_i915_private *dev_priv,
13616                                       struct intel_shared_dpll *pll,
13617                                       struct intel_dpll_hw_state *hw_state)
13618 {
13619         uint32_t val;
13620
13621         if (!intel_display_power_is_enabled(dev_priv, POWER_DOMAIN_PLLS))
13622                 return false;
13623
13624         val = I915_READ(PCH_DPLL(pll->id));
13625         hw_state->dpll = val;
13626         hw_state->fp0 = I915_READ(PCH_FP0(pll->id));
13627         hw_state->fp1 = I915_READ(PCH_FP1(pll->id));
13628
13629         return val & DPLL_VCO_ENABLE;
13630 }
13631
13632 static void ibx_pch_dpll_mode_set(struct drm_i915_private *dev_priv,
13633                                   struct intel_shared_dpll *pll)
13634 {
13635         I915_WRITE(PCH_FP0(pll->id), pll->config.hw_state.fp0);
13636         I915_WRITE(PCH_FP1(pll->id), pll->config.hw_state.fp1);
13637 }
13638
13639 static void ibx_pch_dpll_enable(struct drm_i915_private *dev_priv,
13640                                 struct intel_shared_dpll *pll)
13641 {
13642         /* PCH refclock must be enabled first */
13643         ibx_assert_pch_refclk_enabled(dev_priv);
13644
13645         I915_WRITE(PCH_DPLL(pll->id), pll->config.hw_state.dpll);
13646
13647         /* Wait for the clocks to stabilize. */
13648         POSTING_READ(PCH_DPLL(pll->id));
13649         udelay(150);
13650
13651         /* The pixel multiplier can only be updated once the
13652          * DPLL is enabled and the clocks are stable.
13653          *
13654          * So write it again.
13655          */
13656         I915_WRITE(PCH_DPLL(pll->id), pll->config.hw_state.dpll);
13657         POSTING_READ(PCH_DPLL(pll->id));
13658         udelay(200);
13659 }
13660
13661 static void ibx_pch_dpll_disable(struct drm_i915_private *dev_priv,
13662                                  struct intel_shared_dpll *pll)
13663 {
13664         struct drm_device *dev = dev_priv->dev;
13665         struct intel_crtc *crtc;
13666
13667         /* Make sure no transcoder isn't still depending on us. */
13668         for_each_intel_crtc(dev, crtc) {
13669                 if (intel_crtc_to_shared_dpll(crtc) == pll)
13670                         assert_pch_transcoder_disabled(dev_priv, crtc->pipe);
13671         }
13672
13673         I915_WRITE(PCH_DPLL(pll->id), 0);
13674         POSTING_READ(PCH_DPLL(pll->id));
13675         udelay(200);
13676 }
13677
13678 static char *ibx_pch_dpll_names[] = {
13679         "PCH DPLL A",
13680         "PCH DPLL B",
13681 };
13682
13683 static void ibx_pch_dpll_init(struct drm_device *dev)
13684 {
13685         struct drm_i915_private *dev_priv = dev->dev_private;
13686         int i;
13687
13688         dev_priv->num_shared_dpll = 2;
13689
13690         for (i = 0; i < dev_priv->num_shared_dpll; i++) {
13691                 dev_priv->shared_dplls[i].id = i;
13692                 dev_priv->shared_dplls[i].name = ibx_pch_dpll_names[i];
13693                 dev_priv->shared_dplls[i].mode_set = ibx_pch_dpll_mode_set;
13694                 dev_priv->shared_dplls[i].enable = ibx_pch_dpll_enable;
13695                 dev_priv->shared_dplls[i].disable = ibx_pch_dpll_disable;
13696                 dev_priv->shared_dplls[i].get_hw_state =
13697                         ibx_pch_dpll_get_hw_state;
13698         }
13699 }
13700
13701 static void intel_shared_dpll_init(struct drm_device *dev)
13702 {
13703         struct drm_i915_private *dev_priv = dev->dev_private;
13704
13705         if (HAS_DDI(dev))
13706                 intel_ddi_pll_init(dev);
13707         else if (HAS_PCH_IBX(dev) || HAS_PCH_CPT(dev))
13708                 ibx_pch_dpll_init(dev);
13709         else
13710                 dev_priv->num_shared_dpll = 0;
13711
13712         BUG_ON(dev_priv->num_shared_dpll > I915_NUM_PLLS);
13713 }
13714
13715 /**
13716  * intel_prepare_plane_fb - Prepare fb for usage on plane
13717  * @plane: drm plane to prepare for
13718  * @fb: framebuffer to prepare for presentation
13719  *
13720  * Prepares a framebuffer for usage on a display plane.  Generally this
13721  * involves pinning the underlying object and updating the frontbuffer tracking
13722  * bits.  Some older platforms need special physical address handling for
13723  * cursor planes.
13724  *
13725  * Must be called with struct_mutex held.
13726  *
13727  * Returns 0 on success, negative error code on failure.
13728  */
13729 int
13730 intel_prepare_plane_fb(struct drm_plane *plane,
13731                        const struct drm_plane_state *new_state)
13732 {
13733         struct drm_device *dev = plane->dev;
13734         struct drm_framebuffer *fb = new_state->fb;
13735         struct intel_plane *intel_plane = to_intel_plane(plane);
13736         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
13737         struct drm_i915_gem_object *old_obj = intel_fb_obj(plane->state->fb);
13738         int ret = 0;
13739
13740         if (!obj && !old_obj)
13741                 return 0;
13742
13743         if (old_obj) {
13744                 struct drm_crtc_state *crtc_state =
13745                         drm_atomic_get_existing_crtc_state(new_state->state, plane->state->crtc);
13746
13747                 /* Big Hammer, we also need to ensure that any pending
13748                  * MI_WAIT_FOR_EVENT inside a user batch buffer on the
13749                  * current scanout is retired before unpinning the old
13750                  * framebuffer. Note that we rely on userspace rendering
13751                  * into the buffer attached to the pipe they are waiting
13752                  * on. If not, userspace generates a GPU hang with IPEHR
13753                  * point to the MI_WAIT_FOR_EVENT.
13754                  *
13755                  * This should only fail upon a hung GPU, in which case we
13756                  * can safely continue.
13757                  */
13758                 if (needs_modeset(crtc_state))
13759                         ret = i915_gem_object_wait_rendering(old_obj, true);
13760
13761                 /* Swallow -EIO errors to allow updates during hw lockup. */
13762                 if (ret && ret != -EIO)
13763                         return ret;
13764         }
13765
13766         /* For framebuffer backed by dmabuf, wait for fence */
13767         if (obj && obj->base.dma_buf) {
13768                 ret = reservation_object_wait_timeout_rcu(obj->base.dma_buf->resv,
13769                                                           false, true,
13770                                                           MAX_SCHEDULE_TIMEOUT);
13771                 if (ret == -ERESTARTSYS)
13772                         return ret;
13773
13774                 WARN_ON(ret < 0);
13775         }
13776
13777         if (!obj) {
13778                 ret = 0;
13779         } else if (plane->type == DRM_PLANE_TYPE_CURSOR &&
13780             INTEL_INFO(dev)->cursor_needs_physical) {
13781                 int align = IS_I830(dev) ? 16 * 1024 : 256;
13782                 ret = i915_gem_object_attach_phys(obj, align);
13783                 if (ret)
13784                         DRM_DEBUG_KMS("failed to attach phys object\n");
13785         } else {
13786                 ret = intel_pin_and_fence_fb_obj(plane, fb, new_state);
13787         }
13788
13789         if (ret == 0) {
13790                 if (obj) {
13791                         struct intel_plane_state *plane_state =
13792                                 to_intel_plane_state(new_state);
13793
13794                         i915_gem_request_assign(&plane_state->wait_req,
13795                                                 obj->last_write_req);
13796                 }
13797
13798                 i915_gem_track_fb(old_obj, obj, intel_plane->frontbuffer_bit);
13799         }
13800
13801         return ret;
13802 }
13803
13804 /**
13805  * intel_cleanup_plane_fb - Cleans up an fb after plane use
13806  * @plane: drm plane to clean up for
13807  * @fb: old framebuffer that was on plane
13808  *
13809  * Cleans up a framebuffer that has just been removed from a plane.
13810  *
13811  * Must be called with struct_mutex held.
13812  */
13813 void
13814 intel_cleanup_plane_fb(struct drm_plane *plane,
13815                        const struct drm_plane_state *old_state)
13816 {
13817         struct drm_device *dev = plane->dev;
13818         struct intel_plane *intel_plane = to_intel_plane(plane);
13819         struct intel_plane_state *old_intel_state;
13820         struct drm_i915_gem_object *old_obj = intel_fb_obj(old_state->fb);
13821         struct drm_i915_gem_object *obj = intel_fb_obj(plane->state->fb);
13822
13823         old_intel_state = to_intel_plane_state(old_state);
13824
13825         if (!obj && !old_obj)
13826                 return;
13827
13828         if (old_obj && (plane->type != DRM_PLANE_TYPE_CURSOR ||
13829             !INTEL_INFO(dev)->cursor_needs_physical))
13830                 intel_unpin_fb_obj(old_state->fb, old_state);
13831
13832         /* prepare_fb aborted? */
13833         if ((old_obj && (old_obj->frontbuffer_bits & intel_plane->frontbuffer_bit)) ||
13834             (obj && !(obj->frontbuffer_bits & intel_plane->frontbuffer_bit)))
13835                 i915_gem_track_fb(old_obj, obj, intel_plane->frontbuffer_bit);
13836
13837         i915_gem_request_assign(&old_intel_state->wait_req, NULL);
13838
13839 }
13840
13841 int
13842 skl_max_scale(struct intel_crtc *intel_crtc, struct intel_crtc_state *crtc_state)
13843 {
13844         int max_scale;
13845         struct drm_device *dev;
13846         struct drm_i915_private *dev_priv;
13847         int crtc_clock, cdclk;
13848
13849         if (!intel_crtc || !crtc_state)
13850                 return DRM_PLANE_HELPER_NO_SCALING;
13851
13852         dev = intel_crtc->base.dev;
13853         dev_priv = dev->dev_private;
13854         crtc_clock = crtc_state->base.adjusted_mode.crtc_clock;
13855         cdclk = to_intel_atomic_state(crtc_state->base.state)->cdclk;
13856
13857         if (WARN_ON_ONCE(!crtc_clock || cdclk < crtc_clock))
13858                 return DRM_PLANE_HELPER_NO_SCALING;
13859
13860         /*
13861          * skl max scale is lower of:
13862          *    close to 3 but not 3, -1 is for that purpose
13863          *            or
13864          *    cdclk/crtc_clock
13865          */
13866         max_scale = min((1 << 16) * 3 - 1, (1 << 8) * ((cdclk << 8) / crtc_clock));
13867
13868         return max_scale;
13869 }
13870
13871 static int
13872 intel_check_primary_plane(struct drm_plane *plane,
13873                           struct intel_crtc_state *crtc_state,
13874                           struct intel_plane_state *state)
13875 {
13876         struct drm_crtc *crtc = state->base.crtc;
13877         struct drm_framebuffer *fb = state->base.fb;
13878         int min_scale = DRM_PLANE_HELPER_NO_SCALING;
13879         int max_scale = DRM_PLANE_HELPER_NO_SCALING;
13880         bool can_position = false;
13881
13882         /* use scaler when colorkey is not required */
13883         if (INTEL_INFO(plane->dev)->gen >= 9 &&
13884             state->ckey.flags == I915_SET_COLORKEY_NONE) {
13885                 min_scale = 1;
13886                 max_scale = skl_max_scale(to_intel_crtc(crtc), crtc_state);
13887                 can_position = true;
13888         }
13889
13890         return drm_plane_helper_check_update(plane, crtc, fb, &state->src,
13891                                              &state->dst, &state->clip,
13892                                              min_scale, max_scale,
13893                                              can_position, true,
13894                                              &state->visible);
13895 }
13896
13897 static void
13898 intel_commit_primary_plane(struct drm_plane *plane,
13899                            struct intel_plane_state *state)
13900 {
13901         struct drm_crtc *crtc = state->base.crtc;
13902         struct drm_framebuffer *fb = state->base.fb;
13903         struct drm_device *dev = plane->dev;
13904         struct drm_i915_private *dev_priv = dev->dev_private;
13905
13906         crtc = crtc ? crtc : plane->crtc;
13907
13908         dev_priv->display.update_primary_plane(crtc, fb,
13909                                                state->src.x1 >> 16,
13910                                                state->src.y1 >> 16);
13911 }
13912
13913 static void
13914 intel_disable_primary_plane(struct drm_plane *plane,
13915                             struct drm_crtc *crtc)
13916 {
13917         struct drm_device *dev = plane->dev;
13918         struct drm_i915_private *dev_priv = dev->dev_private;
13919
13920         dev_priv->display.update_primary_plane(crtc, NULL, 0, 0);
13921 }
13922
13923 static void intel_begin_crtc_commit(struct drm_crtc *crtc,
13924                                     struct drm_crtc_state *old_crtc_state)
13925 {
13926         struct drm_device *dev = crtc->dev;
13927         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
13928         struct intel_crtc_state *old_intel_state =
13929                 to_intel_crtc_state(old_crtc_state);
13930         bool modeset = needs_modeset(crtc->state);
13931
13932         /* Perform vblank evasion around commit operation */
13933         intel_pipe_update_start(intel_crtc);
13934
13935         if (modeset)
13936                 return;
13937
13938         if (to_intel_crtc_state(crtc->state)->update_pipe)
13939                 intel_update_pipe_config(intel_crtc, old_intel_state);
13940         else if (INTEL_INFO(dev)->gen >= 9)
13941                 skl_detach_scalers(intel_crtc);
13942 }
13943
13944 static void intel_finish_crtc_commit(struct drm_crtc *crtc,
13945                                      struct drm_crtc_state *old_crtc_state)
13946 {
13947         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
13948
13949         intel_pipe_update_end(intel_crtc);
13950 }
13951
13952 /**
13953  * intel_plane_destroy - destroy a plane
13954  * @plane: plane to destroy
13955  *
13956  * Common destruction function for all types of planes (primary, cursor,
13957  * sprite).
13958  */
13959 void intel_plane_destroy(struct drm_plane *plane)
13960 {
13961         struct intel_plane *intel_plane = to_intel_plane(plane);
13962         drm_plane_cleanup(plane);
13963         kfree(intel_plane);
13964 }
13965
13966 const struct drm_plane_funcs intel_plane_funcs = {
13967         .update_plane = drm_atomic_helper_update_plane,
13968         .disable_plane = drm_atomic_helper_disable_plane,
13969         .destroy = intel_plane_destroy,
13970         .set_property = drm_atomic_helper_plane_set_property,
13971         .atomic_get_property = intel_plane_atomic_get_property,
13972         .atomic_set_property = intel_plane_atomic_set_property,
13973         .atomic_duplicate_state = intel_plane_duplicate_state,
13974         .atomic_destroy_state = intel_plane_destroy_state,
13975
13976 };
13977
13978 static struct drm_plane *intel_primary_plane_create(struct drm_device *dev,
13979                                                     int pipe)
13980 {
13981         struct intel_plane *primary;
13982         struct intel_plane_state *state;
13983         const uint32_t *intel_primary_formats;
13984         unsigned int num_formats;
13985
13986         primary = kzalloc(sizeof(*primary), GFP_KERNEL);
13987         if (primary == NULL)
13988                 return NULL;
13989
13990         state = intel_create_plane_state(&primary->base);
13991         if (!state) {
13992                 kfree(primary);
13993                 return NULL;
13994         }
13995         primary->base.state = &state->base;
13996
13997         primary->can_scale = false;
13998         primary->max_downscale = 1;
13999         if (INTEL_INFO(dev)->gen >= 9) {
14000                 primary->can_scale = true;
14001                 state->scaler_id = -1;
14002         }
14003         primary->pipe = pipe;
14004         primary->plane = pipe;
14005         primary->frontbuffer_bit = INTEL_FRONTBUFFER_PRIMARY(pipe);
14006         primary->check_plane = intel_check_primary_plane;
14007         primary->commit_plane = intel_commit_primary_plane;
14008         primary->disable_plane = intel_disable_primary_plane;
14009         if (HAS_FBC(dev) && INTEL_INFO(dev)->gen < 4)
14010                 primary->plane = !pipe;
14011
14012         if (INTEL_INFO(dev)->gen >= 9) {
14013                 intel_primary_formats = skl_primary_formats;
14014                 num_formats = ARRAY_SIZE(skl_primary_formats);
14015         } else if (INTEL_INFO(dev)->gen >= 4) {
14016                 intel_primary_formats = i965_primary_formats;
14017                 num_formats = ARRAY_SIZE(i965_primary_formats);
14018         } else {
14019                 intel_primary_formats = i8xx_primary_formats;
14020                 num_formats = ARRAY_SIZE(i8xx_primary_formats);
14021         }
14022
14023         drm_universal_plane_init(dev, &primary->base, 0,
14024                                  &intel_plane_funcs,
14025                                  intel_primary_formats, num_formats,
14026                                  DRM_PLANE_TYPE_PRIMARY, NULL);
14027
14028         if (INTEL_INFO(dev)->gen >= 4)
14029                 intel_create_rotation_property(dev, primary);
14030
14031         drm_plane_helper_add(&primary->base, &intel_plane_helper_funcs);
14032
14033         return &primary->base;
14034 }
14035
14036 void intel_create_rotation_property(struct drm_device *dev, struct intel_plane *plane)
14037 {
14038         if (!dev->mode_config.rotation_property) {
14039                 unsigned long flags = BIT(DRM_ROTATE_0) |
14040                         BIT(DRM_ROTATE_180);
14041
14042                 if (INTEL_INFO(dev)->gen >= 9)
14043                         flags |= BIT(DRM_ROTATE_90) | BIT(DRM_ROTATE_270);
14044
14045                 dev->mode_config.rotation_property =
14046                         drm_mode_create_rotation_property(dev, flags);
14047         }
14048         if (dev->mode_config.rotation_property)
14049                 drm_object_attach_property(&plane->base.base,
14050                                 dev->mode_config.rotation_property,
14051                                 plane->base.state->rotation);
14052 }
14053
14054 static int
14055 intel_check_cursor_plane(struct drm_plane *plane,
14056                          struct intel_crtc_state *crtc_state,
14057                          struct intel_plane_state *state)
14058 {
14059         struct drm_crtc *crtc = crtc_state->base.crtc;
14060         struct drm_framebuffer *fb = state->base.fb;
14061         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
14062         unsigned stride;
14063         int ret;
14064
14065         ret = drm_plane_helper_check_update(plane, crtc, fb, &state->src,
14066                                             &state->dst, &state->clip,
14067                                             DRM_PLANE_HELPER_NO_SCALING,
14068                                             DRM_PLANE_HELPER_NO_SCALING,
14069                                             true, true, &state->visible);
14070         if (ret)
14071                 return ret;
14072
14073         /* if we want to turn off the cursor ignore width and height */
14074         if (!obj)
14075                 return 0;
14076
14077         /* Check for which cursor types we support */
14078         if (!cursor_size_ok(plane->dev, state->base.crtc_w, state->base.crtc_h)) {
14079                 DRM_DEBUG("Cursor dimension %dx%d not supported\n",
14080                           state->base.crtc_w, state->base.crtc_h);
14081                 return -EINVAL;
14082         }
14083
14084         stride = roundup_pow_of_two(state->base.crtc_w) * 4;
14085         if (obj->base.size < stride * state->base.crtc_h) {
14086                 DRM_DEBUG_KMS("buffer is too small\n");
14087                 return -ENOMEM;
14088         }
14089
14090         if (fb->modifier[0] != DRM_FORMAT_MOD_NONE) {
14091                 DRM_DEBUG_KMS("cursor cannot be tiled\n");
14092                 return -EINVAL;
14093         }
14094
14095         return 0;
14096 }
14097
14098 static void
14099 intel_disable_cursor_plane(struct drm_plane *plane,
14100                            struct drm_crtc *crtc)
14101 {
14102         intel_crtc_update_cursor(crtc, false);
14103 }
14104
14105 static void
14106 intel_commit_cursor_plane(struct drm_plane *plane,
14107                           struct intel_plane_state *state)
14108 {
14109         struct drm_crtc *crtc = state->base.crtc;
14110         struct drm_device *dev = plane->dev;
14111         struct intel_crtc *intel_crtc;
14112         struct drm_i915_gem_object *obj = intel_fb_obj(state->base.fb);
14113         uint32_t addr;
14114
14115         crtc = crtc ? crtc : plane->crtc;
14116         intel_crtc = to_intel_crtc(crtc);
14117
14118         if (!obj)
14119                 addr = 0;
14120         else if (!INTEL_INFO(dev)->cursor_needs_physical)
14121                 addr = i915_gem_obj_ggtt_offset(obj);
14122         else
14123                 addr = obj->phys_handle->busaddr;
14124
14125         intel_crtc->cursor_addr = addr;
14126
14127         intel_crtc_update_cursor(crtc, state->visible);
14128 }
14129
14130 static struct drm_plane *intel_cursor_plane_create(struct drm_device *dev,
14131                                                    int pipe)
14132 {
14133         struct intel_plane *cursor;
14134         struct intel_plane_state *state;
14135
14136         cursor = kzalloc(sizeof(*cursor), GFP_KERNEL);
14137         if (cursor == NULL)
14138                 return NULL;
14139
14140         state = intel_create_plane_state(&cursor->base);
14141         if (!state) {
14142                 kfree(cursor);
14143                 return NULL;
14144         }
14145         cursor->base.state = &state->base;
14146
14147         cursor->can_scale = false;
14148         cursor->max_downscale = 1;
14149         cursor->pipe = pipe;
14150         cursor->plane = pipe;
14151         cursor->frontbuffer_bit = INTEL_FRONTBUFFER_CURSOR(pipe);
14152         cursor->check_plane = intel_check_cursor_plane;
14153         cursor->commit_plane = intel_commit_cursor_plane;
14154         cursor->disable_plane = intel_disable_cursor_plane;
14155
14156         drm_universal_plane_init(dev, &cursor->base, 0,
14157                                  &intel_plane_funcs,
14158                                  intel_cursor_formats,
14159                                  ARRAY_SIZE(intel_cursor_formats),
14160                                  DRM_PLANE_TYPE_CURSOR, NULL);
14161
14162         if (INTEL_INFO(dev)->gen >= 4) {
14163                 if (!dev->mode_config.rotation_property)
14164                         dev->mode_config.rotation_property =
14165                                 drm_mode_create_rotation_property(dev,
14166                                                         BIT(DRM_ROTATE_0) |
14167                                                         BIT(DRM_ROTATE_180));
14168                 if (dev->mode_config.rotation_property)
14169                         drm_object_attach_property(&cursor->base.base,
14170                                 dev->mode_config.rotation_property,
14171                                 state->base.rotation);
14172         }
14173
14174         if (INTEL_INFO(dev)->gen >=9)
14175                 state->scaler_id = -1;
14176
14177         drm_plane_helper_add(&cursor->base, &intel_plane_helper_funcs);
14178
14179         return &cursor->base;
14180 }
14181
14182 static void skl_init_scalers(struct drm_device *dev, struct intel_crtc *intel_crtc,
14183         struct intel_crtc_state *crtc_state)
14184 {
14185         int i;
14186         struct intel_scaler *intel_scaler;
14187         struct intel_crtc_scaler_state *scaler_state = &crtc_state->scaler_state;
14188
14189         for (i = 0; i < intel_crtc->num_scalers; i++) {
14190                 intel_scaler = &scaler_state->scalers[i];
14191                 intel_scaler->in_use = 0;
14192                 intel_scaler->mode = PS_SCALER_MODE_DYN;
14193         }
14194
14195         scaler_state->scaler_id = -1;
14196 }
14197
14198 static void intel_crtc_init(struct drm_device *dev, int pipe)
14199 {
14200         struct drm_i915_private *dev_priv = dev->dev_private;
14201         struct intel_crtc *intel_crtc;
14202         struct intel_crtc_state *crtc_state = NULL;
14203         struct drm_plane *primary = NULL;
14204         struct drm_plane *cursor = NULL;
14205         int i, ret;
14206
14207         intel_crtc = kzalloc(sizeof(*intel_crtc), GFP_KERNEL);
14208         if (intel_crtc == NULL)
14209                 return;
14210
14211         crtc_state = kzalloc(sizeof(*crtc_state), GFP_KERNEL);
14212         if (!crtc_state)
14213                 goto fail;
14214         intel_crtc->config = crtc_state;
14215         intel_crtc->base.state = &crtc_state->base;
14216         crtc_state->base.crtc = &intel_crtc->base;
14217
14218         /* initialize shared scalers */
14219         if (INTEL_INFO(dev)->gen >= 9) {
14220                 if (pipe == PIPE_C)
14221                         intel_crtc->num_scalers = 1;
14222                 else
14223                         intel_crtc->num_scalers = SKL_NUM_SCALERS;
14224
14225                 skl_init_scalers(dev, intel_crtc, crtc_state);
14226         }
14227
14228         primary = intel_primary_plane_create(dev, pipe);
14229         if (!primary)
14230                 goto fail;
14231
14232         cursor = intel_cursor_plane_create(dev, pipe);
14233         if (!cursor)
14234                 goto fail;
14235
14236         ret = drm_crtc_init_with_planes(dev, &intel_crtc->base, primary,
14237                                         cursor, &intel_crtc_funcs, NULL);
14238         if (ret)
14239                 goto fail;
14240
14241         drm_mode_crtc_set_gamma_size(&intel_crtc->base, 256);
14242         for (i = 0; i < 256; i++) {
14243                 intel_crtc->lut_r[i] = i;
14244                 intel_crtc->lut_g[i] = i;
14245                 intel_crtc->lut_b[i] = i;
14246         }
14247
14248         /*
14249          * On gen2/3 only plane A can do fbc, but the panel fitter and lvds port
14250          * is hooked to pipe B. Hence we want plane A feeding pipe B.
14251          */
14252         intel_crtc->pipe = pipe;
14253         intel_crtc->plane = pipe;
14254         if (HAS_FBC(dev) && INTEL_INFO(dev)->gen < 4) {
14255                 DRM_DEBUG_KMS("swapping pipes & planes for FBC\n");
14256                 intel_crtc->plane = !pipe;
14257         }
14258
14259         intel_crtc->cursor_base = ~0;
14260         intel_crtc->cursor_cntl = ~0;
14261         intel_crtc->cursor_size = ~0;
14262
14263         intel_crtc->wm.cxsr_allowed = true;
14264
14265         BUG_ON(pipe >= ARRAY_SIZE(dev_priv->plane_to_crtc_mapping) ||
14266                dev_priv->plane_to_crtc_mapping[intel_crtc->plane] != NULL);
14267         dev_priv->plane_to_crtc_mapping[intel_crtc->plane] = &intel_crtc->base;
14268         dev_priv->pipe_to_crtc_mapping[intel_crtc->pipe] = &intel_crtc->base;
14269
14270         drm_crtc_helper_add(&intel_crtc->base, &intel_helper_funcs);
14271
14272         WARN_ON(drm_crtc_index(&intel_crtc->base) != intel_crtc->pipe);
14273         return;
14274
14275 fail:
14276         if (primary)
14277                 drm_plane_cleanup(primary);
14278         if (cursor)
14279                 drm_plane_cleanup(cursor);
14280         kfree(crtc_state);
14281         kfree(intel_crtc);
14282 }
14283
14284 enum pipe intel_get_pipe_from_connector(struct intel_connector *connector)
14285 {
14286         struct drm_encoder *encoder = connector->base.encoder;
14287         struct drm_device *dev = connector->base.dev;
14288
14289         WARN_ON(!drm_modeset_is_locked(&dev->mode_config.connection_mutex));
14290
14291         if (!encoder || WARN_ON(!encoder->crtc))
14292                 return INVALID_PIPE;
14293
14294         return to_intel_crtc(encoder->crtc)->pipe;
14295 }
14296
14297 int intel_get_pipe_from_crtc_id(struct drm_device *dev, void *data,
14298                                 struct drm_file *file)
14299 {
14300         struct drm_i915_get_pipe_from_crtc_id *pipe_from_crtc_id = data;
14301         struct drm_crtc *drmmode_crtc;
14302         struct intel_crtc *crtc;
14303
14304         drmmode_crtc = drm_crtc_find(dev, pipe_from_crtc_id->crtc_id);
14305
14306         if (!drmmode_crtc) {
14307                 DRM_ERROR("no such CRTC id\n");
14308                 return -ENOENT;
14309         }
14310
14311         crtc = to_intel_crtc(drmmode_crtc);
14312         pipe_from_crtc_id->pipe = crtc->pipe;
14313
14314         return 0;
14315 }
14316
14317 static int intel_encoder_clones(struct intel_encoder *encoder)
14318 {
14319         struct drm_device *dev = encoder->base.dev;
14320         struct intel_encoder *source_encoder;
14321         int index_mask = 0;
14322         int entry = 0;
14323
14324         for_each_intel_encoder(dev, source_encoder) {
14325                 if (encoders_cloneable(encoder, source_encoder))
14326                         index_mask |= (1 << entry);
14327
14328                 entry++;
14329         }
14330
14331         return index_mask;
14332 }
14333
14334 static bool has_edp_a(struct drm_device *dev)
14335 {
14336         struct drm_i915_private *dev_priv = dev->dev_private;
14337
14338         if (!IS_MOBILE(dev))
14339                 return false;
14340
14341         if ((I915_READ(DP_A) & DP_DETECTED) == 0)
14342                 return false;
14343
14344         if (IS_GEN5(dev) && (I915_READ(FUSE_STRAP) & ILK_eDP_A_DISABLE))
14345                 return false;
14346
14347         return true;
14348 }
14349
14350 static bool intel_crt_present(struct drm_device *dev)
14351 {
14352         struct drm_i915_private *dev_priv = dev->dev_private;
14353
14354         if (INTEL_INFO(dev)->gen >= 9)
14355                 return false;
14356
14357         if (IS_HSW_ULT(dev) || IS_BDW_ULT(dev))
14358                 return false;
14359
14360         if (IS_CHERRYVIEW(dev))
14361                 return false;
14362
14363         if (HAS_PCH_LPT_H(dev) && I915_READ(SFUSE_STRAP) & SFUSE_STRAP_CRT_DISABLED)
14364                 return false;
14365
14366         /* DDI E can't be used if DDI A requires 4 lanes */
14367         if (HAS_DDI(dev) && I915_READ(DDI_BUF_CTL(PORT_A)) & DDI_A_4_LANES)
14368                 return false;
14369
14370         if (!dev_priv->vbt.int_crt_support)
14371                 return false;
14372
14373         return true;
14374 }
14375
14376 static void intel_setup_outputs(struct drm_device *dev)
14377 {
14378         struct drm_i915_private *dev_priv = dev->dev_private;
14379         struct intel_encoder *encoder;
14380         bool dpd_is_edp = false;
14381
14382         intel_lvds_init(dev);
14383
14384         if (intel_crt_present(dev))
14385                 intel_crt_init(dev);
14386
14387         if (IS_BROXTON(dev)) {
14388                 /*
14389                  * FIXME: Broxton doesn't support port detection via the
14390                  * DDI_BUF_CTL_A or SFUSE_STRAP registers, find another way to
14391                  * detect the ports.
14392                  */
14393                 intel_ddi_init(dev, PORT_A);
14394                 intel_ddi_init(dev, PORT_B);
14395                 intel_ddi_init(dev, PORT_C);
14396         } else if (HAS_DDI(dev)) {
14397                 int found;
14398
14399                 /*
14400                  * Haswell uses DDI functions to detect digital outputs.
14401                  * On SKL pre-D0 the strap isn't connected, so we assume
14402                  * it's there.
14403                  */
14404                 found = I915_READ(DDI_BUF_CTL(PORT_A)) & DDI_INIT_DISPLAY_DETECTED;
14405                 /* WaIgnoreDDIAStrap: skl */
14406                 if (found || IS_SKYLAKE(dev) || IS_KABYLAKE(dev))
14407                         intel_ddi_init(dev, PORT_A);
14408
14409                 /* DDI B, C and D detection is indicated by the SFUSE_STRAP
14410                  * register */
14411                 found = I915_READ(SFUSE_STRAP);
14412
14413                 if (found & SFUSE_STRAP_DDIB_DETECTED)
14414                         intel_ddi_init(dev, PORT_B);
14415                 if (found & SFUSE_STRAP_DDIC_DETECTED)
14416                         intel_ddi_init(dev, PORT_C);
14417                 if (found & SFUSE_STRAP_DDID_DETECTED)
14418                         intel_ddi_init(dev, PORT_D);
14419                 /*
14420                  * On SKL we don't have a way to detect DDI-E so we rely on VBT.
14421                  */
14422                 if ((IS_SKYLAKE(dev) || IS_KABYLAKE(dev)) &&
14423                     (dev_priv->vbt.ddi_port_info[PORT_E].supports_dp ||
14424                      dev_priv->vbt.ddi_port_info[PORT_E].supports_dvi ||
14425                      dev_priv->vbt.ddi_port_info[PORT_E].supports_hdmi))
14426                         intel_ddi_init(dev, PORT_E);
14427
14428         } else if (HAS_PCH_SPLIT(dev)) {
14429                 int found;
14430                 dpd_is_edp = intel_dp_is_edp(dev, PORT_D);
14431
14432                 if (has_edp_a(dev))
14433                         intel_dp_init(dev, DP_A, PORT_A);
14434
14435                 if (I915_READ(PCH_HDMIB) & SDVO_DETECTED) {
14436                         /* PCH SDVOB multiplex with HDMIB */
14437                         found = intel_sdvo_init(dev, PCH_SDVOB, PORT_B);
14438                         if (!found)
14439                                 intel_hdmi_init(dev, PCH_HDMIB, PORT_B);
14440                         if (!found && (I915_READ(PCH_DP_B) & DP_DETECTED))
14441                                 intel_dp_init(dev, PCH_DP_B, PORT_B);
14442                 }
14443
14444                 if (I915_READ(PCH_HDMIC) & SDVO_DETECTED)
14445                         intel_hdmi_init(dev, PCH_HDMIC, PORT_C);
14446
14447                 if (!dpd_is_edp && I915_READ(PCH_HDMID) & SDVO_DETECTED)
14448                         intel_hdmi_init(dev, PCH_HDMID, PORT_D);
14449
14450                 if (I915_READ(PCH_DP_C) & DP_DETECTED)
14451                         intel_dp_init(dev, PCH_DP_C, PORT_C);
14452
14453                 if (I915_READ(PCH_DP_D) & DP_DETECTED)
14454                         intel_dp_init(dev, PCH_DP_D, PORT_D);
14455         } else if (IS_VALLEYVIEW(dev) || IS_CHERRYVIEW(dev)) {
14456                 /*
14457                  * The DP_DETECTED bit is the latched state of the DDC
14458                  * SDA pin at boot. However since eDP doesn't require DDC
14459                  * (no way to plug in a DP->HDMI dongle) the DDC pins for
14460                  * eDP ports may have been muxed to an alternate function.
14461                  * Thus we can't rely on the DP_DETECTED bit alone to detect
14462                  * eDP ports. Consult the VBT as well as DP_DETECTED to
14463                  * detect eDP ports.
14464                  */
14465                 if (I915_READ(VLV_HDMIB) & SDVO_DETECTED &&
14466                     !intel_dp_is_edp(dev, PORT_B))
14467                         intel_hdmi_init(dev, VLV_HDMIB, PORT_B);
14468                 if (I915_READ(VLV_DP_B) & DP_DETECTED ||
14469                     intel_dp_is_edp(dev, PORT_B))
14470                         intel_dp_init(dev, VLV_DP_B, PORT_B);
14471
14472                 if (I915_READ(VLV_HDMIC) & SDVO_DETECTED &&
14473                     !intel_dp_is_edp(dev, PORT_C))
14474                         intel_hdmi_init(dev, VLV_HDMIC, PORT_C);
14475                 if (I915_READ(VLV_DP_C) & DP_DETECTED ||
14476                     intel_dp_is_edp(dev, PORT_C))
14477                         intel_dp_init(dev, VLV_DP_C, PORT_C);
14478
14479                 if (IS_CHERRYVIEW(dev)) {
14480                         /* eDP not supported on port D, so don't check VBT */
14481                         if (I915_READ(CHV_HDMID) & SDVO_DETECTED)
14482                                 intel_hdmi_init(dev, CHV_HDMID, PORT_D);
14483                         if (I915_READ(CHV_DP_D) & DP_DETECTED)
14484                                 intel_dp_init(dev, CHV_DP_D, PORT_D);
14485                 }
14486
14487                 intel_dsi_init(dev);
14488         } else if (!IS_GEN2(dev) && !IS_PINEVIEW(dev)) {
14489                 bool found = false;
14490
14491                 if (I915_READ(GEN3_SDVOB) & SDVO_DETECTED) {
14492                         DRM_DEBUG_KMS("probing SDVOB\n");
14493                         found = intel_sdvo_init(dev, GEN3_SDVOB, PORT_B);
14494                         if (!found && IS_G4X(dev)) {
14495                                 DRM_DEBUG_KMS("probing HDMI on SDVOB\n");
14496                                 intel_hdmi_init(dev, GEN4_HDMIB, PORT_B);
14497                         }
14498
14499                         if (!found && IS_G4X(dev))
14500                                 intel_dp_init(dev, DP_B, PORT_B);
14501                 }
14502
14503                 /* Before G4X SDVOC doesn't have its own detect register */
14504
14505                 if (I915_READ(GEN3_SDVOB) & SDVO_DETECTED) {
14506                         DRM_DEBUG_KMS("probing SDVOC\n");
14507                         found = intel_sdvo_init(dev, GEN3_SDVOC, PORT_C);
14508                 }
14509
14510                 if (!found && (I915_READ(GEN3_SDVOC) & SDVO_DETECTED)) {
14511
14512                         if (IS_G4X(dev)) {
14513                                 DRM_DEBUG_KMS("probing HDMI on SDVOC\n");
14514                                 intel_hdmi_init(dev, GEN4_HDMIC, PORT_C);
14515                         }
14516                         if (IS_G4X(dev))
14517                                 intel_dp_init(dev, DP_C, PORT_C);
14518                 }
14519
14520                 if (IS_G4X(dev) &&
14521                     (I915_READ(DP_D) & DP_DETECTED))
14522                         intel_dp_init(dev, DP_D, PORT_D);
14523         } else if (IS_GEN2(dev))
14524                 intel_dvo_init(dev);
14525
14526         if (SUPPORTS_TV(dev))
14527                 intel_tv_init(dev);
14528
14529         intel_psr_init(dev);
14530
14531         for_each_intel_encoder(dev, encoder) {
14532                 encoder->base.possible_crtcs = encoder->crtc_mask;
14533                 encoder->base.possible_clones =
14534                         intel_encoder_clones(encoder);
14535         }
14536
14537         intel_init_pch_refclk(dev);
14538
14539         drm_helper_move_panel_connectors_to_head(dev);
14540 }
14541
14542 static void intel_user_framebuffer_destroy(struct drm_framebuffer *fb)
14543 {
14544         struct drm_device *dev = fb->dev;
14545         struct intel_framebuffer *intel_fb = to_intel_framebuffer(fb);
14546
14547         drm_framebuffer_cleanup(fb);
14548         mutex_lock(&dev->struct_mutex);
14549         WARN_ON(!intel_fb->obj->framebuffer_references--);
14550         drm_gem_object_unreference(&intel_fb->obj->base);
14551         mutex_unlock(&dev->struct_mutex);
14552         kfree(intel_fb);
14553 }
14554
14555 static int intel_user_framebuffer_create_handle(struct drm_framebuffer *fb,
14556                                                 struct drm_file *file,
14557                                                 unsigned int *handle)
14558 {
14559         struct intel_framebuffer *intel_fb = to_intel_framebuffer(fb);
14560         struct drm_i915_gem_object *obj = intel_fb->obj;
14561
14562         if (obj->userptr.mm) {
14563                 DRM_DEBUG("attempting to use a userptr for a framebuffer, denied\n");
14564                 return -EINVAL;
14565         }
14566
14567         return drm_gem_handle_create(file, &obj->base, handle);
14568 }
14569
14570 static int intel_user_framebuffer_dirty(struct drm_framebuffer *fb,
14571                                         struct drm_file *file,
14572                                         unsigned flags, unsigned color,
14573                                         struct drm_clip_rect *clips,
14574                                         unsigned num_clips)
14575 {
14576         struct drm_device *dev = fb->dev;
14577         struct intel_framebuffer *intel_fb = to_intel_framebuffer(fb);
14578         struct drm_i915_gem_object *obj = intel_fb->obj;
14579
14580         mutex_lock(&dev->struct_mutex);
14581         intel_fb_obj_flush(obj, false, ORIGIN_DIRTYFB);
14582         mutex_unlock(&dev->struct_mutex);
14583
14584         return 0;
14585 }
14586
14587 static const struct drm_framebuffer_funcs intel_fb_funcs = {
14588         .destroy = intel_user_framebuffer_destroy,
14589         .create_handle = intel_user_framebuffer_create_handle,
14590         .dirty = intel_user_framebuffer_dirty,
14591 };
14592
14593 static
14594 u32 intel_fb_pitch_limit(struct drm_device *dev, uint64_t fb_modifier,
14595                          uint32_t pixel_format)
14596 {
14597         u32 gen = INTEL_INFO(dev)->gen;
14598
14599         if (gen >= 9) {
14600                 /* "The stride in bytes must not exceed the of the size of 8K
14601                  *  pixels and 32K bytes."
14602                  */
14603                  return min(8192*drm_format_plane_cpp(pixel_format, 0), 32768);
14604         } else if (gen >= 5 && !IS_VALLEYVIEW(dev) && !IS_CHERRYVIEW(dev)) {
14605                 return 32*1024;
14606         } else if (gen >= 4) {
14607                 if (fb_modifier == I915_FORMAT_MOD_X_TILED)
14608                         return 16*1024;
14609                 else
14610                         return 32*1024;
14611         } else if (gen >= 3) {
14612                 if (fb_modifier == I915_FORMAT_MOD_X_TILED)
14613                         return 8*1024;
14614                 else
14615                         return 16*1024;
14616         } else {
14617                 /* XXX DSPC is limited to 4k tiled */
14618                 return 8*1024;
14619         }
14620 }
14621
14622 static int intel_framebuffer_init(struct drm_device *dev,
14623                                   struct intel_framebuffer *intel_fb,
14624                                   struct drm_mode_fb_cmd2 *mode_cmd,
14625                                   struct drm_i915_gem_object *obj)
14626 {
14627         unsigned int aligned_height;
14628         int ret;
14629         u32 pitch_limit, stride_alignment;
14630
14631         WARN_ON(!mutex_is_locked(&dev->struct_mutex));
14632
14633         if (mode_cmd->flags & DRM_MODE_FB_MODIFIERS) {
14634                 /* Enforce that fb modifier and tiling mode match, but only for
14635                  * X-tiled. This is needed for FBC. */
14636                 if (!!(obj->tiling_mode == I915_TILING_X) !=
14637                     !!(mode_cmd->modifier[0] == I915_FORMAT_MOD_X_TILED)) {
14638                         DRM_DEBUG("tiling_mode doesn't match fb modifier\n");
14639                         return -EINVAL;
14640                 }
14641         } else {
14642                 if (obj->tiling_mode == I915_TILING_X)
14643                         mode_cmd->modifier[0] = I915_FORMAT_MOD_X_TILED;
14644                 else if (obj->tiling_mode == I915_TILING_Y) {
14645                         DRM_DEBUG("No Y tiling for legacy addfb\n");
14646                         return -EINVAL;
14647                 }
14648         }
14649
14650         /* Passed in modifier sanity checking. */
14651         switch (mode_cmd->modifier[0]) {
14652         case I915_FORMAT_MOD_Y_TILED:
14653         case I915_FORMAT_MOD_Yf_TILED:
14654                 if (INTEL_INFO(dev)->gen < 9) {
14655                         DRM_DEBUG("Unsupported tiling 0x%llx!\n",
14656                                   mode_cmd->modifier[0]);
14657                         return -EINVAL;
14658                 }
14659         case DRM_FORMAT_MOD_NONE:
14660         case I915_FORMAT_MOD_X_TILED:
14661                 break;
14662         default:
14663                 DRM_DEBUG("Unsupported fb modifier 0x%llx!\n",
14664                           mode_cmd->modifier[0]);
14665                 return -EINVAL;
14666         }
14667
14668         stride_alignment = intel_fb_stride_alignment(dev, mode_cmd->modifier[0],
14669                                                      mode_cmd->pixel_format);
14670         if (mode_cmd->pitches[0] & (stride_alignment - 1)) {
14671                 DRM_DEBUG("pitch (%d) must be at least %u byte aligned\n",
14672                           mode_cmd->pitches[0], stride_alignment);
14673                 return -EINVAL;
14674         }
14675
14676         pitch_limit = intel_fb_pitch_limit(dev, mode_cmd->modifier[0],
14677                                            mode_cmd->pixel_format);
14678         if (mode_cmd->pitches[0] > pitch_limit) {
14679                 DRM_DEBUG("%s pitch (%u) must be at less than %d\n",
14680                           mode_cmd->modifier[0] != DRM_FORMAT_MOD_NONE ?
14681                           "tiled" : "linear",
14682                           mode_cmd->pitches[0], pitch_limit);
14683                 return -EINVAL;
14684         }
14685
14686         if (mode_cmd->modifier[0] == I915_FORMAT_MOD_X_TILED &&
14687             mode_cmd->pitches[0] != obj->stride) {
14688                 DRM_DEBUG("pitch (%d) must match tiling stride (%d)\n",
14689                           mode_cmd->pitches[0], obj->stride);
14690                 return -EINVAL;
14691         }
14692
14693         /* Reject formats not supported by any plane early. */
14694         switch (mode_cmd->pixel_format) {
14695         case DRM_FORMAT_C8:
14696         case DRM_FORMAT_RGB565:
14697         case DRM_FORMAT_XRGB8888:
14698         case DRM_FORMAT_ARGB8888:
14699                 break;
14700         case DRM_FORMAT_XRGB1555:
14701                 if (INTEL_INFO(dev)->gen > 3) {
14702                         DRM_DEBUG("unsupported pixel format: %s\n",
14703                                   drm_get_format_name(mode_cmd->pixel_format));
14704                         return -EINVAL;
14705                 }
14706                 break;
14707         case DRM_FORMAT_ABGR8888:
14708                 if (!IS_VALLEYVIEW(dev) && !IS_CHERRYVIEW(dev) &&
14709                     INTEL_INFO(dev)->gen < 9) {
14710                         DRM_DEBUG("unsupported pixel format: %s\n",
14711                                   drm_get_format_name(mode_cmd->pixel_format));
14712                         return -EINVAL;
14713                 }
14714                 break;
14715         case DRM_FORMAT_XBGR8888:
14716         case DRM_FORMAT_XRGB2101010:
14717         case DRM_FORMAT_XBGR2101010:
14718                 if (INTEL_INFO(dev)->gen < 4) {
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_ABGR2101010:
14725                 if (!IS_VALLEYVIEW(dev) && !IS_CHERRYVIEW(dev)) {
14726                         DRM_DEBUG("unsupported pixel format: %s\n",
14727                                   drm_get_format_name(mode_cmd->pixel_format));
14728                         return -EINVAL;
14729                 }
14730                 break;
14731         case DRM_FORMAT_YUYV:
14732         case DRM_FORMAT_UYVY:
14733         case DRM_FORMAT_YVYU:
14734         case DRM_FORMAT_VYUY:
14735                 if (INTEL_INFO(dev)->gen < 5) {
14736                         DRM_DEBUG("unsupported pixel format: %s\n",
14737                                   drm_get_format_name(mode_cmd->pixel_format));
14738                         return -EINVAL;
14739                 }
14740                 break;
14741         default:
14742                 DRM_DEBUG("unsupported pixel format: %s\n",
14743                           drm_get_format_name(mode_cmd->pixel_format));
14744                 return -EINVAL;
14745         }
14746
14747         /* FIXME need to adjust LINOFF/TILEOFF accordingly. */
14748         if (mode_cmd->offsets[0] != 0)
14749                 return -EINVAL;
14750
14751         aligned_height = intel_fb_align_height(dev, mode_cmd->height,
14752                                                mode_cmd->pixel_format,
14753                                                mode_cmd->modifier[0]);
14754         /* FIXME drm helper for size checks (especially planar formats)? */
14755         if (obj->base.size < aligned_height * mode_cmd->pitches[0])
14756                 return -EINVAL;
14757
14758         drm_helper_mode_fill_fb_struct(&intel_fb->base, mode_cmd);
14759         intel_fb->obj = obj;
14760         intel_fb->obj->framebuffer_references++;
14761
14762         ret = drm_framebuffer_init(dev, &intel_fb->base, &intel_fb_funcs);
14763         if (ret) {
14764                 DRM_ERROR("framebuffer init failed %d\n", ret);
14765                 return ret;
14766         }
14767
14768         return 0;
14769 }
14770
14771 static struct drm_framebuffer *
14772 intel_user_framebuffer_create(struct drm_device *dev,
14773                               struct drm_file *filp,
14774                               const struct drm_mode_fb_cmd2 *user_mode_cmd)
14775 {
14776         struct drm_framebuffer *fb;
14777         struct drm_i915_gem_object *obj;
14778         struct drm_mode_fb_cmd2 mode_cmd = *user_mode_cmd;
14779
14780         obj = to_intel_bo(drm_gem_object_lookup(dev, filp,
14781                                                 mode_cmd.handles[0]));
14782         if (&obj->base == NULL)
14783                 return ERR_PTR(-ENOENT);
14784
14785         fb = intel_framebuffer_create(dev, &mode_cmd, obj);
14786         if (IS_ERR(fb))
14787                 drm_gem_object_unreference_unlocked(&obj->base);
14788
14789         return fb;
14790 }
14791
14792 #ifndef CONFIG_DRM_FBDEV_EMULATION
14793 static inline void intel_fbdev_output_poll_changed(struct drm_device *dev)
14794 {
14795 }
14796 #endif
14797
14798 static const struct drm_mode_config_funcs intel_mode_funcs = {
14799         .fb_create = intel_user_framebuffer_create,
14800         .output_poll_changed = intel_fbdev_output_poll_changed,
14801         .atomic_check = intel_atomic_check,
14802         .atomic_commit = intel_atomic_commit,
14803         .atomic_state_alloc = intel_atomic_state_alloc,
14804         .atomic_state_clear = intel_atomic_state_clear,
14805 };
14806
14807 /* Set up chip specific display functions */
14808 static void intel_init_display(struct drm_device *dev)
14809 {
14810         struct drm_i915_private *dev_priv = dev->dev_private;
14811
14812         if (HAS_PCH_SPLIT(dev) || IS_G4X(dev))
14813                 dev_priv->display.find_dpll = g4x_find_best_dpll;
14814         else if (IS_CHERRYVIEW(dev))
14815                 dev_priv->display.find_dpll = chv_find_best_dpll;
14816         else if (IS_VALLEYVIEW(dev))
14817                 dev_priv->display.find_dpll = vlv_find_best_dpll;
14818         else if (IS_PINEVIEW(dev))
14819                 dev_priv->display.find_dpll = pnv_find_best_dpll;
14820         else
14821                 dev_priv->display.find_dpll = i9xx_find_best_dpll;
14822
14823         if (INTEL_INFO(dev)->gen >= 9) {
14824                 dev_priv->display.get_pipe_config = haswell_get_pipe_config;
14825                 dev_priv->display.get_initial_plane_config =
14826                         skylake_get_initial_plane_config;
14827                 dev_priv->display.crtc_compute_clock =
14828                         haswell_crtc_compute_clock;
14829                 dev_priv->display.crtc_enable = haswell_crtc_enable;
14830                 dev_priv->display.crtc_disable = haswell_crtc_disable;
14831                 dev_priv->display.update_primary_plane =
14832                         skylake_update_primary_plane;
14833         } else if (HAS_DDI(dev)) {
14834                 dev_priv->display.get_pipe_config = haswell_get_pipe_config;
14835                 dev_priv->display.get_initial_plane_config =
14836                         ironlake_get_initial_plane_config;
14837                 dev_priv->display.crtc_compute_clock =
14838                         haswell_crtc_compute_clock;
14839                 dev_priv->display.crtc_enable = haswell_crtc_enable;
14840                 dev_priv->display.crtc_disable = haswell_crtc_disable;
14841                 dev_priv->display.update_primary_plane =
14842                         ironlake_update_primary_plane;
14843         } else if (HAS_PCH_SPLIT(dev)) {
14844                 dev_priv->display.get_pipe_config = ironlake_get_pipe_config;
14845                 dev_priv->display.get_initial_plane_config =
14846                         ironlake_get_initial_plane_config;
14847                 dev_priv->display.crtc_compute_clock =
14848                         ironlake_crtc_compute_clock;
14849                 dev_priv->display.crtc_enable = ironlake_crtc_enable;
14850                 dev_priv->display.crtc_disable = ironlake_crtc_disable;
14851                 dev_priv->display.update_primary_plane =
14852                         ironlake_update_primary_plane;
14853         } else if (IS_VALLEYVIEW(dev) || IS_CHERRYVIEW(dev)) {
14854                 dev_priv->display.get_pipe_config = i9xx_get_pipe_config;
14855                 dev_priv->display.get_initial_plane_config =
14856                         i9xx_get_initial_plane_config;
14857                 dev_priv->display.crtc_compute_clock = i9xx_crtc_compute_clock;
14858                 dev_priv->display.crtc_enable = valleyview_crtc_enable;
14859                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
14860                 dev_priv->display.update_primary_plane =
14861                         i9xx_update_primary_plane;
14862         } else {
14863                 dev_priv->display.get_pipe_config = i9xx_get_pipe_config;
14864                 dev_priv->display.get_initial_plane_config =
14865                         i9xx_get_initial_plane_config;
14866                 dev_priv->display.crtc_compute_clock = i9xx_crtc_compute_clock;
14867                 dev_priv->display.crtc_enable = i9xx_crtc_enable;
14868                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
14869                 dev_priv->display.update_primary_plane =
14870                         i9xx_update_primary_plane;
14871         }
14872
14873         /* Returns the core display clock speed */
14874         if (IS_SKYLAKE(dev) || IS_KABYLAKE(dev))
14875                 dev_priv->display.get_display_clock_speed =
14876                         skylake_get_display_clock_speed;
14877         else if (IS_BROXTON(dev))
14878                 dev_priv->display.get_display_clock_speed =
14879                         broxton_get_display_clock_speed;
14880         else if (IS_BROADWELL(dev))
14881                 dev_priv->display.get_display_clock_speed =
14882                         broadwell_get_display_clock_speed;
14883         else if (IS_HASWELL(dev))
14884                 dev_priv->display.get_display_clock_speed =
14885                         haswell_get_display_clock_speed;
14886         else if (IS_VALLEYVIEW(dev) || IS_CHERRYVIEW(dev))
14887                 dev_priv->display.get_display_clock_speed =
14888                         valleyview_get_display_clock_speed;
14889         else if (IS_GEN5(dev))
14890                 dev_priv->display.get_display_clock_speed =
14891                         ilk_get_display_clock_speed;
14892         else if (IS_I945G(dev) || IS_BROADWATER(dev) ||
14893                  IS_GEN6(dev) || IS_IVYBRIDGE(dev))
14894                 dev_priv->display.get_display_clock_speed =
14895                         i945_get_display_clock_speed;
14896         else if (IS_GM45(dev))
14897                 dev_priv->display.get_display_clock_speed =
14898                         gm45_get_display_clock_speed;
14899         else if (IS_CRESTLINE(dev))
14900                 dev_priv->display.get_display_clock_speed =
14901                         i965gm_get_display_clock_speed;
14902         else if (IS_PINEVIEW(dev))
14903                 dev_priv->display.get_display_clock_speed =
14904                         pnv_get_display_clock_speed;
14905         else if (IS_G33(dev) || IS_G4X(dev))
14906                 dev_priv->display.get_display_clock_speed =
14907                         g33_get_display_clock_speed;
14908         else if (IS_I915G(dev))
14909                 dev_priv->display.get_display_clock_speed =
14910                         i915_get_display_clock_speed;
14911         else if (IS_I945GM(dev) || IS_845G(dev))
14912                 dev_priv->display.get_display_clock_speed =
14913                         i9xx_misc_get_display_clock_speed;
14914         else if (IS_I915GM(dev))
14915                 dev_priv->display.get_display_clock_speed =
14916                         i915gm_get_display_clock_speed;
14917         else if (IS_I865G(dev))
14918                 dev_priv->display.get_display_clock_speed =
14919                         i865_get_display_clock_speed;
14920         else if (IS_I85X(dev))
14921                 dev_priv->display.get_display_clock_speed =
14922                         i85x_get_display_clock_speed;
14923         else { /* 830 */
14924                 WARN(!IS_I830(dev), "Unknown platform. Assuming 133 MHz CDCLK\n");
14925                 dev_priv->display.get_display_clock_speed =
14926                         i830_get_display_clock_speed;
14927         }
14928
14929         if (IS_GEN5(dev)) {
14930                 dev_priv->display.fdi_link_train = ironlake_fdi_link_train;
14931         } else if (IS_GEN6(dev)) {
14932                 dev_priv->display.fdi_link_train = gen6_fdi_link_train;
14933         } else if (IS_IVYBRIDGE(dev)) {
14934                 /* FIXME: detect B0+ stepping and use auto training */
14935                 dev_priv->display.fdi_link_train = ivb_manual_fdi_link_train;
14936         } else if (IS_HASWELL(dev) || IS_BROADWELL(dev)) {
14937                 dev_priv->display.fdi_link_train = hsw_fdi_link_train;
14938                 if (IS_BROADWELL(dev)) {
14939                         dev_priv->display.modeset_commit_cdclk =
14940                                 broadwell_modeset_commit_cdclk;
14941                         dev_priv->display.modeset_calc_cdclk =
14942                                 broadwell_modeset_calc_cdclk;
14943                 }
14944         } else if (IS_VALLEYVIEW(dev) || IS_CHERRYVIEW(dev)) {
14945                 dev_priv->display.modeset_commit_cdclk =
14946                         valleyview_modeset_commit_cdclk;
14947                 dev_priv->display.modeset_calc_cdclk =
14948                         valleyview_modeset_calc_cdclk;
14949         } else if (IS_BROXTON(dev)) {
14950                 dev_priv->display.modeset_commit_cdclk =
14951                         broxton_modeset_commit_cdclk;
14952                 dev_priv->display.modeset_calc_cdclk =
14953                         broxton_modeset_calc_cdclk;
14954         }
14955
14956         switch (INTEL_INFO(dev)->gen) {
14957         case 2:
14958                 dev_priv->display.queue_flip = intel_gen2_queue_flip;
14959                 break;
14960
14961         case 3:
14962                 dev_priv->display.queue_flip = intel_gen3_queue_flip;
14963                 break;
14964
14965         case 4:
14966         case 5:
14967                 dev_priv->display.queue_flip = intel_gen4_queue_flip;
14968                 break;
14969
14970         case 6:
14971                 dev_priv->display.queue_flip = intel_gen6_queue_flip;
14972                 break;
14973         case 7:
14974         case 8: /* FIXME(BDW): Check that the gen8 RCS flip works. */
14975                 dev_priv->display.queue_flip = intel_gen7_queue_flip;
14976                 break;
14977         case 9:
14978                 /* Drop through - unsupported since execlist only. */
14979         default:
14980                 /* Default just returns -ENODEV to indicate unsupported */
14981                 dev_priv->display.queue_flip = intel_default_queue_flip;
14982         }
14983
14984         mutex_init(&dev_priv->pps_mutex);
14985 }
14986
14987 /*
14988  * Some BIOSes insist on assuming the GPU's pipe A is enabled at suspend,
14989  * resume, or other times.  This quirk makes sure that's the case for
14990  * affected systems.
14991  */
14992 static void quirk_pipea_force(struct drm_device *dev)
14993 {
14994         struct drm_i915_private *dev_priv = dev->dev_private;
14995
14996         dev_priv->quirks |= QUIRK_PIPEA_FORCE;
14997         DRM_INFO("applying pipe a force quirk\n");
14998 }
14999
15000 static void quirk_pipeb_force(struct drm_device *dev)
15001 {
15002         struct drm_i915_private *dev_priv = dev->dev_private;
15003
15004         dev_priv->quirks |= QUIRK_PIPEB_FORCE;
15005         DRM_INFO("applying pipe b force quirk\n");
15006 }
15007
15008 /*
15009  * Some machines (Lenovo U160) do not work with SSC on LVDS for some reason
15010  */
15011 static void quirk_ssc_force_disable(struct drm_device *dev)
15012 {
15013         struct drm_i915_private *dev_priv = dev->dev_private;
15014         dev_priv->quirks |= QUIRK_LVDS_SSC_DISABLE;
15015         DRM_INFO("applying lvds SSC disable quirk\n");
15016 }
15017
15018 /*
15019  * A machine (e.g. Acer Aspire 5734Z) may need to invert the panel backlight
15020  * brightness value
15021  */
15022 static void quirk_invert_brightness(struct drm_device *dev)
15023 {
15024         struct drm_i915_private *dev_priv = dev->dev_private;
15025         dev_priv->quirks |= QUIRK_INVERT_BRIGHTNESS;
15026         DRM_INFO("applying inverted panel brightness quirk\n");
15027 }
15028
15029 /* Some VBT's incorrectly indicate no backlight is present */
15030 static void quirk_backlight_present(struct drm_device *dev)
15031 {
15032         struct drm_i915_private *dev_priv = dev->dev_private;
15033         dev_priv->quirks |= QUIRK_BACKLIGHT_PRESENT;
15034         DRM_INFO("applying backlight present quirk\n");
15035 }
15036
15037 struct intel_quirk {
15038         int device;
15039         int subsystem_vendor;
15040         int subsystem_device;
15041         void (*hook)(struct drm_device *dev);
15042 };
15043
15044 /* For systems that don't have a meaningful PCI subdevice/subvendor ID */
15045 struct intel_dmi_quirk {
15046         void (*hook)(struct drm_device *dev);
15047         const struct dmi_system_id (*dmi_id_list)[];
15048 };
15049
15050 static int intel_dmi_reverse_brightness(const struct dmi_system_id *id)
15051 {
15052         DRM_INFO("Backlight polarity reversed on %s\n", id->ident);
15053         return 1;
15054 }
15055
15056 static const struct intel_dmi_quirk intel_dmi_quirks[] = {
15057         {
15058                 .dmi_id_list = &(const struct dmi_system_id[]) {
15059                         {
15060                                 .callback = intel_dmi_reverse_brightness,
15061                                 .ident = "NCR Corporation",
15062                                 .matches = {DMI_MATCH(DMI_SYS_VENDOR, "NCR Corporation"),
15063                                             DMI_MATCH(DMI_PRODUCT_NAME, ""),
15064                                 },
15065                         },
15066                         { }  /* terminating entry */
15067                 },
15068                 .hook = quirk_invert_brightness,
15069         },
15070 };
15071
15072 static struct intel_quirk intel_quirks[] = {
15073         /* Toshiba Protege R-205, S-209 needs pipe A force quirk */
15074         { 0x2592, 0x1179, 0x0001, quirk_pipea_force },
15075
15076         /* ThinkPad T60 needs pipe A force quirk (bug #16494) */
15077         { 0x2782, 0x17aa, 0x201a, quirk_pipea_force },
15078
15079         /* 830 needs to leave pipe A & dpll A up */
15080         { 0x3577, PCI_ANY_ID, PCI_ANY_ID, quirk_pipea_force },
15081
15082         /* 830 needs to leave pipe B & dpll B up */
15083         { 0x3577, PCI_ANY_ID, PCI_ANY_ID, quirk_pipeb_force },
15084
15085         /* Lenovo U160 cannot use SSC on LVDS */
15086         { 0x0046, 0x17aa, 0x3920, quirk_ssc_force_disable },
15087
15088         /* Sony Vaio Y cannot use SSC on LVDS */
15089         { 0x0046, 0x104d, 0x9076, quirk_ssc_force_disable },
15090
15091         /* Acer Aspire 5734Z must invert backlight brightness */
15092         { 0x2a42, 0x1025, 0x0459, quirk_invert_brightness },
15093
15094         /* Acer/eMachines G725 */
15095         { 0x2a42, 0x1025, 0x0210, quirk_invert_brightness },
15096
15097         /* Acer/eMachines e725 */
15098         { 0x2a42, 0x1025, 0x0212, quirk_invert_brightness },
15099
15100         /* Acer/Packard Bell NCL20 */
15101         { 0x2a42, 0x1025, 0x034b, quirk_invert_brightness },
15102
15103         /* Acer Aspire 4736Z */
15104         { 0x2a42, 0x1025, 0x0260, quirk_invert_brightness },
15105
15106         /* Acer Aspire 5336 */
15107         { 0x2a42, 0x1025, 0x048a, quirk_invert_brightness },
15108
15109         /* Acer C720 and C720P Chromebooks (Celeron 2955U) have backlights */
15110         { 0x0a06, 0x1025, 0x0a11, quirk_backlight_present },
15111
15112         /* Acer C720 Chromebook (Core i3 4005U) */
15113         { 0x0a16, 0x1025, 0x0a11, quirk_backlight_present },
15114
15115         /* Apple Macbook 2,1 (Core 2 T7400) */
15116         { 0x27a2, 0x8086, 0x7270, quirk_backlight_present },
15117
15118         /* Apple Macbook 4,1 */
15119         { 0x2a02, 0x106b, 0x00a1, quirk_backlight_present },
15120
15121         /* Toshiba CB35 Chromebook (Celeron 2955U) */
15122         { 0x0a06, 0x1179, 0x0a88, quirk_backlight_present },
15123
15124         /* HP Chromebook 14 (Celeron 2955U) */
15125         { 0x0a06, 0x103c, 0x21ed, quirk_backlight_present },
15126
15127         /* Dell Chromebook 11 */
15128         { 0x0a06, 0x1028, 0x0a35, quirk_backlight_present },
15129
15130         /* Dell Chromebook 11 (2015 version) */
15131         { 0x0a16, 0x1028, 0x0a35, quirk_backlight_present },
15132 };
15133
15134 static void intel_init_quirks(struct drm_device *dev)
15135 {
15136         struct pci_dev *d = dev->pdev;
15137         int i;
15138
15139         for (i = 0; i < ARRAY_SIZE(intel_quirks); i++) {
15140                 struct intel_quirk *q = &intel_quirks[i];
15141
15142                 if (d->device == q->device &&
15143                     (d->subsystem_vendor == q->subsystem_vendor ||
15144                      q->subsystem_vendor == PCI_ANY_ID) &&
15145                     (d->subsystem_device == q->subsystem_device ||
15146                      q->subsystem_device == PCI_ANY_ID))
15147                         q->hook(dev);
15148         }
15149         for (i = 0; i < ARRAY_SIZE(intel_dmi_quirks); i++) {
15150                 if (dmi_check_system(*intel_dmi_quirks[i].dmi_id_list) != 0)
15151                         intel_dmi_quirks[i].hook(dev);
15152         }
15153 }
15154
15155 /* Disable the VGA plane that we never use */
15156 static void i915_disable_vga(struct drm_device *dev)
15157 {
15158         struct drm_i915_private *dev_priv = dev->dev_private;
15159         u8 sr1;
15160         i915_reg_t vga_reg = i915_vgacntrl_reg(dev);
15161
15162         /* WaEnableVGAAccessThroughIOPort:ctg,elk,ilk,snb,ivb,vlv,hsw */
15163         vga_get_uninterruptible(dev->pdev, VGA_RSRC_LEGACY_IO);
15164         outb(SR01, VGA_SR_INDEX);
15165         sr1 = inb(VGA_SR_DATA);
15166         outb(sr1 | 1<<5, VGA_SR_DATA);
15167         vga_put(dev->pdev, VGA_RSRC_LEGACY_IO);
15168         udelay(300);
15169
15170         I915_WRITE(vga_reg, VGA_DISP_DISABLE);
15171         POSTING_READ(vga_reg);
15172 }
15173
15174 void intel_modeset_init_hw(struct drm_device *dev)
15175 {
15176         intel_update_cdclk(dev);
15177         intel_prepare_ddi(dev);
15178         intel_init_clock_gating(dev);
15179         intel_enable_gt_powersave(dev);
15180 }
15181
15182 void intel_modeset_init(struct drm_device *dev)
15183 {
15184         struct drm_i915_private *dev_priv = dev->dev_private;
15185         int sprite, ret;
15186         enum pipe pipe;
15187         struct intel_crtc *crtc;
15188
15189         drm_mode_config_init(dev);
15190
15191         dev->mode_config.min_width = 0;
15192         dev->mode_config.min_height = 0;
15193
15194         dev->mode_config.preferred_depth = 24;
15195         dev->mode_config.prefer_shadow = 1;
15196
15197         dev->mode_config.allow_fb_modifiers = true;
15198
15199         dev->mode_config.funcs = &intel_mode_funcs;
15200
15201         intel_init_quirks(dev);
15202
15203         intel_init_pm(dev);
15204
15205         if (INTEL_INFO(dev)->num_pipes == 0)
15206                 return;
15207
15208         /*
15209          * There may be no VBT; and if the BIOS enabled SSC we can
15210          * just keep using it to avoid unnecessary flicker.  Whereas if the
15211          * BIOS isn't using it, don't assume it will work even if the VBT
15212          * indicates as much.
15213          */
15214         if (HAS_PCH_IBX(dev) || HAS_PCH_CPT(dev)) {
15215                 bool bios_lvds_use_ssc = !!(I915_READ(PCH_DREF_CONTROL) &
15216                                             DREF_SSC1_ENABLE);
15217
15218                 if (dev_priv->vbt.lvds_use_ssc != bios_lvds_use_ssc) {
15219                         DRM_DEBUG_KMS("SSC %sabled by BIOS, overriding VBT which says %sabled\n",
15220                                      bios_lvds_use_ssc ? "en" : "dis",
15221                                      dev_priv->vbt.lvds_use_ssc ? "en" : "dis");
15222                         dev_priv->vbt.lvds_use_ssc = bios_lvds_use_ssc;
15223                 }
15224         }
15225
15226         intel_init_display(dev);
15227         intel_init_audio(dev);
15228
15229         if (IS_GEN2(dev)) {
15230                 dev->mode_config.max_width = 2048;
15231                 dev->mode_config.max_height = 2048;
15232         } else if (IS_GEN3(dev)) {
15233                 dev->mode_config.max_width = 4096;
15234                 dev->mode_config.max_height = 4096;
15235         } else {
15236                 dev->mode_config.max_width = 8192;
15237                 dev->mode_config.max_height = 8192;
15238         }
15239
15240         if (IS_845G(dev) || IS_I865G(dev)) {
15241                 dev->mode_config.cursor_width = IS_845G(dev) ? 64 : 512;
15242                 dev->mode_config.cursor_height = 1023;
15243         } else if (IS_GEN2(dev)) {
15244                 dev->mode_config.cursor_width = GEN2_CURSOR_WIDTH;
15245                 dev->mode_config.cursor_height = GEN2_CURSOR_HEIGHT;
15246         } else {
15247                 dev->mode_config.cursor_width = MAX_CURSOR_WIDTH;
15248                 dev->mode_config.cursor_height = MAX_CURSOR_HEIGHT;
15249         }
15250
15251         dev->mode_config.fb_base = dev_priv->gtt.mappable_base;
15252
15253         DRM_DEBUG_KMS("%d display pipe%s available.\n",
15254                       INTEL_INFO(dev)->num_pipes,
15255                       INTEL_INFO(dev)->num_pipes > 1 ? "s" : "");
15256
15257         for_each_pipe(dev_priv, pipe) {
15258                 intel_crtc_init(dev, pipe);
15259                 for_each_sprite(dev_priv, pipe, sprite) {
15260                         ret = intel_plane_init(dev, pipe, sprite);
15261                         if (ret)
15262                                 DRM_DEBUG_KMS("pipe %c sprite %c init failed: %d\n",
15263                                               pipe_name(pipe), sprite_name(pipe, sprite), ret);
15264                 }
15265         }
15266
15267         intel_update_czclk(dev_priv);
15268         intel_update_cdclk(dev);
15269
15270         intel_shared_dpll_init(dev);
15271
15272         /* Just disable it once at startup */
15273         i915_disable_vga(dev);
15274         intel_setup_outputs(dev);
15275
15276         drm_modeset_lock_all(dev);
15277         intel_modeset_setup_hw_state(dev);
15278         drm_modeset_unlock_all(dev);
15279
15280         for_each_intel_crtc(dev, crtc) {
15281                 struct intel_initial_plane_config plane_config = {};
15282
15283                 if (!crtc->active)
15284                         continue;
15285
15286                 /*
15287                  * Note that reserving the BIOS fb up front prevents us
15288                  * from stuffing other stolen allocations like the ring
15289                  * on top.  This prevents some ugliness at boot time, and
15290                  * can even allow for smooth boot transitions if the BIOS
15291                  * fb is large enough for the active pipe configuration.
15292                  */
15293                 dev_priv->display.get_initial_plane_config(crtc,
15294                                                            &plane_config);
15295
15296                 /*
15297                  * If the fb is shared between multiple heads, we'll
15298                  * just get the first one.
15299                  */
15300                 intel_find_initial_plane_obj(crtc, &plane_config);
15301         }
15302 }
15303
15304 static void intel_enable_pipe_a(struct drm_device *dev)
15305 {
15306         struct intel_connector *connector;
15307         struct drm_connector *crt = NULL;
15308         struct intel_load_detect_pipe load_detect_temp;
15309         struct drm_modeset_acquire_ctx *ctx = dev->mode_config.acquire_ctx;
15310
15311         /* We can't just switch on the pipe A, we need to set things up with a
15312          * proper mode and output configuration. As a gross hack, enable pipe A
15313          * by enabling the load detect pipe once. */
15314         for_each_intel_connector(dev, connector) {
15315                 if (connector->encoder->type == INTEL_OUTPUT_ANALOG) {
15316                         crt = &connector->base;
15317                         break;
15318                 }
15319         }
15320
15321         if (!crt)
15322                 return;
15323
15324         if (intel_get_load_detect_pipe(crt, NULL, &load_detect_temp, ctx))
15325                 intel_release_load_detect_pipe(crt, &load_detect_temp, ctx);
15326 }
15327
15328 static bool
15329 intel_check_plane_mapping(struct intel_crtc *crtc)
15330 {
15331         struct drm_device *dev = crtc->base.dev;
15332         struct drm_i915_private *dev_priv = dev->dev_private;
15333         u32 val;
15334
15335         if (INTEL_INFO(dev)->num_pipes == 1)
15336                 return true;
15337
15338         val = I915_READ(DSPCNTR(!crtc->plane));
15339
15340         if ((val & DISPLAY_PLANE_ENABLE) &&
15341             (!!(val & DISPPLANE_SEL_PIPE_MASK) == crtc->pipe))
15342                 return false;
15343
15344         return true;
15345 }
15346
15347 static bool intel_crtc_has_encoders(struct intel_crtc *crtc)
15348 {
15349         struct drm_device *dev = crtc->base.dev;
15350         struct intel_encoder *encoder;
15351
15352         for_each_encoder_on_crtc(dev, &crtc->base, encoder)
15353                 return true;
15354
15355         return false;
15356 }
15357
15358 static void intel_sanitize_crtc(struct intel_crtc *crtc)
15359 {
15360         struct drm_device *dev = crtc->base.dev;
15361         struct drm_i915_private *dev_priv = dev->dev_private;
15362         i915_reg_t reg = PIPECONF(crtc->config->cpu_transcoder);
15363
15364         /* Clear any frame start delays used for debugging left by the BIOS */
15365         I915_WRITE(reg, I915_READ(reg) & ~PIPECONF_FRAME_START_DELAY_MASK);
15366
15367         /* restore vblank interrupts to correct state */
15368         drm_crtc_vblank_reset(&crtc->base);
15369         if (crtc->active) {
15370                 struct intel_plane *plane;
15371
15372                 drm_crtc_vblank_on(&crtc->base);
15373
15374                 /* Disable everything but the primary plane */
15375                 for_each_intel_plane_on_crtc(dev, crtc, plane) {
15376                         if (plane->base.type == DRM_PLANE_TYPE_PRIMARY)
15377                                 continue;
15378
15379                         plane->disable_plane(&plane->base, &crtc->base);
15380                 }
15381         }
15382
15383         /* We need to sanitize the plane -> pipe mapping first because this will
15384          * disable the crtc (and hence change the state) if it is wrong. Note
15385          * that gen4+ has a fixed plane -> pipe mapping.  */
15386         if (INTEL_INFO(dev)->gen < 4 && !intel_check_plane_mapping(crtc)) {
15387                 bool plane;
15388
15389                 DRM_DEBUG_KMS("[CRTC:%d] wrong plane connection detected!\n",
15390                               crtc->base.base.id);
15391
15392                 /* Pipe has the wrong plane attached and the plane is active.
15393                  * Temporarily change the plane mapping and disable everything
15394                  * ...  */
15395                 plane = crtc->plane;
15396                 to_intel_plane_state(crtc->base.primary->state)->visible = true;
15397                 crtc->plane = !plane;
15398                 intel_crtc_disable_noatomic(&crtc->base);
15399                 crtc->plane = plane;
15400         }
15401
15402         if (dev_priv->quirks & QUIRK_PIPEA_FORCE &&
15403             crtc->pipe == PIPE_A && !crtc->active) {
15404                 /* BIOS forgot to enable pipe A, this mostly happens after
15405                  * resume. Force-enable the pipe to fix this, the update_dpms
15406                  * call below we restore the pipe to the right state, but leave
15407                  * the required bits on. */
15408                 intel_enable_pipe_a(dev);
15409         }
15410
15411         /* Adjust the state of the output pipe according to whether we
15412          * have active connectors/encoders. */
15413         if (!intel_crtc_has_encoders(crtc))
15414                 intel_crtc_disable_noatomic(&crtc->base);
15415
15416         if (crtc->active != crtc->base.state->active) {
15417                 struct intel_encoder *encoder;
15418
15419                 /* This can happen either due to bugs in the get_hw_state
15420                  * functions or because of calls to intel_crtc_disable_noatomic,
15421                  * or because the pipe is force-enabled due to the
15422                  * pipe A quirk. */
15423                 DRM_DEBUG_KMS("[CRTC:%d] hw state adjusted, was %s, now %s\n",
15424                               crtc->base.base.id,
15425                               crtc->base.state->enable ? "enabled" : "disabled",
15426                               crtc->active ? "enabled" : "disabled");
15427
15428                 WARN_ON(drm_atomic_set_mode_for_crtc(crtc->base.state, NULL) < 0);
15429                 crtc->base.state->active = crtc->active;
15430                 crtc->base.enabled = crtc->active;
15431
15432                 /* Because we only establish the connector -> encoder ->
15433                  * crtc links if something is active, this means the
15434                  * crtc is now deactivated. Break the links. connector
15435                  * -> encoder links are only establish when things are
15436                  *  actually up, hence no need to break them. */
15437                 WARN_ON(crtc->active);
15438
15439                 for_each_encoder_on_crtc(dev, &crtc->base, encoder)
15440                         encoder->base.crtc = NULL;
15441         }
15442
15443         if (crtc->active || HAS_GMCH_DISPLAY(dev)) {
15444                 /*
15445                  * We start out with underrun reporting disabled to avoid races.
15446                  * For correct bookkeeping mark this on active crtcs.
15447                  *
15448                  * Also on gmch platforms we dont have any hardware bits to
15449                  * disable the underrun reporting. Which means we need to start
15450                  * out with underrun reporting disabled also on inactive pipes,
15451                  * since otherwise we'll complain about the garbage we read when
15452                  * e.g. coming up after runtime pm.
15453                  *
15454                  * No protection against concurrent access is required - at
15455                  * worst a fifo underrun happens which also sets this to false.
15456                  */
15457                 crtc->cpu_fifo_underrun_disabled = true;
15458                 crtc->pch_fifo_underrun_disabled = true;
15459         }
15460 }
15461
15462 static void intel_sanitize_encoder(struct intel_encoder *encoder)
15463 {
15464         struct intel_connector *connector;
15465         struct drm_device *dev = encoder->base.dev;
15466         bool active = false;
15467
15468         /* We need to check both for a crtc link (meaning that the
15469          * encoder is active and trying to read from a pipe) and the
15470          * pipe itself being active. */
15471         bool has_active_crtc = encoder->base.crtc &&
15472                 to_intel_crtc(encoder->base.crtc)->active;
15473
15474         for_each_intel_connector(dev, connector) {
15475                 if (connector->base.encoder != &encoder->base)
15476                         continue;
15477
15478                 active = true;
15479                 break;
15480         }
15481
15482         if (active && !has_active_crtc) {
15483                 DRM_DEBUG_KMS("[ENCODER:%d:%s] has active connectors but no active pipe!\n",
15484                               encoder->base.base.id,
15485                               encoder->base.name);
15486
15487                 /* Connector is active, but has no active pipe. This is
15488                  * fallout from our resume register restoring. Disable
15489                  * the encoder manually again. */
15490                 if (encoder->base.crtc) {
15491                         DRM_DEBUG_KMS("[ENCODER:%d:%s] manually disabled\n",
15492                                       encoder->base.base.id,
15493                                       encoder->base.name);
15494                         encoder->disable(encoder);
15495                         if (encoder->post_disable)
15496                                 encoder->post_disable(encoder);
15497                 }
15498                 encoder->base.crtc = NULL;
15499
15500                 /* Inconsistent output/port/pipe state happens presumably due to
15501                  * a bug in one of the get_hw_state functions. Or someplace else
15502                  * in our code, like the register restore mess on resume. Clamp
15503                  * things to off as a safer default. */
15504                 for_each_intel_connector(dev, connector) {
15505                         if (connector->encoder != encoder)
15506                                 continue;
15507                         connector->base.dpms = DRM_MODE_DPMS_OFF;
15508                         connector->base.encoder = NULL;
15509                 }
15510         }
15511         /* Enabled encoders without active connectors will be fixed in
15512          * the crtc fixup. */
15513 }
15514
15515 void i915_redisable_vga_power_on(struct drm_device *dev)
15516 {
15517         struct drm_i915_private *dev_priv = dev->dev_private;
15518         i915_reg_t vga_reg = i915_vgacntrl_reg(dev);
15519
15520         if (!(I915_READ(vga_reg) & VGA_DISP_DISABLE)) {
15521                 DRM_DEBUG_KMS("Something enabled VGA plane, disabling it\n");
15522                 i915_disable_vga(dev);
15523         }
15524 }
15525
15526 void i915_redisable_vga(struct drm_device *dev)
15527 {
15528         struct drm_i915_private *dev_priv = dev->dev_private;
15529
15530         /* This function can be called both from intel_modeset_setup_hw_state or
15531          * at a very early point in our resume sequence, where the power well
15532          * structures are not yet restored. Since this function is at a very
15533          * paranoid "someone might have enabled VGA while we were not looking"
15534          * level, just check if the power well is enabled instead of trying to
15535          * follow the "don't touch the power well if we don't need it" policy
15536          * the rest of the driver uses. */
15537         if (!intel_display_power_is_enabled(dev_priv, POWER_DOMAIN_VGA))
15538                 return;
15539
15540         i915_redisable_vga_power_on(dev);
15541 }
15542
15543 static bool primary_get_hw_state(struct intel_plane *plane)
15544 {
15545         struct drm_i915_private *dev_priv = to_i915(plane->base.dev);
15546
15547         return I915_READ(DSPCNTR(plane->plane)) & DISPLAY_PLANE_ENABLE;
15548 }
15549
15550 /* FIXME read out full plane state for all planes */
15551 static void readout_plane_state(struct intel_crtc *crtc)
15552 {
15553         struct drm_plane *primary = crtc->base.primary;
15554         struct intel_plane_state *plane_state =
15555                 to_intel_plane_state(primary->state);
15556
15557         plane_state->visible = crtc->active &&
15558                 primary_get_hw_state(to_intel_plane(primary));
15559
15560         if (plane_state->visible)
15561                 crtc->base.state->plane_mask |= 1 << drm_plane_index(primary);
15562 }
15563
15564 static void intel_modeset_readout_hw_state(struct drm_device *dev)
15565 {
15566         struct drm_i915_private *dev_priv = dev->dev_private;
15567         enum pipe pipe;
15568         struct intel_crtc *crtc;
15569         struct intel_encoder *encoder;
15570         struct intel_connector *connector;
15571         int i;
15572
15573         for_each_intel_crtc(dev, crtc) {
15574                 __drm_atomic_helper_crtc_destroy_state(&crtc->base, crtc->base.state);
15575                 memset(crtc->config, 0, sizeof(*crtc->config));
15576                 crtc->config->base.crtc = &crtc->base;
15577
15578                 crtc->active = dev_priv->display.get_pipe_config(crtc,
15579                                                                  crtc->config);
15580
15581                 crtc->base.state->active = crtc->active;
15582                 crtc->base.enabled = crtc->active;
15583
15584                 readout_plane_state(crtc);
15585
15586                 DRM_DEBUG_KMS("[CRTC:%d] hw state readout: %s\n",
15587                               crtc->base.base.id,
15588                               crtc->active ? "enabled" : "disabled");
15589         }
15590
15591         for (i = 0; i < dev_priv->num_shared_dpll; i++) {
15592                 struct intel_shared_dpll *pll = &dev_priv->shared_dplls[i];
15593
15594                 pll->on = pll->get_hw_state(dev_priv, pll,
15595                                             &pll->config.hw_state);
15596                 pll->active = 0;
15597                 pll->config.crtc_mask = 0;
15598                 for_each_intel_crtc(dev, crtc) {
15599                         if (crtc->active && intel_crtc_to_shared_dpll(crtc) == pll) {
15600                                 pll->active++;
15601                                 pll->config.crtc_mask |= 1 << crtc->pipe;
15602                         }
15603                 }
15604
15605                 DRM_DEBUG_KMS("%s hw state readout: crtc_mask 0x%08x, on %i\n",
15606                               pll->name, pll->config.crtc_mask, pll->on);
15607
15608                 if (pll->config.crtc_mask)
15609                         intel_display_power_get(dev_priv, POWER_DOMAIN_PLLS);
15610         }
15611
15612         for_each_intel_encoder(dev, encoder) {
15613                 pipe = 0;
15614
15615                 if (encoder->get_hw_state(encoder, &pipe)) {
15616                         crtc = to_intel_crtc(dev_priv->pipe_to_crtc_mapping[pipe]);
15617                         encoder->base.crtc = &crtc->base;
15618                         encoder->get_config(encoder, crtc->config);
15619                 } else {
15620                         encoder->base.crtc = NULL;
15621                 }
15622
15623                 DRM_DEBUG_KMS("[ENCODER:%d:%s] hw state readout: %s, pipe %c\n",
15624                               encoder->base.base.id,
15625                               encoder->base.name,
15626                               encoder->base.crtc ? "enabled" : "disabled",
15627                               pipe_name(pipe));
15628         }
15629
15630         for_each_intel_connector(dev, connector) {
15631                 if (connector->get_hw_state(connector)) {
15632                         connector->base.dpms = DRM_MODE_DPMS_ON;
15633                         connector->base.encoder = &connector->encoder->base;
15634                 } else {
15635                         connector->base.dpms = DRM_MODE_DPMS_OFF;
15636                         connector->base.encoder = NULL;
15637                 }
15638                 DRM_DEBUG_KMS("[CONNECTOR:%d:%s] hw state readout: %s\n",
15639                               connector->base.base.id,
15640                               connector->base.name,
15641                               connector->base.encoder ? "enabled" : "disabled");
15642         }
15643
15644         for_each_intel_crtc(dev, crtc) {
15645                 crtc->base.hwmode = crtc->config->base.adjusted_mode;
15646
15647                 memset(&crtc->base.mode, 0, sizeof(crtc->base.mode));
15648                 if (crtc->base.state->active) {
15649                         intel_mode_from_pipe_config(&crtc->base.mode, crtc->config);
15650                         intel_mode_from_pipe_config(&crtc->base.state->adjusted_mode, crtc->config);
15651                         WARN_ON(drm_atomic_set_mode_for_crtc(crtc->base.state, &crtc->base.mode));
15652
15653                         /*
15654                          * The initial mode needs to be set in order to keep
15655                          * the atomic core happy. It wants a valid mode if the
15656                          * crtc's enabled, so we do the above call.
15657                          *
15658                          * At this point some state updated by the connectors
15659                          * in their ->detect() callback has not run yet, so
15660                          * no recalculation can be done yet.
15661                          *
15662                          * Even if we could do a recalculation and modeset
15663                          * right now it would cause a double modeset if
15664                          * fbdev or userspace chooses a different initial mode.
15665                          *
15666                          * If that happens, someone indicated they wanted a
15667                          * mode change, which means it's safe to do a full
15668                          * recalculation.
15669                          */
15670                         crtc->base.state->mode.private_flags = I915_MODE_FLAG_INHERITED;
15671
15672                         drm_calc_timestamping_constants(&crtc->base, &crtc->base.hwmode);
15673                         update_scanline_offset(crtc);
15674                 }
15675         }
15676 }
15677
15678 /* Scan out the current hw modeset state,
15679  * and sanitizes it to the current state
15680  */
15681 static void
15682 intel_modeset_setup_hw_state(struct drm_device *dev)
15683 {
15684         struct drm_i915_private *dev_priv = dev->dev_private;
15685         enum pipe pipe;
15686         struct intel_crtc *crtc;
15687         struct intel_encoder *encoder;
15688         int i;
15689
15690         intel_modeset_readout_hw_state(dev);
15691
15692         /* HW state is read out, now we need to sanitize this mess. */
15693         for_each_intel_encoder(dev, encoder) {
15694                 intel_sanitize_encoder(encoder);
15695         }
15696
15697         for_each_pipe(dev_priv, pipe) {
15698                 crtc = to_intel_crtc(dev_priv->pipe_to_crtc_mapping[pipe]);
15699                 intel_sanitize_crtc(crtc);
15700                 intel_dump_pipe_config(crtc, crtc->config,
15701                                        "[setup_hw_state]");
15702         }
15703
15704         intel_modeset_update_connector_atomic_state(dev);
15705
15706         for (i = 0; i < dev_priv->num_shared_dpll; i++) {
15707                 struct intel_shared_dpll *pll = &dev_priv->shared_dplls[i];
15708
15709                 if (!pll->on || pll->active)
15710                         continue;
15711
15712                 DRM_DEBUG_KMS("%s enabled but not in use, disabling\n", pll->name);
15713
15714                 pll->disable(dev_priv, pll);
15715                 pll->on = false;
15716         }
15717
15718         if (IS_VALLEYVIEW(dev) || IS_CHERRYVIEW(dev))
15719                 vlv_wm_get_hw_state(dev);
15720         else if (IS_GEN9(dev))
15721                 skl_wm_get_hw_state(dev);
15722         else if (HAS_PCH_SPLIT(dev))
15723                 ilk_wm_get_hw_state(dev);
15724
15725         for_each_intel_crtc(dev, crtc) {
15726                 unsigned long put_domains;
15727
15728                 put_domains = modeset_get_crtc_power_domains(&crtc->base);
15729                 if (WARN_ON(put_domains))
15730                         modeset_put_power_domains(dev_priv, put_domains);
15731         }
15732         intel_display_set_init_power(dev_priv, false);
15733 }
15734
15735 void intel_display_resume(struct drm_device *dev)
15736 {
15737         struct drm_atomic_state *state = drm_atomic_state_alloc(dev);
15738         struct intel_connector *conn;
15739         struct intel_plane *plane;
15740         struct drm_crtc *crtc;
15741         int ret;
15742
15743         if (!state)
15744                 return;
15745
15746         state->acquire_ctx = dev->mode_config.acquire_ctx;
15747
15748         /* preserve complete old state, including dpll */
15749         intel_atomic_get_shared_dpll_state(state);
15750
15751         for_each_crtc(dev, crtc) {
15752                 struct drm_crtc_state *crtc_state =
15753                         drm_atomic_get_crtc_state(state, crtc);
15754
15755                 ret = PTR_ERR_OR_ZERO(crtc_state);
15756                 if (ret)
15757                         goto err;
15758
15759                 /* force a restore */
15760                 crtc_state->mode_changed = true;
15761         }
15762
15763         for_each_intel_plane(dev, plane) {
15764                 ret = PTR_ERR_OR_ZERO(drm_atomic_get_plane_state(state, &plane->base));
15765                 if (ret)
15766                         goto err;
15767         }
15768
15769         for_each_intel_connector(dev, conn) {
15770                 ret = PTR_ERR_OR_ZERO(drm_atomic_get_connector_state(state, &conn->base));
15771                 if (ret)
15772                         goto err;
15773         }
15774
15775         intel_modeset_setup_hw_state(dev);
15776
15777         i915_redisable_vga(dev);
15778         ret = drm_atomic_commit(state);
15779         if (!ret)
15780                 return;
15781
15782 err:
15783         DRM_ERROR("Restoring old state failed with %i\n", ret);
15784         drm_atomic_state_free(state);
15785 }
15786
15787 void intel_modeset_gem_init(struct drm_device *dev)
15788 {
15789         struct drm_crtc *c;
15790         struct drm_i915_gem_object *obj;
15791         int ret;
15792
15793         mutex_lock(&dev->struct_mutex);
15794         intel_init_gt_powersave(dev);
15795         mutex_unlock(&dev->struct_mutex);
15796
15797         intel_modeset_init_hw(dev);
15798
15799         intel_setup_overlay(dev);
15800
15801         /*
15802          * Make sure any fbs we allocated at startup are properly
15803          * pinned & fenced.  When we do the allocation it's too early
15804          * for this.
15805          */
15806         for_each_crtc(dev, c) {
15807                 obj = intel_fb_obj(c->primary->fb);
15808                 if (obj == NULL)
15809                         continue;
15810
15811                 mutex_lock(&dev->struct_mutex);
15812                 ret = intel_pin_and_fence_fb_obj(c->primary,
15813                                                  c->primary->fb,
15814                                                  c->primary->state);
15815                 mutex_unlock(&dev->struct_mutex);
15816                 if (ret) {
15817                         DRM_ERROR("failed to pin boot fb on pipe %d\n",
15818                                   to_intel_crtc(c)->pipe);
15819                         drm_framebuffer_unreference(c->primary->fb);
15820                         c->primary->fb = NULL;
15821                         c->primary->crtc = c->primary->state->crtc = NULL;
15822                         update_state_fb(c->primary);
15823                         c->state->plane_mask &= ~(1 << drm_plane_index(c->primary));
15824                 }
15825         }
15826
15827         intel_backlight_register(dev);
15828 }
15829
15830 void intel_connector_unregister(struct intel_connector *intel_connector)
15831 {
15832         struct drm_connector *connector = &intel_connector->base;
15833
15834         intel_panel_destroy_backlight(connector);
15835         drm_connector_unregister(connector);
15836 }
15837
15838 void intel_modeset_cleanup(struct drm_device *dev)
15839 {
15840         struct drm_i915_private *dev_priv = dev->dev_private;
15841         struct intel_connector *connector;
15842
15843         intel_disable_gt_powersave(dev);
15844
15845         intel_backlight_unregister(dev);
15846
15847         /*
15848          * Interrupts and polling as the first thing to avoid creating havoc.
15849          * Too much stuff here (turning of connectors, ...) would
15850          * experience fancy races otherwise.
15851          */
15852         intel_irq_uninstall(dev_priv);
15853
15854         /*
15855          * Due to the hpd irq storm handling the hotplug work can re-arm the
15856          * poll handlers. Hence disable polling after hpd handling is shut down.
15857          */
15858         drm_kms_helper_poll_fini(dev);
15859
15860         intel_unregister_dsm_handler();
15861
15862         intel_fbc_disable(dev_priv);
15863
15864         /* flush any delayed tasks or pending work */
15865         flush_scheduled_work();
15866
15867         /* destroy the backlight and sysfs files before encoders/connectors */
15868         for_each_intel_connector(dev, connector)
15869                 connector->unregister(connector);
15870
15871         drm_mode_config_cleanup(dev);
15872
15873         intel_cleanup_overlay(dev);
15874
15875         mutex_lock(&dev->struct_mutex);
15876         intel_cleanup_gt_powersave(dev);
15877         mutex_unlock(&dev->struct_mutex);
15878 }
15879
15880 /*
15881  * Return which encoder is currently attached for connector.
15882  */
15883 struct drm_encoder *intel_best_encoder(struct drm_connector *connector)
15884 {
15885         return &intel_attached_encoder(connector)->base;
15886 }
15887
15888 void intel_connector_attach_encoder(struct intel_connector *connector,
15889                                     struct intel_encoder *encoder)
15890 {
15891         connector->encoder = encoder;
15892         drm_mode_connector_attach_encoder(&connector->base,
15893                                           &encoder->base);
15894 }
15895
15896 /*
15897  * set vga decode state - true == enable VGA decode
15898  */
15899 int intel_modeset_vga_set_state(struct drm_device *dev, bool state)
15900 {
15901         struct drm_i915_private *dev_priv = dev->dev_private;
15902         unsigned reg = INTEL_INFO(dev)->gen >= 6 ? SNB_GMCH_CTRL : INTEL_GMCH_CTRL;
15903         u16 gmch_ctrl;
15904
15905         if (pci_read_config_word(dev_priv->bridge_dev, reg, &gmch_ctrl)) {
15906                 DRM_ERROR("failed to read control word\n");
15907                 return -EIO;
15908         }
15909
15910         if (!!(gmch_ctrl & INTEL_GMCH_VGA_DISABLE) == !state)
15911                 return 0;
15912
15913         if (state)
15914                 gmch_ctrl &= ~INTEL_GMCH_VGA_DISABLE;
15915         else
15916                 gmch_ctrl |= INTEL_GMCH_VGA_DISABLE;
15917
15918         if (pci_write_config_word(dev_priv->bridge_dev, reg, gmch_ctrl)) {
15919                 DRM_ERROR("failed to write control word\n");
15920                 return -EIO;
15921         }
15922
15923         return 0;
15924 }
15925
15926 struct intel_display_error_state {
15927
15928         u32 power_well_driver;
15929
15930         int num_transcoders;
15931
15932         struct intel_cursor_error_state {
15933                 u32 control;
15934                 u32 position;
15935                 u32 base;
15936                 u32 size;
15937         } cursor[I915_MAX_PIPES];
15938
15939         struct intel_pipe_error_state {
15940                 bool power_domain_on;
15941                 u32 source;
15942                 u32 stat;
15943         } pipe[I915_MAX_PIPES];
15944
15945         struct intel_plane_error_state {
15946                 u32 control;
15947                 u32 stride;
15948                 u32 size;
15949                 u32 pos;
15950                 u32 addr;
15951                 u32 surface;
15952                 u32 tile_offset;
15953         } plane[I915_MAX_PIPES];
15954
15955         struct intel_transcoder_error_state {
15956                 bool power_domain_on;
15957                 enum transcoder cpu_transcoder;
15958
15959                 u32 conf;
15960
15961                 u32 htotal;
15962                 u32 hblank;
15963                 u32 hsync;
15964                 u32 vtotal;
15965                 u32 vblank;
15966                 u32 vsync;
15967         } transcoder[4];
15968 };
15969
15970 struct intel_display_error_state *
15971 intel_display_capture_error_state(struct drm_device *dev)
15972 {
15973         struct drm_i915_private *dev_priv = dev->dev_private;
15974         struct intel_display_error_state *error;
15975         int transcoders[] = {
15976                 TRANSCODER_A,
15977                 TRANSCODER_B,
15978                 TRANSCODER_C,
15979                 TRANSCODER_EDP,
15980         };
15981         int i;
15982
15983         if (INTEL_INFO(dev)->num_pipes == 0)
15984                 return NULL;
15985
15986         error = kzalloc(sizeof(*error), GFP_ATOMIC);
15987         if (error == NULL)
15988                 return NULL;
15989
15990         if (IS_HASWELL(dev) || IS_BROADWELL(dev))
15991                 error->power_well_driver = I915_READ(HSW_PWR_WELL_DRIVER);
15992
15993         for_each_pipe(dev_priv, i) {
15994                 error->pipe[i].power_domain_on =
15995                         __intel_display_power_is_enabled(dev_priv,
15996                                                          POWER_DOMAIN_PIPE(i));
15997                 if (!error->pipe[i].power_domain_on)
15998                         continue;
15999
16000                 error->cursor[i].control = I915_READ(CURCNTR(i));
16001                 error->cursor[i].position = I915_READ(CURPOS(i));
16002                 error->cursor[i].base = I915_READ(CURBASE(i));
16003
16004                 error->plane[i].control = I915_READ(DSPCNTR(i));
16005                 error->plane[i].stride = I915_READ(DSPSTRIDE(i));
16006                 if (INTEL_INFO(dev)->gen <= 3) {
16007                         error->plane[i].size = I915_READ(DSPSIZE(i));
16008                         error->plane[i].pos = I915_READ(DSPPOS(i));
16009                 }
16010                 if (INTEL_INFO(dev)->gen <= 7 && !IS_HASWELL(dev))
16011                         error->plane[i].addr = I915_READ(DSPADDR(i));
16012                 if (INTEL_INFO(dev)->gen >= 4) {
16013                         error->plane[i].surface = I915_READ(DSPSURF(i));
16014                         error->plane[i].tile_offset = I915_READ(DSPTILEOFF(i));
16015                 }
16016
16017                 error->pipe[i].source = I915_READ(PIPESRC(i));
16018
16019                 if (HAS_GMCH_DISPLAY(dev))
16020                         error->pipe[i].stat = I915_READ(PIPESTAT(i));
16021         }
16022
16023         error->num_transcoders = INTEL_INFO(dev)->num_pipes;
16024         if (HAS_DDI(dev_priv->dev))
16025                 error->num_transcoders++; /* Account for eDP. */
16026
16027         for (i = 0; i < error->num_transcoders; i++) {
16028                 enum transcoder cpu_transcoder = transcoders[i];
16029
16030                 error->transcoder[i].power_domain_on =
16031                         __intel_display_power_is_enabled(dev_priv,
16032                                 POWER_DOMAIN_TRANSCODER(cpu_transcoder));
16033                 if (!error->transcoder[i].power_domain_on)
16034                         continue;
16035
16036                 error->transcoder[i].cpu_transcoder = cpu_transcoder;
16037
16038                 error->transcoder[i].conf = I915_READ(PIPECONF(cpu_transcoder));
16039                 error->transcoder[i].htotal = I915_READ(HTOTAL(cpu_transcoder));
16040                 error->transcoder[i].hblank = I915_READ(HBLANK(cpu_transcoder));
16041                 error->transcoder[i].hsync = I915_READ(HSYNC(cpu_transcoder));
16042                 error->transcoder[i].vtotal = I915_READ(VTOTAL(cpu_transcoder));
16043                 error->transcoder[i].vblank = I915_READ(VBLANK(cpu_transcoder));
16044                 error->transcoder[i].vsync = I915_READ(VSYNC(cpu_transcoder));
16045         }
16046
16047         return error;
16048 }
16049
16050 #define err_printf(e, ...) i915_error_printf(e, __VA_ARGS__)
16051
16052 void
16053 intel_display_print_error_state(struct drm_i915_error_state_buf *m,
16054                                 struct drm_device *dev,
16055                                 struct intel_display_error_state *error)
16056 {
16057         struct drm_i915_private *dev_priv = dev->dev_private;
16058         int i;
16059
16060         if (!error)
16061                 return;
16062
16063         err_printf(m, "Num Pipes: %d\n", INTEL_INFO(dev)->num_pipes);
16064         if (IS_HASWELL(dev) || IS_BROADWELL(dev))
16065                 err_printf(m, "PWR_WELL_CTL2: %08x\n",
16066                            error->power_well_driver);
16067         for_each_pipe(dev_priv, i) {
16068                 err_printf(m, "Pipe [%d]:\n", i);
16069                 err_printf(m, "  Power: %s\n",
16070                            error->pipe[i].power_domain_on ? "on" : "off");
16071                 err_printf(m, "  SRC: %08x\n", error->pipe[i].source);
16072                 err_printf(m, "  STAT: %08x\n", error->pipe[i].stat);
16073
16074                 err_printf(m, "Plane [%d]:\n", i);
16075                 err_printf(m, "  CNTR: %08x\n", error->plane[i].control);
16076                 err_printf(m, "  STRIDE: %08x\n", error->plane[i].stride);
16077                 if (INTEL_INFO(dev)->gen <= 3) {
16078                         err_printf(m, "  SIZE: %08x\n", error->plane[i].size);
16079                         err_printf(m, "  POS: %08x\n", error->plane[i].pos);
16080                 }
16081                 if (INTEL_INFO(dev)->gen <= 7 && !IS_HASWELL(dev))
16082                         err_printf(m, "  ADDR: %08x\n", error->plane[i].addr);
16083                 if (INTEL_INFO(dev)->gen >= 4) {
16084                         err_printf(m, "  SURF: %08x\n", error->plane[i].surface);
16085                         err_printf(m, "  TILEOFF: %08x\n", error->plane[i].tile_offset);
16086                 }
16087
16088                 err_printf(m, "Cursor [%d]:\n", i);
16089                 err_printf(m, "  CNTR: %08x\n", error->cursor[i].control);
16090                 err_printf(m, "  POS: %08x\n", error->cursor[i].position);
16091                 err_printf(m, "  BASE: %08x\n", error->cursor[i].base);
16092         }
16093
16094         for (i = 0; i < error->num_transcoders; i++) {
16095                 err_printf(m, "CPU transcoder: %c\n",
16096                            transcoder_name(error->transcoder[i].cpu_transcoder));
16097                 err_printf(m, "  Power: %s\n",
16098                            error->transcoder[i].power_domain_on ? "on" : "off");
16099                 err_printf(m, "  CONF: %08x\n", error->transcoder[i].conf);
16100                 err_printf(m, "  HTOTAL: %08x\n", error->transcoder[i].htotal);
16101                 err_printf(m, "  HBLANK: %08x\n", error->transcoder[i].hblank);
16102                 err_printf(m, "  HSYNC: %08x\n", error->transcoder[i].hsync);
16103                 err_printf(m, "  VTOTAL: %08x\n", error->transcoder[i].vtotal);
16104                 err_printf(m, "  VBLANK: %08x\n", error->transcoder[i].vblank);
16105                 err_printf(m, "  VSYNC: %08x\n", error->transcoder[i].vsync);
16106         }
16107 }
16108
16109 void intel_modeset_preclose(struct drm_device *dev, struct drm_file *file)
16110 {
16111         struct intel_crtc *crtc;
16112
16113         for_each_intel_crtc(dev, crtc) {
16114                 struct intel_unpin_work *work;
16115
16116                 spin_lock_irq(&dev->event_lock);
16117
16118                 work = crtc->unpin_work;
16119
16120                 if (work && work->event &&
16121                     work->event->base.file_priv == file) {
16122                         kfree(work->event);
16123                         work->event = NULL;
16124                 }
16125
16126                 spin_unlock_irq(&dev->event_lock);
16127         }
16128 }