]> git.karo-electronics.de Git - karo-tx-linux.git/blob - drivers/gpu/drm/i915/intel_display.c
Revert "drm/i915/ilk: Don't disable SSC source if it's in use"
[karo-tx-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 "intel_dsi.h"
40 #include "i915_trace.h"
41 #include <drm/drm_atomic.h>
42 #include <drm/drm_atomic_helper.h>
43 #include <drm/drm_dp_helper.h>
44 #include <drm/drm_crtc_helper.h>
45 #include <drm/drm_plane_helper.h>
46 #include <drm/drm_rect.h>
47 #include <linux/dma_remapping.h>
48 #include <linux/reservation.h>
49 #include <linux/dma-buf.h>
50
51 static bool is_mmio_work(struct intel_flip_work *work)
52 {
53         return work->mmio_work.func;
54 }
55
56 /* Primary plane formats for gen <= 3 */
57 static const uint32_t i8xx_primary_formats[] = {
58         DRM_FORMAT_C8,
59         DRM_FORMAT_RGB565,
60         DRM_FORMAT_XRGB1555,
61         DRM_FORMAT_XRGB8888,
62 };
63
64 /* Primary plane formats for gen >= 4 */
65 static const uint32_t i965_primary_formats[] = {
66         DRM_FORMAT_C8,
67         DRM_FORMAT_RGB565,
68         DRM_FORMAT_XRGB8888,
69         DRM_FORMAT_XBGR8888,
70         DRM_FORMAT_XRGB2101010,
71         DRM_FORMAT_XBGR2101010,
72 };
73
74 static const uint32_t skl_primary_formats[] = {
75         DRM_FORMAT_C8,
76         DRM_FORMAT_RGB565,
77         DRM_FORMAT_XRGB8888,
78         DRM_FORMAT_XBGR8888,
79         DRM_FORMAT_ARGB8888,
80         DRM_FORMAT_ABGR8888,
81         DRM_FORMAT_XRGB2101010,
82         DRM_FORMAT_XBGR2101010,
83         DRM_FORMAT_YUYV,
84         DRM_FORMAT_YVYU,
85         DRM_FORMAT_UYVY,
86         DRM_FORMAT_VYUY,
87 };
88
89 /* Cursor formats */
90 static const uint32_t intel_cursor_formats[] = {
91         DRM_FORMAT_ARGB8888,
92 };
93
94 static void i9xx_crtc_clock_get(struct intel_crtc *crtc,
95                                 struct intel_crtc_state *pipe_config);
96 static void ironlake_pch_clock_get(struct intel_crtc *crtc,
97                                    struct intel_crtc_state *pipe_config);
98
99 static int intel_framebuffer_init(struct drm_device *dev,
100                                   struct intel_framebuffer *ifb,
101                                   struct drm_mode_fb_cmd2 *mode_cmd,
102                                   struct drm_i915_gem_object *obj);
103 static void i9xx_set_pipeconf(struct intel_crtc *intel_crtc);
104 static void intel_set_pipe_timings(struct intel_crtc *intel_crtc);
105 static void intel_set_pipe_src_size(struct intel_crtc *intel_crtc);
106 static void intel_cpu_transcoder_set_m_n(struct intel_crtc *crtc,
107                                          struct intel_link_m_n *m_n,
108                                          struct intel_link_m_n *m2_n2);
109 static void ironlake_set_pipeconf(struct drm_crtc *crtc);
110 static void haswell_set_pipeconf(struct drm_crtc *crtc);
111 static void haswell_set_pipemisc(struct drm_crtc *crtc);
112 static void vlv_prepare_pll(struct intel_crtc *crtc,
113                             const struct intel_crtc_state *pipe_config);
114 static void chv_prepare_pll(struct intel_crtc *crtc,
115                             const struct intel_crtc_state *pipe_config);
116 static void intel_begin_crtc_commit(struct drm_crtc *, struct drm_crtc_state *);
117 static void intel_finish_crtc_commit(struct drm_crtc *, struct drm_crtc_state *);
118 static void skl_init_scalers(struct drm_device *dev, struct intel_crtc *intel_crtc,
119         struct intel_crtc_state *crtc_state);
120 static void skylake_pfit_enable(struct intel_crtc *crtc);
121 static void ironlake_pfit_disable(struct intel_crtc *crtc, bool force);
122 static void ironlake_pfit_enable(struct intel_crtc *crtc);
123 static void intel_modeset_setup_hw_state(struct drm_device *dev);
124 static void intel_pre_disable_primary_noatomic(struct drm_crtc *crtc);
125 static int ilk_max_pixel_rate(struct drm_atomic_state *state);
126 static int broxton_calc_cdclk(int max_pixclk);
127
128 struct intel_limit {
129         struct {
130                 int min, max;
131         } dot, vco, n, m, m1, m2, p, p1;
132
133         struct {
134                 int dot_limit;
135                 int p2_slow, p2_fast;
136         } p2;
137 };
138
139 /* returns HPLL frequency in kHz */
140 static int valleyview_get_vco(struct drm_i915_private *dev_priv)
141 {
142         int hpll_freq, vco_freq[] = { 800, 1600, 2000, 2400 };
143
144         /* Obtain SKU information */
145         mutex_lock(&dev_priv->sb_lock);
146         hpll_freq = vlv_cck_read(dev_priv, CCK_FUSE_REG) &
147                 CCK_FUSE_HPLL_FREQ_MASK;
148         mutex_unlock(&dev_priv->sb_lock);
149
150         return vco_freq[hpll_freq] * 1000;
151 }
152
153 int vlv_get_cck_clock(struct drm_i915_private *dev_priv,
154                       const char *name, u32 reg, int ref_freq)
155 {
156         u32 val;
157         int divider;
158
159         mutex_lock(&dev_priv->sb_lock);
160         val = vlv_cck_read(dev_priv, reg);
161         mutex_unlock(&dev_priv->sb_lock);
162
163         divider = val & CCK_FREQUENCY_VALUES;
164
165         WARN((val & CCK_FREQUENCY_STATUS) !=
166              (divider << CCK_FREQUENCY_STATUS_SHIFT),
167              "%s change in progress\n", name);
168
169         return DIV_ROUND_CLOSEST(ref_freq << 1, divider + 1);
170 }
171
172 static int vlv_get_cck_clock_hpll(struct drm_i915_private *dev_priv,
173                                   const char *name, u32 reg)
174 {
175         if (dev_priv->hpll_freq == 0)
176                 dev_priv->hpll_freq = valleyview_get_vco(dev_priv);
177
178         return vlv_get_cck_clock(dev_priv, name, reg,
179                                  dev_priv->hpll_freq);
180 }
181
182 static int
183 intel_pch_rawclk(struct drm_i915_private *dev_priv)
184 {
185         return (I915_READ(PCH_RAWCLK_FREQ) & RAWCLK_FREQ_MASK) * 1000;
186 }
187
188 static int
189 intel_vlv_hrawclk(struct drm_i915_private *dev_priv)
190 {
191         /* RAWCLK_FREQ_VLV register updated from power well code */
192         return vlv_get_cck_clock_hpll(dev_priv, "hrawclk",
193                                       CCK_DISPLAY_REF_CLOCK_CONTROL);
194 }
195
196 static int
197 intel_g4x_hrawclk(struct drm_i915_private *dev_priv)
198 {
199         uint32_t clkcfg;
200
201         /* hrawclock is 1/4 the FSB frequency */
202         clkcfg = I915_READ(CLKCFG);
203         switch (clkcfg & CLKCFG_FSB_MASK) {
204         case CLKCFG_FSB_400:
205                 return 100000;
206         case CLKCFG_FSB_533:
207                 return 133333;
208         case CLKCFG_FSB_667:
209                 return 166667;
210         case CLKCFG_FSB_800:
211                 return 200000;
212         case CLKCFG_FSB_1067:
213                 return 266667;
214         case CLKCFG_FSB_1333:
215                 return 333333;
216         /* these two are just a guess; one of them might be right */
217         case CLKCFG_FSB_1600:
218         case CLKCFG_FSB_1600_ALT:
219                 return 400000;
220         default:
221                 return 133333;
222         }
223 }
224
225 void intel_update_rawclk(struct drm_i915_private *dev_priv)
226 {
227         if (HAS_PCH_SPLIT(dev_priv))
228                 dev_priv->rawclk_freq = intel_pch_rawclk(dev_priv);
229         else if (IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv))
230                 dev_priv->rawclk_freq = intel_vlv_hrawclk(dev_priv);
231         else if (IS_G4X(dev_priv) || IS_PINEVIEW(dev_priv))
232                 dev_priv->rawclk_freq = intel_g4x_hrawclk(dev_priv);
233         else
234                 return; /* no rawclk on other platforms, or no need to know it */
235
236         DRM_DEBUG_DRIVER("rawclk rate: %d kHz\n", dev_priv->rawclk_freq);
237 }
238
239 static void intel_update_czclk(struct drm_i915_private *dev_priv)
240 {
241         if (!(IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv)))
242                 return;
243
244         dev_priv->czclk_freq = vlv_get_cck_clock_hpll(dev_priv, "czclk",
245                                                       CCK_CZ_CLOCK_CONTROL);
246
247         DRM_DEBUG_DRIVER("CZ clock rate: %d kHz\n", dev_priv->czclk_freq);
248 }
249
250 static inline u32 /* units of 100MHz */
251 intel_fdi_link_freq(struct drm_i915_private *dev_priv,
252                     const struct intel_crtc_state *pipe_config)
253 {
254         if (HAS_DDI(dev_priv))
255                 return pipe_config->port_clock; /* SPLL */
256         else if (IS_GEN5(dev_priv))
257                 return ((I915_READ(FDI_PLL_BIOS_0) & FDI_PLL_FB_CLOCK_MASK) + 2) * 10000;
258         else
259                 return 270000;
260 }
261
262 static const struct intel_limit intel_limits_i8xx_dac = {
263         .dot = { .min = 25000, .max = 350000 },
264         .vco = { .min = 908000, .max = 1512000 },
265         .n = { .min = 2, .max = 16 },
266         .m = { .min = 96, .max = 140 },
267         .m1 = { .min = 18, .max = 26 },
268         .m2 = { .min = 6, .max = 16 },
269         .p = { .min = 4, .max = 128 },
270         .p1 = { .min = 2, .max = 33 },
271         .p2 = { .dot_limit = 165000,
272                 .p2_slow = 4, .p2_fast = 2 },
273 };
274
275 static const struct intel_limit intel_limits_i8xx_dvo = {
276         .dot = { .min = 25000, .max = 350000 },
277         .vco = { .min = 908000, .max = 1512000 },
278         .n = { .min = 2, .max = 16 },
279         .m = { .min = 96, .max = 140 },
280         .m1 = { .min = 18, .max = 26 },
281         .m2 = { .min = 6, .max = 16 },
282         .p = { .min = 4, .max = 128 },
283         .p1 = { .min = 2, .max = 33 },
284         .p2 = { .dot_limit = 165000,
285                 .p2_slow = 4, .p2_fast = 4 },
286 };
287
288 static const struct intel_limit intel_limits_i8xx_lvds = {
289         .dot = { .min = 25000, .max = 350000 },
290         .vco = { .min = 908000, .max = 1512000 },
291         .n = { .min = 2, .max = 16 },
292         .m = { .min = 96, .max = 140 },
293         .m1 = { .min = 18, .max = 26 },
294         .m2 = { .min = 6, .max = 16 },
295         .p = { .min = 4, .max = 128 },
296         .p1 = { .min = 1, .max = 6 },
297         .p2 = { .dot_limit = 165000,
298                 .p2_slow = 14, .p2_fast = 7 },
299 };
300
301 static const struct intel_limit intel_limits_i9xx_sdvo = {
302         .dot = { .min = 20000, .max = 400000 },
303         .vco = { .min = 1400000, .max = 2800000 },
304         .n = { .min = 1, .max = 6 },
305         .m = { .min = 70, .max = 120 },
306         .m1 = { .min = 8, .max = 18 },
307         .m2 = { .min = 3, .max = 7 },
308         .p = { .min = 5, .max = 80 },
309         .p1 = { .min = 1, .max = 8 },
310         .p2 = { .dot_limit = 200000,
311                 .p2_slow = 10, .p2_fast = 5 },
312 };
313
314 static const struct intel_limit intel_limits_i9xx_lvds = {
315         .dot = { .min = 20000, .max = 400000 },
316         .vco = { .min = 1400000, .max = 2800000 },
317         .n = { .min = 1, .max = 6 },
318         .m = { .min = 70, .max = 120 },
319         .m1 = { .min = 8, .max = 18 },
320         .m2 = { .min = 3, .max = 7 },
321         .p = { .min = 7, .max = 98 },
322         .p1 = { .min = 1, .max = 8 },
323         .p2 = { .dot_limit = 112000,
324                 .p2_slow = 14, .p2_fast = 7 },
325 };
326
327
328 static const struct intel_limit intel_limits_g4x_sdvo = {
329         .dot = { .min = 25000, .max = 270000 },
330         .vco = { .min = 1750000, .max = 3500000},
331         .n = { .min = 1, .max = 4 },
332         .m = { .min = 104, .max = 138 },
333         .m1 = { .min = 17, .max = 23 },
334         .m2 = { .min = 5, .max = 11 },
335         .p = { .min = 10, .max = 30 },
336         .p1 = { .min = 1, .max = 3},
337         .p2 = { .dot_limit = 270000,
338                 .p2_slow = 10,
339                 .p2_fast = 10
340         },
341 };
342
343 static const struct intel_limit intel_limits_g4x_hdmi = {
344         .dot = { .min = 22000, .max = 400000 },
345         .vco = { .min = 1750000, .max = 3500000},
346         .n = { .min = 1, .max = 4 },
347         .m = { .min = 104, .max = 138 },
348         .m1 = { .min = 16, .max = 23 },
349         .m2 = { .min = 5, .max = 11 },
350         .p = { .min = 5, .max = 80 },
351         .p1 = { .min = 1, .max = 8},
352         .p2 = { .dot_limit = 165000,
353                 .p2_slow = 10, .p2_fast = 5 },
354 };
355
356 static const struct intel_limit intel_limits_g4x_single_channel_lvds = {
357         .dot = { .min = 20000, .max = 115000 },
358         .vco = { .min = 1750000, .max = 3500000 },
359         .n = { .min = 1, .max = 3 },
360         .m = { .min = 104, .max = 138 },
361         .m1 = { .min = 17, .max = 23 },
362         .m2 = { .min = 5, .max = 11 },
363         .p = { .min = 28, .max = 112 },
364         .p1 = { .min = 2, .max = 8 },
365         .p2 = { .dot_limit = 0,
366                 .p2_slow = 14, .p2_fast = 14
367         },
368 };
369
370 static const struct intel_limit intel_limits_g4x_dual_channel_lvds = {
371         .dot = { .min = 80000, .max = 224000 },
372         .vco = { .min = 1750000, .max = 3500000 },
373         .n = { .min = 1, .max = 3 },
374         .m = { .min = 104, .max = 138 },
375         .m1 = { .min = 17, .max = 23 },
376         .m2 = { .min = 5, .max = 11 },
377         .p = { .min = 14, .max = 42 },
378         .p1 = { .min = 2, .max = 6 },
379         .p2 = { .dot_limit = 0,
380                 .p2_slow = 7, .p2_fast = 7
381         },
382 };
383
384 static const struct intel_limit intel_limits_pineview_sdvo = {
385         .dot = { .min = 20000, .max = 400000},
386         .vco = { .min = 1700000, .max = 3500000 },
387         /* Pineview's Ncounter is a ring counter */
388         .n = { .min = 3, .max = 6 },
389         .m = { .min = 2, .max = 256 },
390         /* Pineview only has one combined m divider, which we treat as m2. */
391         .m1 = { .min = 0, .max = 0 },
392         .m2 = { .min = 0, .max = 254 },
393         .p = { .min = 5, .max = 80 },
394         .p1 = { .min = 1, .max = 8 },
395         .p2 = { .dot_limit = 200000,
396                 .p2_slow = 10, .p2_fast = 5 },
397 };
398
399 static const struct intel_limit intel_limits_pineview_lvds = {
400         .dot = { .min = 20000, .max = 400000 },
401         .vco = { .min = 1700000, .max = 3500000 },
402         .n = { .min = 3, .max = 6 },
403         .m = { .min = 2, .max = 256 },
404         .m1 = { .min = 0, .max = 0 },
405         .m2 = { .min = 0, .max = 254 },
406         .p = { .min = 7, .max = 112 },
407         .p1 = { .min = 1, .max = 8 },
408         .p2 = { .dot_limit = 112000,
409                 .p2_slow = 14, .p2_fast = 14 },
410 };
411
412 /* Ironlake / Sandybridge
413  *
414  * We calculate clock using (register_value + 2) for N/M1/M2, so here
415  * the range value for them is (actual_value - 2).
416  */
417 static const struct intel_limit intel_limits_ironlake_dac = {
418         .dot = { .min = 25000, .max = 350000 },
419         .vco = { .min = 1760000, .max = 3510000 },
420         .n = { .min = 1, .max = 5 },
421         .m = { .min = 79, .max = 127 },
422         .m1 = { .min = 12, .max = 22 },
423         .m2 = { .min = 5, .max = 9 },
424         .p = { .min = 5, .max = 80 },
425         .p1 = { .min = 1, .max = 8 },
426         .p2 = { .dot_limit = 225000,
427                 .p2_slow = 10, .p2_fast = 5 },
428 };
429
430 static const struct intel_limit intel_limits_ironlake_single_lvds = {
431         .dot = { .min = 25000, .max = 350000 },
432         .vco = { .min = 1760000, .max = 3510000 },
433         .n = { .min = 1, .max = 3 },
434         .m = { .min = 79, .max = 118 },
435         .m1 = { .min = 12, .max = 22 },
436         .m2 = { .min = 5, .max = 9 },
437         .p = { .min = 28, .max = 112 },
438         .p1 = { .min = 2, .max = 8 },
439         .p2 = { .dot_limit = 225000,
440                 .p2_slow = 14, .p2_fast = 14 },
441 };
442
443 static const struct intel_limit intel_limits_ironlake_dual_lvds = {
444         .dot = { .min = 25000, .max = 350000 },
445         .vco = { .min = 1760000, .max = 3510000 },
446         .n = { .min = 1, .max = 3 },
447         .m = { .min = 79, .max = 127 },
448         .m1 = { .min = 12, .max = 22 },
449         .m2 = { .min = 5, .max = 9 },
450         .p = { .min = 14, .max = 56 },
451         .p1 = { .min = 2, .max = 8 },
452         .p2 = { .dot_limit = 225000,
453                 .p2_slow = 7, .p2_fast = 7 },
454 };
455
456 /* LVDS 100mhz refclk limits. */
457 static const struct intel_limit intel_limits_ironlake_single_lvds_100m = {
458         .dot = { .min = 25000, .max = 350000 },
459         .vco = { .min = 1760000, .max = 3510000 },
460         .n = { .min = 1, .max = 2 },
461         .m = { .min = 79, .max = 126 },
462         .m1 = { .min = 12, .max = 22 },
463         .m2 = { .min = 5, .max = 9 },
464         .p = { .min = 28, .max = 112 },
465         .p1 = { .min = 2, .max = 8 },
466         .p2 = { .dot_limit = 225000,
467                 .p2_slow = 14, .p2_fast = 14 },
468 };
469
470 static const struct intel_limit intel_limits_ironlake_dual_lvds_100m = {
471         .dot = { .min = 25000, .max = 350000 },
472         .vco = { .min = 1760000, .max = 3510000 },
473         .n = { .min = 1, .max = 3 },
474         .m = { .min = 79, .max = 126 },
475         .m1 = { .min = 12, .max = 22 },
476         .m2 = { .min = 5, .max = 9 },
477         .p = { .min = 14, .max = 42 },
478         .p1 = { .min = 2, .max = 6 },
479         .p2 = { .dot_limit = 225000,
480                 .p2_slow = 7, .p2_fast = 7 },
481 };
482
483 static const struct intel_limit intel_limits_vlv = {
484          /*
485           * These are the data rate limits (measured in fast clocks)
486           * since those are the strictest limits we have. The fast
487           * clock and actual rate limits are more relaxed, so checking
488           * them would make no difference.
489           */
490         .dot = { .min = 25000 * 5, .max = 270000 * 5 },
491         .vco = { .min = 4000000, .max = 6000000 },
492         .n = { .min = 1, .max = 7 },
493         .m1 = { .min = 2, .max = 3 },
494         .m2 = { .min = 11, .max = 156 },
495         .p1 = { .min = 2, .max = 3 },
496         .p2 = { .p2_slow = 2, .p2_fast = 20 }, /* slow=min, fast=max */
497 };
498
499 static const struct intel_limit intel_limits_chv = {
500         /*
501          * These are the data rate limits (measured in fast clocks)
502          * since those are the strictest limits we have.  The fast
503          * clock and actual rate limits are more relaxed, so checking
504          * them would make no difference.
505          */
506         .dot = { .min = 25000 * 5, .max = 540000 * 5},
507         .vco = { .min = 4800000, .max = 6480000 },
508         .n = { .min = 1, .max = 1 },
509         .m1 = { .min = 2, .max = 2 },
510         .m2 = { .min = 24 << 22, .max = 175 << 22 },
511         .p1 = { .min = 2, .max = 4 },
512         .p2 = { .p2_slow = 1, .p2_fast = 14 },
513 };
514
515 static const struct intel_limit intel_limits_bxt = {
516         /* FIXME: find real dot limits */
517         .dot = { .min = 0, .max = INT_MAX },
518         .vco = { .min = 4800000, .max = 6700000 },
519         .n = { .min = 1, .max = 1 },
520         .m1 = { .min = 2, .max = 2 },
521         /* FIXME: find real m2 limits */
522         .m2 = { .min = 2 << 22, .max = 255 << 22 },
523         .p1 = { .min = 2, .max = 4 },
524         .p2 = { .p2_slow = 1, .p2_fast = 20 },
525 };
526
527 static bool
528 needs_modeset(struct drm_crtc_state *state)
529 {
530         return drm_atomic_crtc_needs_modeset(state);
531 }
532
533 /**
534  * Returns whether any output on the specified pipe is of the specified type
535  */
536 bool intel_pipe_has_type(struct intel_crtc *crtc, enum intel_output_type type)
537 {
538         struct drm_device *dev = crtc->base.dev;
539         struct intel_encoder *encoder;
540
541         for_each_encoder_on_crtc(dev, &crtc->base, encoder)
542                 if (encoder->type == type)
543                         return true;
544
545         return false;
546 }
547
548 /**
549  * Returns whether any output on the specified pipe will have the specified
550  * type after a staged modeset is complete, i.e., the same as
551  * intel_pipe_has_type() but looking at encoder->new_crtc instead of
552  * encoder->crtc.
553  */
554 static bool intel_pipe_will_have_type(const struct intel_crtc_state *crtc_state,
555                                       int type)
556 {
557         struct drm_atomic_state *state = crtc_state->base.state;
558         struct drm_connector *connector;
559         struct drm_connector_state *connector_state;
560         struct intel_encoder *encoder;
561         int i, num_connectors = 0;
562
563         for_each_connector_in_state(state, connector, connector_state, i) {
564                 if (connector_state->crtc != crtc_state->base.crtc)
565                         continue;
566
567                 num_connectors++;
568
569                 encoder = to_intel_encoder(connector_state->best_encoder);
570                 if (encoder->type == type)
571                         return true;
572         }
573
574         WARN_ON(num_connectors == 0);
575
576         return false;
577 }
578
579 /*
580  * Platform specific helpers to calculate the port PLL loopback- (clock.m),
581  * and post-divider (clock.p) values, pre- (clock.vco) and post-divided fast
582  * (clock.dot) clock rates. This fast dot clock is fed to the port's IO logic.
583  * The helpers' return value is the rate of the clock that is fed to the
584  * display engine's pipe which can be the above fast dot clock rate or a
585  * divided-down version of it.
586  */
587 /* m1 is reserved as 0 in Pineview, n is a ring counter */
588 static int pnv_calc_dpll_params(int refclk, struct dpll *clock)
589 {
590         clock->m = clock->m2 + 2;
591         clock->p = clock->p1 * clock->p2;
592         if (WARN_ON(clock->n == 0 || clock->p == 0))
593                 return 0;
594         clock->vco = DIV_ROUND_CLOSEST(refclk * clock->m, clock->n);
595         clock->dot = DIV_ROUND_CLOSEST(clock->vco, clock->p);
596
597         return clock->dot;
598 }
599
600 static uint32_t i9xx_dpll_compute_m(struct dpll *dpll)
601 {
602         return 5 * (dpll->m1 + 2) + (dpll->m2 + 2);
603 }
604
605 static int i9xx_calc_dpll_params(int refclk, struct dpll *clock)
606 {
607         clock->m = i9xx_dpll_compute_m(clock);
608         clock->p = clock->p1 * clock->p2;
609         if (WARN_ON(clock->n + 2 == 0 || clock->p == 0))
610                 return 0;
611         clock->vco = DIV_ROUND_CLOSEST(refclk * clock->m, clock->n + 2);
612         clock->dot = DIV_ROUND_CLOSEST(clock->vco, clock->p);
613
614         return clock->dot;
615 }
616
617 static int vlv_calc_dpll_params(int refclk, struct dpll *clock)
618 {
619         clock->m = clock->m1 * clock->m2;
620         clock->p = clock->p1 * clock->p2;
621         if (WARN_ON(clock->n == 0 || clock->p == 0))
622                 return 0;
623         clock->vco = DIV_ROUND_CLOSEST(refclk * clock->m, clock->n);
624         clock->dot = DIV_ROUND_CLOSEST(clock->vco, clock->p);
625
626         return clock->dot / 5;
627 }
628
629 int chv_calc_dpll_params(int refclk, struct dpll *clock)
630 {
631         clock->m = clock->m1 * clock->m2;
632         clock->p = clock->p1 * clock->p2;
633         if (WARN_ON(clock->n == 0 || clock->p == 0))
634                 return 0;
635         clock->vco = DIV_ROUND_CLOSEST_ULL((uint64_t)refclk * clock->m,
636                         clock->n << 22);
637         clock->dot = DIV_ROUND_CLOSEST(clock->vco, clock->p);
638
639         return clock->dot / 5;
640 }
641
642 #define INTELPllInvalid(s)   do { /* DRM_DEBUG(s); */ return false; } while (0)
643 /**
644  * Returns whether the given set of divisors are valid for a given refclk with
645  * the given connectors.
646  */
647
648 static bool intel_PLL_is_valid(struct drm_device *dev,
649                                const struct intel_limit *limit,
650                                const struct dpll *clock)
651 {
652         if (clock->n   < limit->n.min   || limit->n.max   < clock->n)
653                 INTELPllInvalid("n out of range\n");
654         if (clock->p1  < limit->p1.min  || limit->p1.max  < clock->p1)
655                 INTELPllInvalid("p1 out of range\n");
656         if (clock->m2  < limit->m2.min  || limit->m2.max  < clock->m2)
657                 INTELPllInvalid("m2 out of range\n");
658         if (clock->m1  < limit->m1.min  || limit->m1.max  < clock->m1)
659                 INTELPllInvalid("m1 out of range\n");
660
661         if (!IS_PINEVIEW(dev) && !IS_VALLEYVIEW(dev) &&
662             !IS_CHERRYVIEW(dev) && !IS_BROXTON(dev))
663                 if (clock->m1 <= clock->m2)
664                         INTELPllInvalid("m1 <= m2\n");
665
666         if (!IS_VALLEYVIEW(dev) && !IS_CHERRYVIEW(dev) && !IS_BROXTON(dev)) {
667                 if (clock->p < limit->p.min || limit->p.max < clock->p)
668                         INTELPllInvalid("p out of range\n");
669                 if (clock->m < limit->m.min || limit->m.max < clock->m)
670                         INTELPllInvalid("m out of range\n");
671         }
672
673         if (clock->vco < limit->vco.min || limit->vco.max < clock->vco)
674                 INTELPllInvalid("vco out of range\n");
675         /* XXX: We may need to be checking "Dot clock" depending on the multiplier,
676          * connector, etc., rather than just a single range.
677          */
678         if (clock->dot < limit->dot.min || limit->dot.max < clock->dot)
679                 INTELPllInvalid("dot out of range\n");
680
681         return true;
682 }
683
684 static int
685 i9xx_select_p2_div(const struct intel_limit *limit,
686                    const struct intel_crtc_state *crtc_state,
687                    int target)
688 {
689         struct drm_device *dev = crtc_state->base.crtc->dev;
690
691         if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_LVDS)) {
692                 /*
693                  * For LVDS just rely on its current settings for dual-channel.
694                  * We haven't figured out how to reliably set up different
695                  * single/dual channel state, if we even can.
696                  */
697                 if (intel_is_dual_link_lvds(dev))
698                         return limit->p2.p2_fast;
699                 else
700                         return limit->p2.p2_slow;
701         } else {
702                 if (target < limit->p2.dot_limit)
703                         return limit->p2.p2_slow;
704                 else
705                         return limit->p2.p2_fast;
706         }
707 }
708
709 /*
710  * Returns a set of divisors for the desired target clock with the given
711  * refclk, or FALSE.  The returned values represent the clock equation:
712  * reflck * (5 * (m1 + 2) + (m2 + 2)) / (n + 2) / p1 / p2.
713  *
714  * Target and reference clocks are specified in kHz.
715  *
716  * If match_clock is provided, then best_clock P divider must match the P
717  * divider from @match_clock used for LVDS downclocking.
718  */
719 static bool
720 i9xx_find_best_dpll(const struct intel_limit *limit,
721                     struct intel_crtc_state *crtc_state,
722                     int target, int refclk, struct dpll *match_clock,
723                     struct dpll *best_clock)
724 {
725         struct drm_device *dev = crtc_state->base.crtc->dev;
726         struct dpll clock;
727         int err = target;
728
729         memset(best_clock, 0, sizeof(*best_clock));
730
731         clock.p2 = i9xx_select_p2_div(limit, crtc_state, target);
732
733         for (clock.m1 = limit->m1.min; clock.m1 <= limit->m1.max;
734              clock.m1++) {
735                 for (clock.m2 = limit->m2.min;
736                      clock.m2 <= limit->m2.max; clock.m2++) {
737                         if (clock.m2 >= clock.m1)
738                                 break;
739                         for (clock.n = limit->n.min;
740                              clock.n <= limit->n.max; clock.n++) {
741                                 for (clock.p1 = limit->p1.min;
742                                         clock.p1 <= limit->p1.max; clock.p1++) {
743                                         int this_err;
744
745                                         i9xx_calc_dpll_params(refclk, &clock);
746                                         if (!intel_PLL_is_valid(dev, limit,
747                                                                 &clock))
748                                                 continue;
749                                         if (match_clock &&
750                                             clock.p != match_clock->p)
751                                                 continue;
752
753                                         this_err = abs(clock.dot - target);
754                                         if (this_err < err) {
755                                                 *best_clock = clock;
756                                                 err = this_err;
757                                         }
758                                 }
759                         }
760                 }
761         }
762
763         return (err != target);
764 }
765
766 /*
767  * Returns a set of divisors for the desired target clock with the given
768  * refclk, or FALSE.  The returned values represent the clock equation:
769  * reflck * (5 * (m1 + 2) + (m2 + 2)) / (n + 2) / p1 / p2.
770  *
771  * Target and reference clocks are specified in kHz.
772  *
773  * If match_clock is provided, then best_clock P divider must match the P
774  * divider from @match_clock used for LVDS downclocking.
775  */
776 static bool
777 pnv_find_best_dpll(const struct intel_limit *limit,
778                    struct intel_crtc_state *crtc_state,
779                    int target, int refclk, struct dpll *match_clock,
780                    struct dpll *best_clock)
781 {
782         struct drm_device *dev = crtc_state->base.crtc->dev;
783         struct dpll clock;
784         int err = target;
785
786         memset(best_clock, 0, sizeof(*best_clock));
787
788         clock.p2 = i9xx_select_p2_div(limit, crtc_state, target);
789
790         for (clock.m1 = limit->m1.min; clock.m1 <= limit->m1.max;
791              clock.m1++) {
792                 for (clock.m2 = limit->m2.min;
793                      clock.m2 <= limit->m2.max; clock.m2++) {
794                         for (clock.n = limit->n.min;
795                              clock.n <= limit->n.max; clock.n++) {
796                                 for (clock.p1 = limit->p1.min;
797                                         clock.p1 <= limit->p1.max; clock.p1++) {
798                                         int this_err;
799
800                                         pnv_calc_dpll_params(refclk, &clock);
801                                         if (!intel_PLL_is_valid(dev, limit,
802                                                                 &clock))
803                                                 continue;
804                                         if (match_clock &&
805                                             clock.p != match_clock->p)
806                                                 continue;
807
808                                         this_err = abs(clock.dot - target);
809                                         if (this_err < err) {
810                                                 *best_clock = clock;
811                                                 err = this_err;
812                                         }
813                                 }
814                         }
815                 }
816         }
817
818         return (err != target);
819 }
820
821 /*
822  * Returns a set of divisors for the desired target clock with the given
823  * refclk, or FALSE.  The returned values represent the clock equation:
824  * reflck * (5 * (m1 + 2) + (m2 + 2)) / (n + 2) / p1 / p2.
825  *
826  * Target and reference clocks are specified in kHz.
827  *
828  * If match_clock is provided, then best_clock P divider must match the P
829  * divider from @match_clock used for LVDS downclocking.
830  */
831 static bool
832 g4x_find_best_dpll(const struct intel_limit *limit,
833                    struct intel_crtc_state *crtc_state,
834                    int target, int refclk, struct dpll *match_clock,
835                    struct dpll *best_clock)
836 {
837         struct drm_device *dev = crtc_state->base.crtc->dev;
838         struct dpll clock;
839         int max_n;
840         bool found = false;
841         /* approximately equals target * 0.00585 */
842         int err_most = (target >> 8) + (target >> 9);
843
844         memset(best_clock, 0, sizeof(*best_clock));
845
846         clock.p2 = i9xx_select_p2_div(limit, crtc_state, target);
847
848         max_n = limit->n.max;
849         /* based on hardware requirement, prefer smaller n to precision */
850         for (clock.n = limit->n.min; clock.n <= max_n; clock.n++) {
851                 /* based on hardware requirement, prefere larger m1,m2 */
852                 for (clock.m1 = limit->m1.max;
853                      clock.m1 >= limit->m1.min; clock.m1--) {
854                         for (clock.m2 = limit->m2.max;
855                              clock.m2 >= limit->m2.min; clock.m2--) {
856                                 for (clock.p1 = limit->p1.max;
857                                      clock.p1 >= limit->p1.min; clock.p1--) {
858                                         int this_err;
859
860                                         i9xx_calc_dpll_params(refclk, &clock);
861                                         if (!intel_PLL_is_valid(dev, limit,
862                                                                 &clock))
863                                                 continue;
864
865                                         this_err = abs(clock.dot - target);
866                                         if (this_err < err_most) {
867                                                 *best_clock = clock;
868                                                 err_most = this_err;
869                                                 max_n = clock.n;
870                                                 found = true;
871                                         }
872                                 }
873                         }
874                 }
875         }
876         return found;
877 }
878
879 /*
880  * Check if the calculated PLL configuration is more optimal compared to the
881  * best configuration and error found so far. Return the calculated error.
882  */
883 static bool vlv_PLL_is_optimal(struct drm_device *dev, int target_freq,
884                                const struct dpll *calculated_clock,
885                                const struct dpll *best_clock,
886                                unsigned int best_error_ppm,
887                                unsigned int *error_ppm)
888 {
889         /*
890          * For CHV ignore the error and consider only the P value.
891          * Prefer a bigger P value based on HW requirements.
892          */
893         if (IS_CHERRYVIEW(dev)) {
894                 *error_ppm = 0;
895
896                 return calculated_clock->p > best_clock->p;
897         }
898
899         if (WARN_ON_ONCE(!target_freq))
900                 return false;
901
902         *error_ppm = div_u64(1000000ULL *
903                                 abs(target_freq - calculated_clock->dot),
904                              target_freq);
905         /*
906          * Prefer a better P value over a better (smaller) error if the error
907          * is small. Ensure this preference for future configurations too by
908          * setting the error to 0.
909          */
910         if (*error_ppm < 100 && calculated_clock->p > best_clock->p) {
911                 *error_ppm = 0;
912
913                 return true;
914         }
915
916         return *error_ppm + 10 < best_error_ppm;
917 }
918
919 /*
920  * Returns a set of divisors for the desired target clock with the given
921  * refclk, or FALSE.  The returned values represent the clock equation:
922  * reflck * (5 * (m1 + 2) + (m2 + 2)) / (n + 2) / p1 / p2.
923  */
924 static bool
925 vlv_find_best_dpll(const struct intel_limit *limit,
926                    struct intel_crtc_state *crtc_state,
927                    int target, int refclk, struct dpll *match_clock,
928                    struct dpll *best_clock)
929 {
930         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
931         struct drm_device *dev = crtc->base.dev;
932         struct dpll clock;
933         unsigned int bestppm = 1000000;
934         /* min update 19.2 MHz */
935         int max_n = min(limit->n.max, refclk / 19200);
936         bool found = false;
937
938         target *= 5; /* fast clock */
939
940         memset(best_clock, 0, sizeof(*best_clock));
941
942         /* based on hardware requirement, prefer smaller n to precision */
943         for (clock.n = limit->n.min; clock.n <= max_n; clock.n++) {
944                 for (clock.p1 = limit->p1.max; clock.p1 >= limit->p1.min; clock.p1--) {
945                         for (clock.p2 = limit->p2.p2_fast; clock.p2 >= limit->p2.p2_slow;
946                              clock.p2 -= clock.p2 > 10 ? 2 : 1) {
947                                 clock.p = clock.p1 * clock.p2;
948                                 /* based on hardware requirement, prefer bigger m1,m2 values */
949                                 for (clock.m1 = limit->m1.min; clock.m1 <= limit->m1.max; clock.m1++) {
950                                         unsigned int ppm;
951
952                                         clock.m2 = DIV_ROUND_CLOSEST(target * clock.p * clock.n,
953                                                                      refclk * clock.m1);
954
955                                         vlv_calc_dpll_params(refclk, &clock);
956
957                                         if (!intel_PLL_is_valid(dev, limit,
958                                                                 &clock))
959                                                 continue;
960
961                                         if (!vlv_PLL_is_optimal(dev, target,
962                                                                 &clock,
963                                                                 best_clock,
964                                                                 bestppm, &ppm))
965                                                 continue;
966
967                                         *best_clock = clock;
968                                         bestppm = ppm;
969                                         found = true;
970                                 }
971                         }
972                 }
973         }
974
975         return found;
976 }
977
978 /*
979  * Returns a set of divisors for the desired target clock with the given
980  * refclk, or FALSE.  The returned values represent the clock equation:
981  * reflck * (5 * (m1 + 2) + (m2 + 2)) / (n + 2) / p1 / p2.
982  */
983 static bool
984 chv_find_best_dpll(const struct intel_limit *limit,
985                    struct intel_crtc_state *crtc_state,
986                    int target, int refclk, struct dpll *match_clock,
987                    struct dpll *best_clock)
988 {
989         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
990         struct drm_device *dev = crtc->base.dev;
991         unsigned int best_error_ppm;
992         struct dpll clock;
993         uint64_t m2;
994         int found = false;
995
996         memset(best_clock, 0, sizeof(*best_clock));
997         best_error_ppm = 1000000;
998
999         /*
1000          * Based on hardware doc, the n always set to 1, and m1 always
1001          * set to 2.  If requires to support 200Mhz refclk, we need to
1002          * revisit this because n may not 1 anymore.
1003          */
1004         clock.n = 1, clock.m1 = 2;
1005         target *= 5;    /* fast clock */
1006
1007         for (clock.p1 = limit->p1.max; clock.p1 >= limit->p1.min; clock.p1--) {
1008                 for (clock.p2 = limit->p2.p2_fast;
1009                                 clock.p2 >= limit->p2.p2_slow;
1010                                 clock.p2 -= clock.p2 > 10 ? 2 : 1) {
1011                         unsigned int error_ppm;
1012
1013                         clock.p = clock.p1 * clock.p2;
1014
1015                         m2 = DIV_ROUND_CLOSEST_ULL(((uint64_t)target * clock.p *
1016                                         clock.n) << 22, refclk * clock.m1);
1017
1018                         if (m2 > INT_MAX/clock.m1)
1019                                 continue;
1020
1021                         clock.m2 = m2;
1022
1023                         chv_calc_dpll_params(refclk, &clock);
1024
1025                         if (!intel_PLL_is_valid(dev, limit, &clock))
1026                                 continue;
1027
1028                         if (!vlv_PLL_is_optimal(dev, target, &clock, best_clock,
1029                                                 best_error_ppm, &error_ppm))
1030                                 continue;
1031
1032                         *best_clock = clock;
1033                         best_error_ppm = error_ppm;
1034                         found = true;
1035                 }
1036         }
1037
1038         return found;
1039 }
1040
1041 bool bxt_find_best_dpll(struct intel_crtc_state *crtc_state, int target_clock,
1042                         struct dpll *best_clock)
1043 {
1044         int refclk = 100000;
1045         const struct intel_limit *limit = &intel_limits_bxt;
1046
1047         return chv_find_best_dpll(limit, crtc_state,
1048                                   target_clock, refclk, NULL, best_clock);
1049 }
1050
1051 bool intel_crtc_active(struct drm_crtc *crtc)
1052 {
1053         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
1054
1055         /* Be paranoid as we can arrive here with only partial
1056          * state retrieved from the hardware during setup.
1057          *
1058          * We can ditch the adjusted_mode.crtc_clock check as soon
1059          * as Haswell has gained clock readout/fastboot support.
1060          *
1061          * We can ditch the crtc->primary->fb check as soon as we can
1062          * properly reconstruct framebuffers.
1063          *
1064          * FIXME: The intel_crtc->active here should be switched to
1065          * crtc->state->active once we have proper CRTC states wired up
1066          * for atomic.
1067          */
1068         return intel_crtc->active && crtc->primary->state->fb &&
1069                 intel_crtc->config->base.adjusted_mode.crtc_clock;
1070 }
1071
1072 enum transcoder intel_pipe_to_cpu_transcoder(struct drm_i915_private *dev_priv,
1073                                              enum pipe pipe)
1074 {
1075         struct drm_crtc *crtc = dev_priv->pipe_to_crtc_mapping[pipe];
1076         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
1077
1078         return intel_crtc->config->cpu_transcoder;
1079 }
1080
1081 static bool pipe_dsl_stopped(struct drm_device *dev, enum pipe pipe)
1082 {
1083         struct drm_i915_private *dev_priv = dev->dev_private;
1084         i915_reg_t reg = PIPEDSL(pipe);
1085         u32 line1, line2;
1086         u32 line_mask;
1087
1088         if (IS_GEN2(dev))
1089                 line_mask = DSL_LINEMASK_GEN2;
1090         else
1091                 line_mask = DSL_LINEMASK_GEN3;
1092
1093         line1 = I915_READ(reg) & line_mask;
1094         msleep(5);
1095         line2 = I915_READ(reg) & line_mask;
1096
1097         return line1 == line2;
1098 }
1099
1100 /*
1101  * intel_wait_for_pipe_off - wait for pipe to turn off
1102  * @crtc: crtc whose pipe to wait for
1103  *
1104  * After disabling a pipe, we can't wait for vblank in the usual way,
1105  * spinning on the vblank interrupt status bit, since we won't actually
1106  * see an interrupt when the pipe is disabled.
1107  *
1108  * On Gen4 and above:
1109  *   wait for the pipe register state bit to turn off
1110  *
1111  * Otherwise:
1112  *   wait for the display line value to settle (it usually
1113  *   ends up stopping at the start of the next frame).
1114  *
1115  */
1116 static void intel_wait_for_pipe_off(struct intel_crtc *crtc)
1117 {
1118         struct drm_device *dev = crtc->base.dev;
1119         struct drm_i915_private *dev_priv = dev->dev_private;
1120         enum transcoder cpu_transcoder = crtc->config->cpu_transcoder;
1121         enum pipe pipe = crtc->pipe;
1122
1123         if (INTEL_INFO(dev)->gen >= 4) {
1124                 i915_reg_t reg = PIPECONF(cpu_transcoder);
1125
1126                 /* Wait for the Pipe State to go off */
1127                 if (wait_for((I915_READ(reg) & I965_PIPECONF_ACTIVE) == 0,
1128                              100))
1129                         WARN(1, "pipe_off wait timed out\n");
1130         } else {
1131                 /* Wait for the display line to settle */
1132                 if (wait_for(pipe_dsl_stopped(dev, pipe), 100))
1133                         WARN(1, "pipe_off wait timed out\n");
1134         }
1135 }
1136
1137 /* Only for pre-ILK configs */
1138 void assert_pll(struct drm_i915_private *dev_priv,
1139                 enum pipe pipe, bool state)
1140 {
1141         u32 val;
1142         bool cur_state;
1143
1144         val = I915_READ(DPLL(pipe));
1145         cur_state = !!(val & DPLL_VCO_ENABLE);
1146         I915_STATE_WARN(cur_state != state,
1147              "PLL state assertion failure (expected %s, current %s)\n",
1148                         onoff(state), onoff(cur_state));
1149 }
1150
1151 /* XXX: the dsi pll is shared between MIPI DSI ports */
1152 void assert_dsi_pll(struct drm_i915_private *dev_priv, bool state)
1153 {
1154         u32 val;
1155         bool cur_state;
1156
1157         mutex_lock(&dev_priv->sb_lock);
1158         val = vlv_cck_read(dev_priv, CCK_REG_DSI_PLL_CONTROL);
1159         mutex_unlock(&dev_priv->sb_lock);
1160
1161         cur_state = val & DSI_PLL_VCO_EN;
1162         I915_STATE_WARN(cur_state != state,
1163              "DSI PLL state assertion failure (expected %s, current %s)\n",
1164                         onoff(state), onoff(cur_state));
1165 }
1166
1167 static void assert_fdi_tx(struct drm_i915_private *dev_priv,
1168                           enum pipe pipe, bool state)
1169 {
1170         bool cur_state;
1171         enum transcoder cpu_transcoder = intel_pipe_to_cpu_transcoder(dev_priv,
1172                                                                       pipe);
1173
1174         if (HAS_DDI(dev_priv)) {
1175                 /* DDI does not have a specific FDI_TX register */
1176                 u32 val = I915_READ(TRANS_DDI_FUNC_CTL(cpu_transcoder));
1177                 cur_state = !!(val & TRANS_DDI_FUNC_ENABLE);
1178         } else {
1179                 u32 val = I915_READ(FDI_TX_CTL(pipe));
1180                 cur_state = !!(val & FDI_TX_ENABLE);
1181         }
1182         I915_STATE_WARN(cur_state != state,
1183              "FDI TX state assertion failure (expected %s, current %s)\n",
1184                         onoff(state), onoff(cur_state));
1185 }
1186 #define assert_fdi_tx_enabled(d, p) assert_fdi_tx(d, p, true)
1187 #define assert_fdi_tx_disabled(d, p) assert_fdi_tx(d, p, false)
1188
1189 static void assert_fdi_rx(struct drm_i915_private *dev_priv,
1190                           enum pipe pipe, bool state)
1191 {
1192         u32 val;
1193         bool cur_state;
1194
1195         val = I915_READ(FDI_RX_CTL(pipe));
1196         cur_state = !!(val & FDI_RX_ENABLE);
1197         I915_STATE_WARN(cur_state != state,
1198              "FDI RX state assertion failure (expected %s, current %s)\n",
1199                         onoff(state), onoff(cur_state));
1200 }
1201 #define assert_fdi_rx_enabled(d, p) assert_fdi_rx(d, p, true)
1202 #define assert_fdi_rx_disabled(d, p) assert_fdi_rx(d, p, false)
1203
1204 static void assert_fdi_tx_pll_enabled(struct drm_i915_private *dev_priv,
1205                                       enum pipe pipe)
1206 {
1207         u32 val;
1208
1209         /* ILK FDI PLL is always enabled */
1210         if (IS_GEN5(dev_priv))
1211                 return;
1212
1213         /* On Haswell, DDI ports are responsible for the FDI PLL setup */
1214         if (HAS_DDI(dev_priv))
1215                 return;
1216
1217         val = I915_READ(FDI_TX_CTL(pipe));
1218         I915_STATE_WARN(!(val & FDI_TX_PLL_ENABLE), "FDI TX PLL assertion failure, should be active but is disabled\n");
1219 }
1220
1221 void assert_fdi_rx_pll(struct drm_i915_private *dev_priv,
1222                        enum pipe pipe, bool state)
1223 {
1224         u32 val;
1225         bool cur_state;
1226
1227         val = I915_READ(FDI_RX_CTL(pipe));
1228         cur_state = !!(val & FDI_RX_PLL_ENABLE);
1229         I915_STATE_WARN(cur_state != state,
1230              "FDI RX PLL assertion failure (expected %s, current %s)\n",
1231                         onoff(state), onoff(cur_state));
1232 }
1233
1234 void assert_panel_unlocked(struct drm_i915_private *dev_priv,
1235                            enum pipe pipe)
1236 {
1237         struct drm_device *dev = dev_priv->dev;
1238         i915_reg_t pp_reg;
1239         u32 val;
1240         enum pipe panel_pipe = PIPE_A;
1241         bool locked = true;
1242
1243         if (WARN_ON(HAS_DDI(dev)))
1244                 return;
1245
1246         if (HAS_PCH_SPLIT(dev)) {
1247                 u32 port_sel;
1248
1249                 pp_reg = PCH_PP_CONTROL;
1250                 port_sel = I915_READ(PCH_PP_ON_DELAYS) & PANEL_PORT_SELECT_MASK;
1251
1252                 if (port_sel == PANEL_PORT_SELECT_LVDS &&
1253                     I915_READ(PCH_LVDS) & LVDS_PIPEB_SELECT)
1254                         panel_pipe = PIPE_B;
1255                 /* XXX: else fix for eDP */
1256         } else if (IS_VALLEYVIEW(dev) || IS_CHERRYVIEW(dev)) {
1257                 /* presumably write lock depends on pipe, not port select */
1258                 pp_reg = VLV_PIPE_PP_CONTROL(pipe);
1259                 panel_pipe = pipe;
1260         } else {
1261                 pp_reg = PP_CONTROL;
1262                 if (I915_READ(LVDS) & LVDS_PIPEB_SELECT)
1263                         panel_pipe = PIPE_B;
1264         }
1265
1266         val = I915_READ(pp_reg);
1267         if (!(val & PANEL_POWER_ON) ||
1268             ((val & PANEL_UNLOCK_MASK) == PANEL_UNLOCK_REGS))
1269                 locked = false;
1270
1271         I915_STATE_WARN(panel_pipe == pipe && locked,
1272              "panel assertion failure, pipe %c regs locked\n",
1273              pipe_name(pipe));
1274 }
1275
1276 static void assert_cursor(struct drm_i915_private *dev_priv,
1277                           enum pipe pipe, bool state)
1278 {
1279         struct drm_device *dev = dev_priv->dev;
1280         bool cur_state;
1281
1282         if (IS_845G(dev) || IS_I865G(dev))
1283                 cur_state = I915_READ(CURCNTR(PIPE_A)) & CURSOR_ENABLE;
1284         else
1285                 cur_state = I915_READ(CURCNTR(pipe)) & CURSOR_MODE;
1286
1287         I915_STATE_WARN(cur_state != state,
1288              "cursor on pipe %c assertion failure (expected %s, current %s)\n",
1289                         pipe_name(pipe), onoff(state), onoff(cur_state));
1290 }
1291 #define assert_cursor_enabled(d, p) assert_cursor(d, p, true)
1292 #define assert_cursor_disabled(d, p) assert_cursor(d, p, false)
1293
1294 void assert_pipe(struct drm_i915_private *dev_priv,
1295                  enum pipe pipe, bool state)
1296 {
1297         bool cur_state;
1298         enum transcoder cpu_transcoder = intel_pipe_to_cpu_transcoder(dev_priv,
1299                                                                       pipe);
1300         enum intel_display_power_domain power_domain;
1301
1302         /* if we need the pipe quirk it must be always on */
1303         if ((pipe == PIPE_A && dev_priv->quirks & QUIRK_PIPEA_FORCE) ||
1304             (pipe == PIPE_B && dev_priv->quirks & QUIRK_PIPEB_FORCE))
1305                 state = true;
1306
1307         power_domain = POWER_DOMAIN_TRANSCODER(cpu_transcoder);
1308         if (intel_display_power_get_if_enabled(dev_priv, power_domain)) {
1309                 u32 val = I915_READ(PIPECONF(cpu_transcoder));
1310                 cur_state = !!(val & PIPECONF_ENABLE);
1311
1312                 intel_display_power_put(dev_priv, power_domain);
1313         } else {
1314                 cur_state = false;
1315         }
1316
1317         I915_STATE_WARN(cur_state != state,
1318              "pipe %c assertion failure (expected %s, current %s)\n",
1319                         pipe_name(pipe), onoff(state), onoff(cur_state));
1320 }
1321
1322 static void assert_plane(struct drm_i915_private *dev_priv,
1323                          enum plane plane, bool state)
1324 {
1325         u32 val;
1326         bool cur_state;
1327
1328         val = I915_READ(DSPCNTR(plane));
1329         cur_state = !!(val & DISPLAY_PLANE_ENABLE);
1330         I915_STATE_WARN(cur_state != state,
1331              "plane %c assertion failure (expected %s, current %s)\n",
1332                         plane_name(plane), onoff(state), onoff(cur_state));
1333 }
1334
1335 #define assert_plane_enabled(d, p) assert_plane(d, p, true)
1336 #define assert_plane_disabled(d, p) assert_plane(d, p, false)
1337
1338 static void assert_planes_disabled(struct drm_i915_private *dev_priv,
1339                                    enum pipe pipe)
1340 {
1341         struct drm_device *dev = dev_priv->dev;
1342         int i;
1343
1344         /* Primary planes are fixed to pipes on gen4+ */
1345         if (INTEL_INFO(dev)->gen >= 4) {
1346                 u32 val = I915_READ(DSPCNTR(pipe));
1347                 I915_STATE_WARN(val & DISPLAY_PLANE_ENABLE,
1348                      "plane %c assertion failure, should be disabled but not\n",
1349                      plane_name(pipe));
1350                 return;
1351         }
1352
1353         /* Need to check both planes against the pipe */
1354         for_each_pipe(dev_priv, i) {
1355                 u32 val = I915_READ(DSPCNTR(i));
1356                 enum pipe cur_pipe = (val & DISPPLANE_SEL_PIPE_MASK) >>
1357                         DISPPLANE_SEL_PIPE_SHIFT;
1358                 I915_STATE_WARN((val & DISPLAY_PLANE_ENABLE) && pipe == cur_pipe,
1359                      "plane %c assertion failure, should be off on pipe %c but is still active\n",
1360                      plane_name(i), pipe_name(pipe));
1361         }
1362 }
1363
1364 static void assert_sprites_disabled(struct drm_i915_private *dev_priv,
1365                                     enum pipe pipe)
1366 {
1367         struct drm_device *dev = dev_priv->dev;
1368         int sprite;
1369
1370         if (INTEL_INFO(dev)->gen >= 9) {
1371                 for_each_sprite(dev_priv, pipe, sprite) {
1372                         u32 val = I915_READ(PLANE_CTL(pipe, sprite));
1373                         I915_STATE_WARN(val & PLANE_CTL_ENABLE,
1374                              "plane %d assertion failure, should be off on pipe %c but is still active\n",
1375                              sprite, pipe_name(pipe));
1376                 }
1377         } else if (IS_VALLEYVIEW(dev) || IS_CHERRYVIEW(dev)) {
1378                 for_each_sprite(dev_priv, pipe, sprite) {
1379                         u32 val = I915_READ(SPCNTR(pipe, sprite));
1380                         I915_STATE_WARN(val & SP_ENABLE,
1381                              "sprite %c assertion failure, should be off on pipe %c but is still active\n",
1382                              sprite_name(pipe, sprite), pipe_name(pipe));
1383                 }
1384         } else if (INTEL_INFO(dev)->gen >= 7) {
1385                 u32 val = I915_READ(SPRCTL(pipe));
1386                 I915_STATE_WARN(val & SPRITE_ENABLE,
1387                      "sprite %c assertion failure, should be off on pipe %c but is still active\n",
1388                      plane_name(pipe), pipe_name(pipe));
1389         } else if (INTEL_INFO(dev)->gen >= 5) {
1390                 u32 val = I915_READ(DVSCNTR(pipe));
1391                 I915_STATE_WARN(val & DVS_ENABLE,
1392                      "sprite %c assertion failure, should be off on pipe %c but is still active\n",
1393                      plane_name(pipe), pipe_name(pipe));
1394         }
1395 }
1396
1397 static void assert_vblank_disabled(struct drm_crtc *crtc)
1398 {
1399         if (I915_STATE_WARN_ON(drm_crtc_vblank_get(crtc) == 0))
1400                 drm_crtc_vblank_put(crtc);
1401 }
1402
1403 void assert_pch_transcoder_disabled(struct drm_i915_private *dev_priv,
1404                                     enum pipe pipe)
1405 {
1406         u32 val;
1407         bool enabled;
1408
1409         val = I915_READ(PCH_TRANSCONF(pipe));
1410         enabled = !!(val & TRANS_ENABLE);
1411         I915_STATE_WARN(enabled,
1412              "transcoder assertion failed, should be off on pipe %c but is still active\n",
1413              pipe_name(pipe));
1414 }
1415
1416 static bool dp_pipe_enabled(struct drm_i915_private *dev_priv,
1417                             enum pipe pipe, u32 port_sel, u32 val)
1418 {
1419         if ((val & DP_PORT_EN) == 0)
1420                 return false;
1421
1422         if (HAS_PCH_CPT(dev_priv)) {
1423                 u32 trans_dp_ctl = I915_READ(TRANS_DP_CTL(pipe));
1424                 if ((trans_dp_ctl & TRANS_DP_PORT_SEL_MASK) != port_sel)
1425                         return false;
1426         } else if (IS_CHERRYVIEW(dev_priv)) {
1427                 if ((val & DP_PIPE_MASK_CHV) != DP_PIPE_SELECT_CHV(pipe))
1428                         return false;
1429         } else {
1430                 if ((val & DP_PIPE_MASK) != (pipe << 30))
1431                         return false;
1432         }
1433         return true;
1434 }
1435
1436 static bool hdmi_pipe_enabled(struct drm_i915_private *dev_priv,
1437                               enum pipe pipe, u32 val)
1438 {
1439         if ((val & SDVO_ENABLE) == 0)
1440                 return false;
1441
1442         if (HAS_PCH_CPT(dev_priv)) {
1443                 if ((val & SDVO_PIPE_SEL_MASK_CPT) != SDVO_PIPE_SEL_CPT(pipe))
1444                         return false;
1445         } else if (IS_CHERRYVIEW(dev_priv)) {
1446                 if ((val & SDVO_PIPE_SEL_MASK_CHV) != SDVO_PIPE_SEL_CHV(pipe))
1447                         return false;
1448         } else {
1449                 if ((val & SDVO_PIPE_SEL_MASK) != SDVO_PIPE_SEL(pipe))
1450                         return false;
1451         }
1452         return true;
1453 }
1454
1455 static bool lvds_pipe_enabled(struct drm_i915_private *dev_priv,
1456                               enum pipe pipe, u32 val)
1457 {
1458         if ((val & LVDS_PORT_EN) == 0)
1459                 return false;
1460
1461         if (HAS_PCH_CPT(dev_priv)) {
1462                 if ((val & PORT_TRANS_SEL_MASK) != PORT_TRANS_SEL_CPT(pipe))
1463                         return false;
1464         } else {
1465                 if ((val & LVDS_PIPE_MASK) != LVDS_PIPE(pipe))
1466                         return false;
1467         }
1468         return true;
1469 }
1470
1471 static bool adpa_pipe_enabled(struct drm_i915_private *dev_priv,
1472                               enum pipe pipe, u32 val)
1473 {
1474         if ((val & ADPA_DAC_ENABLE) == 0)
1475                 return false;
1476         if (HAS_PCH_CPT(dev_priv)) {
1477                 if ((val & PORT_TRANS_SEL_MASK) != PORT_TRANS_SEL_CPT(pipe))
1478                         return false;
1479         } else {
1480                 if ((val & ADPA_PIPE_SELECT_MASK) != ADPA_PIPE_SELECT(pipe))
1481                         return false;
1482         }
1483         return true;
1484 }
1485
1486 static void assert_pch_dp_disabled(struct drm_i915_private *dev_priv,
1487                                    enum pipe pipe, i915_reg_t reg,
1488                                    u32 port_sel)
1489 {
1490         u32 val = I915_READ(reg);
1491         I915_STATE_WARN(dp_pipe_enabled(dev_priv, pipe, port_sel, val),
1492              "PCH DP (0x%08x) enabled on transcoder %c, should be disabled\n",
1493              i915_mmio_reg_offset(reg), pipe_name(pipe));
1494
1495         I915_STATE_WARN(HAS_PCH_IBX(dev_priv) && (val & DP_PORT_EN) == 0
1496              && (val & DP_PIPEB_SELECT),
1497              "IBX PCH dp port still using transcoder B\n");
1498 }
1499
1500 static void assert_pch_hdmi_disabled(struct drm_i915_private *dev_priv,
1501                                      enum pipe pipe, i915_reg_t reg)
1502 {
1503         u32 val = I915_READ(reg);
1504         I915_STATE_WARN(hdmi_pipe_enabled(dev_priv, pipe, val),
1505              "PCH HDMI (0x%08x) enabled on transcoder %c, should be disabled\n",
1506              i915_mmio_reg_offset(reg), pipe_name(pipe));
1507
1508         I915_STATE_WARN(HAS_PCH_IBX(dev_priv) && (val & SDVO_ENABLE) == 0
1509              && (val & SDVO_PIPE_B_SELECT),
1510              "IBX PCH hdmi port still using transcoder B\n");
1511 }
1512
1513 static void assert_pch_ports_disabled(struct drm_i915_private *dev_priv,
1514                                       enum pipe pipe)
1515 {
1516         u32 val;
1517
1518         assert_pch_dp_disabled(dev_priv, pipe, PCH_DP_B, TRANS_DP_PORT_SEL_B);
1519         assert_pch_dp_disabled(dev_priv, pipe, PCH_DP_C, TRANS_DP_PORT_SEL_C);
1520         assert_pch_dp_disabled(dev_priv, pipe, PCH_DP_D, TRANS_DP_PORT_SEL_D);
1521
1522         val = I915_READ(PCH_ADPA);
1523         I915_STATE_WARN(adpa_pipe_enabled(dev_priv, pipe, val),
1524              "PCH VGA enabled on transcoder %c, should be disabled\n",
1525              pipe_name(pipe));
1526
1527         val = I915_READ(PCH_LVDS);
1528         I915_STATE_WARN(lvds_pipe_enabled(dev_priv, pipe, val),
1529              "PCH LVDS enabled on transcoder %c, should be disabled\n",
1530              pipe_name(pipe));
1531
1532         assert_pch_hdmi_disabled(dev_priv, pipe, PCH_HDMIB);
1533         assert_pch_hdmi_disabled(dev_priv, pipe, PCH_HDMIC);
1534         assert_pch_hdmi_disabled(dev_priv, pipe, PCH_HDMID);
1535 }
1536
1537 static void _vlv_enable_pll(struct intel_crtc *crtc,
1538                             const struct intel_crtc_state *pipe_config)
1539 {
1540         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
1541         enum pipe pipe = crtc->pipe;
1542
1543         I915_WRITE(DPLL(pipe), pipe_config->dpll_hw_state.dpll);
1544         POSTING_READ(DPLL(pipe));
1545         udelay(150);
1546
1547         if (wait_for(((I915_READ(DPLL(pipe)) & DPLL_LOCK_VLV) == DPLL_LOCK_VLV), 1))
1548                 DRM_ERROR("DPLL %d failed to lock\n", pipe);
1549 }
1550
1551 static void vlv_enable_pll(struct intel_crtc *crtc,
1552                            const struct intel_crtc_state *pipe_config)
1553 {
1554         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
1555         enum pipe pipe = crtc->pipe;
1556
1557         assert_pipe_disabled(dev_priv, pipe);
1558
1559         /* PLL is protected by panel, make sure we can write it */
1560         assert_panel_unlocked(dev_priv, pipe);
1561
1562         if (pipe_config->dpll_hw_state.dpll & DPLL_VCO_ENABLE)
1563                 _vlv_enable_pll(crtc, pipe_config);
1564
1565         I915_WRITE(DPLL_MD(pipe), pipe_config->dpll_hw_state.dpll_md);
1566         POSTING_READ(DPLL_MD(pipe));
1567 }
1568
1569
1570 static void _chv_enable_pll(struct intel_crtc *crtc,
1571                             const struct intel_crtc_state *pipe_config)
1572 {
1573         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
1574         enum pipe pipe = crtc->pipe;
1575         enum dpio_channel port = vlv_pipe_to_channel(pipe);
1576         u32 tmp;
1577
1578         mutex_lock(&dev_priv->sb_lock);
1579
1580         /* Enable back the 10bit clock to display controller */
1581         tmp = vlv_dpio_read(dev_priv, pipe, CHV_CMN_DW14(port));
1582         tmp |= DPIO_DCLKP_EN;
1583         vlv_dpio_write(dev_priv, pipe, CHV_CMN_DW14(port), tmp);
1584
1585         mutex_unlock(&dev_priv->sb_lock);
1586
1587         /*
1588          * Need to wait > 100ns between dclkp clock enable bit and PLL enable.
1589          */
1590         udelay(1);
1591
1592         /* Enable PLL */
1593         I915_WRITE(DPLL(pipe), pipe_config->dpll_hw_state.dpll);
1594
1595         /* Check PLL is locked */
1596         if (wait_for(((I915_READ(DPLL(pipe)) & DPLL_LOCK_VLV) == DPLL_LOCK_VLV), 1))
1597                 DRM_ERROR("PLL %d failed to lock\n", pipe);
1598 }
1599
1600 static void chv_enable_pll(struct intel_crtc *crtc,
1601                            const struct intel_crtc_state *pipe_config)
1602 {
1603         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
1604         enum pipe pipe = crtc->pipe;
1605
1606         assert_pipe_disabled(dev_priv, pipe);
1607
1608         /* PLL is protected by panel, make sure we can write it */
1609         assert_panel_unlocked(dev_priv, pipe);
1610
1611         if (pipe_config->dpll_hw_state.dpll & DPLL_VCO_ENABLE)
1612                 _chv_enable_pll(crtc, pipe_config);
1613
1614         if (pipe != PIPE_A) {
1615                 /*
1616                  * WaPixelRepeatModeFixForC0:chv
1617                  *
1618                  * DPLLCMD is AWOL. Use chicken bits to propagate
1619                  * the value from DPLLBMD to either pipe B or C.
1620                  */
1621                 I915_WRITE(CBR4_VLV, pipe == PIPE_B ? CBR_DPLLBMD_PIPE_B : CBR_DPLLBMD_PIPE_C);
1622                 I915_WRITE(DPLL_MD(PIPE_B), pipe_config->dpll_hw_state.dpll_md);
1623                 I915_WRITE(CBR4_VLV, 0);
1624                 dev_priv->chv_dpll_md[pipe] = pipe_config->dpll_hw_state.dpll_md;
1625
1626                 /*
1627                  * DPLLB VGA mode also seems to cause problems.
1628                  * We should always have it disabled.
1629                  */
1630                 WARN_ON((I915_READ(DPLL(PIPE_B)) & DPLL_VGA_MODE_DIS) == 0);
1631         } else {
1632                 I915_WRITE(DPLL_MD(pipe), pipe_config->dpll_hw_state.dpll_md);
1633                 POSTING_READ(DPLL_MD(pipe));
1634         }
1635 }
1636
1637 static int intel_num_dvo_pipes(struct drm_device *dev)
1638 {
1639         struct intel_crtc *crtc;
1640         int count = 0;
1641
1642         for_each_intel_crtc(dev, crtc)
1643                 count += crtc->base.state->active &&
1644                         intel_pipe_has_type(crtc, INTEL_OUTPUT_DVO);
1645
1646         return count;
1647 }
1648
1649 static void i9xx_enable_pll(struct intel_crtc *crtc)
1650 {
1651         struct drm_device *dev = crtc->base.dev;
1652         struct drm_i915_private *dev_priv = dev->dev_private;
1653         i915_reg_t reg = DPLL(crtc->pipe);
1654         u32 dpll = crtc->config->dpll_hw_state.dpll;
1655
1656         assert_pipe_disabled(dev_priv, crtc->pipe);
1657
1658         /* PLL is protected by panel, make sure we can write it */
1659         if (IS_MOBILE(dev) && !IS_I830(dev))
1660                 assert_panel_unlocked(dev_priv, crtc->pipe);
1661
1662         /* Enable DVO 2x clock on both PLLs if necessary */
1663         if (IS_I830(dev) && intel_num_dvo_pipes(dev) > 0) {
1664                 /*
1665                  * It appears to be important that we don't enable this
1666                  * for the current pipe before otherwise configuring the
1667                  * PLL. No idea how this should be handled if multiple
1668                  * DVO outputs are enabled simultaneosly.
1669                  */
1670                 dpll |= DPLL_DVO_2X_MODE;
1671                 I915_WRITE(DPLL(!crtc->pipe),
1672                            I915_READ(DPLL(!crtc->pipe)) | DPLL_DVO_2X_MODE);
1673         }
1674
1675         /*
1676          * Apparently we need to have VGA mode enabled prior to changing
1677          * the P1/P2 dividers. Otherwise the DPLL will keep using the old
1678          * dividers, even though the register value does change.
1679          */
1680         I915_WRITE(reg, 0);
1681
1682         I915_WRITE(reg, dpll);
1683
1684         /* Wait for the clocks to stabilize. */
1685         POSTING_READ(reg);
1686         udelay(150);
1687
1688         if (INTEL_INFO(dev)->gen >= 4) {
1689                 I915_WRITE(DPLL_MD(crtc->pipe),
1690                            crtc->config->dpll_hw_state.dpll_md);
1691         } else {
1692                 /* The pixel multiplier can only be updated once the
1693                  * DPLL is enabled and the clocks are stable.
1694                  *
1695                  * So write it again.
1696                  */
1697                 I915_WRITE(reg, dpll);
1698         }
1699
1700         /* We do this three times for luck */
1701         I915_WRITE(reg, dpll);
1702         POSTING_READ(reg);
1703         udelay(150); /* wait for warmup */
1704         I915_WRITE(reg, dpll);
1705         POSTING_READ(reg);
1706         udelay(150); /* wait for warmup */
1707         I915_WRITE(reg, dpll);
1708         POSTING_READ(reg);
1709         udelay(150); /* wait for warmup */
1710 }
1711
1712 /**
1713  * i9xx_disable_pll - disable a PLL
1714  * @dev_priv: i915 private structure
1715  * @pipe: pipe PLL to disable
1716  *
1717  * Disable the PLL for @pipe, making sure the pipe is off first.
1718  *
1719  * Note!  This is for pre-ILK only.
1720  */
1721 static void i9xx_disable_pll(struct intel_crtc *crtc)
1722 {
1723         struct drm_device *dev = crtc->base.dev;
1724         struct drm_i915_private *dev_priv = dev->dev_private;
1725         enum pipe pipe = crtc->pipe;
1726
1727         /* Disable DVO 2x clock on both PLLs if necessary */
1728         if (IS_I830(dev) &&
1729             intel_pipe_has_type(crtc, INTEL_OUTPUT_DVO) &&
1730             !intel_num_dvo_pipes(dev)) {
1731                 I915_WRITE(DPLL(PIPE_B),
1732                            I915_READ(DPLL(PIPE_B)) & ~DPLL_DVO_2X_MODE);
1733                 I915_WRITE(DPLL(PIPE_A),
1734                            I915_READ(DPLL(PIPE_A)) & ~DPLL_DVO_2X_MODE);
1735         }
1736
1737         /* Don't disable pipe or pipe PLLs if needed */
1738         if ((pipe == PIPE_A && dev_priv->quirks & QUIRK_PIPEA_FORCE) ||
1739             (pipe == PIPE_B && dev_priv->quirks & QUIRK_PIPEB_FORCE))
1740                 return;
1741
1742         /* Make sure the pipe isn't still relying on us */
1743         assert_pipe_disabled(dev_priv, pipe);
1744
1745         I915_WRITE(DPLL(pipe), DPLL_VGA_MODE_DIS);
1746         POSTING_READ(DPLL(pipe));
1747 }
1748
1749 static void vlv_disable_pll(struct drm_i915_private *dev_priv, enum pipe pipe)
1750 {
1751         u32 val;
1752
1753         /* Make sure the pipe isn't still relying on us */
1754         assert_pipe_disabled(dev_priv, pipe);
1755
1756         val = DPLL_INTEGRATED_REF_CLK_VLV |
1757                 DPLL_REF_CLK_ENABLE_VLV | DPLL_VGA_MODE_DIS;
1758         if (pipe != PIPE_A)
1759                 val |= DPLL_INTEGRATED_CRI_CLK_VLV;
1760
1761         I915_WRITE(DPLL(pipe), val);
1762         POSTING_READ(DPLL(pipe));
1763 }
1764
1765 static void chv_disable_pll(struct drm_i915_private *dev_priv, enum pipe pipe)
1766 {
1767         enum dpio_channel port = vlv_pipe_to_channel(pipe);
1768         u32 val;
1769
1770         /* Make sure the pipe isn't still relying on us */
1771         assert_pipe_disabled(dev_priv, pipe);
1772
1773         val = DPLL_SSC_REF_CLK_CHV |
1774                 DPLL_REF_CLK_ENABLE_VLV | DPLL_VGA_MODE_DIS;
1775         if (pipe != PIPE_A)
1776                 val |= DPLL_INTEGRATED_CRI_CLK_VLV;
1777
1778         I915_WRITE(DPLL(pipe), val);
1779         POSTING_READ(DPLL(pipe));
1780
1781         mutex_lock(&dev_priv->sb_lock);
1782
1783         /* Disable 10bit clock to display controller */
1784         val = vlv_dpio_read(dev_priv, pipe, CHV_CMN_DW14(port));
1785         val &= ~DPIO_DCLKP_EN;
1786         vlv_dpio_write(dev_priv, pipe, CHV_CMN_DW14(port), val);
1787
1788         mutex_unlock(&dev_priv->sb_lock);
1789 }
1790
1791 void vlv_wait_port_ready(struct drm_i915_private *dev_priv,
1792                          struct intel_digital_port *dport,
1793                          unsigned int expected_mask)
1794 {
1795         u32 port_mask;
1796         i915_reg_t dpll_reg;
1797
1798         switch (dport->port) {
1799         case PORT_B:
1800                 port_mask = DPLL_PORTB_READY_MASK;
1801                 dpll_reg = DPLL(0);
1802                 break;
1803         case PORT_C:
1804                 port_mask = DPLL_PORTC_READY_MASK;
1805                 dpll_reg = DPLL(0);
1806                 expected_mask <<= 4;
1807                 break;
1808         case PORT_D:
1809                 port_mask = DPLL_PORTD_READY_MASK;
1810                 dpll_reg = DPIO_PHY_STATUS;
1811                 break;
1812         default:
1813                 BUG();
1814         }
1815
1816         if (wait_for((I915_READ(dpll_reg) & port_mask) == expected_mask, 1000))
1817                 WARN(1, "timed out waiting for port %c ready: got 0x%x, expected 0x%x\n",
1818                      port_name(dport->port), I915_READ(dpll_reg) & port_mask, expected_mask);
1819 }
1820
1821 static void ironlake_enable_pch_transcoder(struct drm_i915_private *dev_priv,
1822                                            enum pipe pipe)
1823 {
1824         struct drm_device *dev = dev_priv->dev;
1825         struct drm_crtc *crtc = dev_priv->pipe_to_crtc_mapping[pipe];
1826         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
1827         i915_reg_t reg;
1828         uint32_t val, pipeconf_val;
1829
1830         /* Make sure PCH DPLL is enabled */
1831         assert_shared_dpll_enabled(dev_priv, intel_crtc->config->shared_dpll);
1832
1833         /* FDI must be feeding us bits for PCH ports */
1834         assert_fdi_tx_enabled(dev_priv, pipe);
1835         assert_fdi_rx_enabled(dev_priv, pipe);
1836
1837         if (HAS_PCH_CPT(dev)) {
1838                 /* Workaround: Set the timing override bit before enabling the
1839                  * pch transcoder. */
1840                 reg = TRANS_CHICKEN2(pipe);
1841                 val = I915_READ(reg);
1842                 val |= TRANS_CHICKEN2_TIMING_OVERRIDE;
1843                 I915_WRITE(reg, val);
1844         }
1845
1846         reg = PCH_TRANSCONF(pipe);
1847         val = I915_READ(reg);
1848         pipeconf_val = I915_READ(PIPECONF(pipe));
1849
1850         if (HAS_PCH_IBX(dev_priv)) {
1851                 /*
1852                  * Make the BPC in transcoder be consistent with
1853                  * that in pipeconf reg. For HDMI we must use 8bpc
1854                  * here for both 8bpc and 12bpc.
1855                  */
1856                 val &= ~PIPECONF_BPC_MASK;
1857                 if (intel_pipe_has_type(intel_crtc, INTEL_OUTPUT_HDMI))
1858                         val |= PIPECONF_8BPC;
1859                 else
1860                         val |= pipeconf_val & PIPECONF_BPC_MASK;
1861         }
1862
1863         val &= ~TRANS_INTERLACE_MASK;
1864         if ((pipeconf_val & PIPECONF_INTERLACE_MASK) == PIPECONF_INTERLACED_ILK)
1865                 if (HAS_PCH_IBX(dev_priv) &&
1866                     intel_pipe_has_type(intel_crtc, INTEL_OUTPUT_SDVO))
1867                         val |= TRANS_LEGACY_INTERLACED_ILK;
1868                 else
1869                         val |= TRANS_INTERLACED;
1870         else
1871                 val |= TRANS_PROGRESSIVE;
1872
1873         I915_WRITE(reg, val | TRANS_ENABLE);
1874         if (wait_for(I915_READ(reg) & TRANS_STATE_ENABLE, 100))
1875                 DRM_ERROR("failed to enable transcoder %c\n", pipe_name(pipe));
1876 }
1877
1878 static void lpt_enable_pch_transcoder(struct drm_i915_private *dev_priv,
1879                                       enum transcoder cpu_transcoder)
1880 {
1881         u32 val, pipeconf_val;
1882
1883         /* FDI must be feeding us bits for PCH ports */
1884         assert_fdi_tx_enabled(dev_priv, (enum pipe) cpu_transcoder);
1885         assert_fdi_rx_enabled(dev_priv, TRANSCODER_A);
1886
1887         /* Workaround: set timing override bit. */
1888         val = I915_READ(TRANS_CHICKEN2(PIPE_A));
1889         val |= TRANS_CHICKEN2_TIMING_OVERRIDE;
1890         I915_WRITE(TRANS_CHICKEN2(PIPE_A), val);
1891
1892         val = TRANS_ENABLE;
1893         pipeconf_val = I915_READ(PIPECONF(cpu_transcoder));
1894
1895         if ((pipeconf_val & PIPECONF_INTERLACE_MASK_HSW) ==
1896             PIPECONF_INTERLACED_ILK)
1897                 val |= TRANS_INTERLACED;
1898         else
1899                 val |= TRANS_PROGRESSIVE;
1900
1901         I915_WRITE(LPT_TRANSCONF, val);
1902         if (wait_for(I915_READ(LPT_TRANSCONF) & TRANS_STATE_ENABLE, 100))
1903                 DRM_ERROR("Failed to enable PCH transcoder\n");
1904 }
1905
1906 static void ironlake_disable_pch_transcoder(struct drm_i915_private *dev_priv,
1907                                             enum pipe pipe)
1908 {
1909         struct drm_device *dev = dev_priv->dev;
1910         i915_reg_t reg;
1911         uint32_t val;
1912
1913         /* FDI relies on the transcoder */
1914         assert_fdi_tx_disabled(dev_priv, pipe);
1915         assert_fdi_rx_disabled(dev_priv, pipe);
1916
1917         /* Ports must be off as well */
1918         assert_pch_ports_disabled(dev_priv, pipe);
1919
1920         reg = PCH_TRANSCONF(pipe);
1921         val = I915_READ(reg);
1922         val &= ~TRANS_ENABLE;
1923         I915_WRITE(reg, val);
1924         /* wait for PCH transcoder off, transcoder state */
1925         if (wait_for((I915_READ(reg) & TRANS_STATE_ENABLE) == 0, 50))
1926                 DRM_ERROR("failed to disable transcoder %c\n", pipe_name(pipe));
1927
1928         if (HAS_PCH_CPT(dev)) {
1929                 /* Workaround: Clear the timing override chicken bit again. */
1930                 reg = TRANS_CHICKEN2(pipe);
1931                 val = I915_READ(reg);
1932                 val &= ~TRANS_CHICKEN2_TIMING_OVERRIDE;
1933                 I915_WRITE(reg, val);
1934         }
1935 }
1936
1937 static void lpt_disable_pch_transcoder(struct drm_i915_private *dev_priv)
1938 {
1939         u32 val;
1940
1941         val = I915_READ(LPT_TRANSCONF);
1942         val &= ~TRANS_ENABLE;
1943         I915_WRITE(LPT_TRANSCONF, val);
1944         /* wait for PCH transcoder off, transcoder state */
1945         if (wait_for((I915_READ(LPT_TRANSCONF) & TRANS_STATE_ENABLE) == 0, 50))
1946                 DRM_ERROR("Failed to disable PCH transcoder\n");
1947
1948         /* Workaround: clear timing override bit. */
1949         val = I915_READ(TRANS_CHICKEN2(PIPE_A));
1950         val &= ~TRANS_CHICKEN2_TIMING_OVERRIDE;
1951         I915_WRITE(TRANS_CHICKEN2(PIPE_A), val);
1952 }
1953
1954 /**
1955  * intel_enable_pipe - enable a pipe, asserting requirements
1956  * @crtc: crtc responsible for the pipe
1957  *
1958  * Enable @crtc's pipe, making sure that various hardware specific requirements
1959  * are met, if applicable, e.g. PLL enabled, LVDS pairs enabled, etc.
1960  */
1961 static void intel_enable_pipe(struct intel_crtc *crtc)
1962 {
1963         struct drm_device *dev = crtc->base.dev;
1964         struct drm_i915_private *dev_priv = dev->dev_private;
1965         enum pipe pipe = crtc->pipe;
1966         enum transcoder cpu_transcoder = crtc->config->cpu_transcoder;
1967         enum pipe pch_transcoder;
1968         i915_reg_t reg;
1969         u32 val;
1970
1971         DRM_DEBUG_KMS("enabling pipe %c\n", pipe_name(pipe));
1972
1973         assert_planes_disabled(dev_priv, pipe);
1974         assert_cursor_disabled(dev_priv, pipe);
1975         assert_sprites_disabled(dev_priv, pipe);
1976
1977         if (HAS_PCH_LPT(dev_priv))
1978                 pch_transcoder = TRANSCODER_A;
1979         else
1980                 pch_transcoder = pipe;
1981
1982         /*
1983          * A pipe without a PLL won't actually be able to drive bits from
1984          * a plane.  On ILK+ the pipe PLLs are integrated, so we don't
1985          * need the check.
1986          */
1987         if (HAS_GMCH_DISPLAY(dev_priv))
1988                 if (crtc->config->has_dsi_encoder)
1989                         assert_dsi_pll_enabled(dev_priv);
1990                 else
1991                         assert_pll_enabled(dev_priv, pipe);
1992         else {
1993                 if (crtc->config->has_pch_encoder) {
1994                         /* if driving the PCH, we need FDI enabled */
1995                         assert_fdi_rx_pll_enabled(dev_priv, pch_transcoder);
1996                         assert_fdi_tx_pll_enabled(dev_priv,
1997                                                   (enum pipe) cpu_transcoder);
1998                 }
1999                 /* FIXME: assert CPU port conditions for SNB+ */
2000         }
2001
2002         reg = PIPECONF(cpu_transcoder);
2003         val = I915_READ(reg);
2004         if (val & PIPECONF_ENABLE) {
2005                 WARN_ON(!((pipe == PIPE_A && dev_priv->quirks & QUIRK_PIPEA_FORCE) ||
2006                           (pipe == PIPE_B && dev_priv->quirks & QUIRK_PIPEB_FORCE)));
2007                 return;
2008         }
2009
2010         I915_WRITE(reg, val | PIPECONF_ENABLE);
2011         POSTING_READ(reg);
2012
2013         /*
2014          * Until the pipe starts DSL will read as 0, which would cause
2015          * an apparent vblank timestamp jump, which messes up also the
2016          * frame count when it's derived from the timestamps. So let's
2017          * wait for the pipe to start properly before we call
2018          * drm_crtc_vblank_on()
2019          */
2020         if (dev->max_vblank_count == 0 &&
2021             wait_for(intel_get_crtc_scanline(crtc) != crtc->scanline_offset, 50))
2022                 DRM_ERROR("pipe %c didn't start\n", pipe_name(pipe));
2023 }
2024
2025 /**
2026  * intel_disable_pipe - disable a pipe, asserting requirements
2027  * @crtc: crtc whose pipes is to be disabled
2028  *
2029  * Disable the pipe of @crtc, making sure that various hardware
2030  * specific requirements are met, if applicable, e.g. plane
2031  * disabled, panel fitter off, etc.
2032  *
2033  * Will wait until the pipe has shut down before returning.
2034  */
2035 static void intel_disable_pipe(struct intel_crtc *crtc)
2036 {
2037         struct drm_i915_private *dev_priv = crtc->base.dev->dev_private;
2038         enum transcoder cpu_transcoder = crtc->config->cpu_transcoder;
2039         enum pipe pipe = crtc->pipe;
2040         i915_reg_t reg;
2041         u32 val;
2042
2043         DRM_DEBUG_KMS("disabling pipe %c\n", pipe_name(pipe));
2044
2045         /*
2046          * Make sure planes won't keep trying to pump pixels to us,
2047          * or we might hang the display.
2048          */
2049         assert_planes_disabled(dev_priv, pipe);
2050         assert_cursor_disabled(dev_priv, pipe);
2051         assert_sprites_disabled(dev_priv, pipe);
2052
2053         reg = PIPECONF(cpu_transcoder);
2054         val = I915_READ(reg);
2055         if ((val & PIPECONF_ENABLE) == 0)
2056                 return;
2057
2058         /*
2059          * Double wide has implications for planes
2060          * so best keep it disabled when not needed.
2061          */
2062         if (crtc->config->double_wide)
2063                 val &= ~PIPECONF_DOUBLE_WIDE;
2064
2065         /* Don't disable pipe or pipe PLLs if needed */
2066         if (!(pipe == PIPE_A && dev_priv->quirks & QUIRK_PIPEA_FORCE) &&
2067             !(pipe == PIPE_B && dev_priv->quirks & QUIRK_PIPEB_FORCE))
2068                 val &= ~PIPECONF_ENABLE;
2069
2070         I915_WRITE(reg, val);
2071         if ((val & PIPECONF_ENABLE) == 0)
2072                 intel_wait_for_pipe_off(crtc);
2073 }
2074
2075 static bool need_vtd_wa(struct drm_device *dev)
2076 {
2077 #ifdef CONFIG_INTEL_IOMMU
2078         if (INTEL_INFO(dev)->gen >= 6 && intel_iommu_gfx_mapped)
2079                 return true;
2080 #endif
2081         return false;
2082 }
2083
2084 static unsigned int intel_tile_size(const struct drm_i915_private *dev_priv)
2085 {
2086         return IS_GEN2(dev_priv) ? 2048 : 4096;
2087 }
2088
2089 static unsigned int intel_tile_width_bytes(const struct drm_i915_private *dev_priv,
2090                                            uint64_t fb_modifier, unsigned int cpp)
2091 {
2092         switch (fb_modifier) {
2093         case DRM_FORMAT_MOD_NONE:
2094                 return cpp;
2095         case I915_FORMAT_MOD_X_TILED:
2096                 if (IS_GEN2(dev_priv))
2097                         return 128;
2098                 else
2099                         return 512;
2100         case I915_FORMAT_MOD_Y_TILED:
2101                 if (IS_GEN2(dev_priv) || HAS_128_BYTE_Y_TILING(dev_priv))
2102                         return 128;
2103                 else
2104                         return 512;
2105         case I915_FORMAT_MOD_Yf_TILED:
2106                 switch (cpp) {
2107                 case 1:
2108                         return 64;
2109                 case 2:
2110                 case 4:
2111                         return 128;
2112                 case 8:
2113                 case 16:
2114                         return 256;
2115                 default:
2116                         MISSING_CASE(cpp);
2117                         return cpp;
2118                 }
2119                 break;
2120         default:
2121                 MISSING_CASE(fb_modifier);
2122                 return cpp;
2123         }
2124 }
2125
2126 unsigned int intel_tile_height(const struct drm_i915_private *dev_priv,
2127                                uint64_t fb_modifier, unsigned int cpp)
2128 {
2129         if (fb_modifier == DRM_FORMAT_MOD_NONE)
2130                 return 1;
2131         else
2132                 return intel_tile_size(dev_priv) /
2133                         intel_tile_width_bytes(dev_priv, fb_modifier, cpp);
2134 }
2135
2136 /* Return the tile dimensions in pixel units */
2137 static void intel_tile_dims(const struct drm_i915_private *dev_priv,
2138                             unsigned int *tile_width,
2139                             unsigned int *tile_height,
2140                             uint64_t fb_modifier,
2141                             unsigned int cpp)
2142 {
2143         unsigned int tile_width_bytes =
2144                 intel_tile_width_bytes(dev_priv, fb_modifier, cpp);
2145
2146         *tile_width = tile_width_bytes / cpp;
2147         *tile_height = intel_tile_size(dev_priv) / tile_width_bytes;
2148 }
2149
2150 unsigned int
2151 intel_fb_align_height(struct drm_device *dev, unsigned int height,
2152                       uint32_t pixel_format, uint64_t fb_modifier)
2153 {
2154         unsigned int cpp = drm_format_plane_cpp(pixel_format, 0);
2155         unsigned int tile_height = intel_tile_height(to_i915(dev), fb_modifier, cpp);
2156
2157         return ALIGN(height, tile_height);
2158 }
2159
2160 unsigned int intel_rotation_info_size(const struct intel_rotation_info *rot_info)
2161 {
2162         unsigned int size = 0;
2163         int i;
2164
2165         for (i = 0 ; i < ARRAY_SIZE(rot_info->plane); i++)
2166                 size += rot_info->plane[i].width * rot_info->plane[i].height;
2167
2168         return size;
2169 }
2170
2171 static void
2172 intel_fill_fb_ggtt_view(struct i915_ggtt_view *view,
2173                         const struct drm_framebuffer *fb,
2174                         unsigned int rotation)
2175 {
2176         if (intel_rotation_90_or_270(rotation)) {
2177                 *view = i915_ggtt_view_rotated;
2178                 view->params.rotated = to_intel_framebuffer(fb)->rot_info;
2179         } else {
2180                 *view = i915_ggtt_view_normal;
2181         }
2182 }
2183
2184 static void
2185 intel_fill_fb_info(struct drm_i915_private *dev_priv,
2186                    struct drm_framebuffer *fb)
2187 {
2188         struct intel_rotation_info *info = &to_intel_framebuffer(fb)->rot_info;
2189         unsigned int tile_size, tile_width, tile_height, cpp;
2190
2191         tile_size = intel_tile_size(dev_priv);
2192
2193         cpp = drm_format_plane_cpp(fb->pixel_format, 0);
2194         intel_tile_dims(dev_priv, &tile_width, &tile_height,
2195                         fb->modifier[0], cpp);
2196
2197         info->plane[0].width = DIV_ROUND_UP(fb->pitches[0], tile_width * cpp);
2198         info->plane[0].height = DIV_ROUND_UP(fb->height, tile_height);
2199
2200         if (info->pixel_format == DRM_FORMAT_NV12) {
2201                 cpp = drm_format_plane_cpp(fb->pixel_format, 1);
2202                 intel_tile_dims(dev_priv, &tile_width, &tile_height,
2203                                 fb->modifier[1], cpp);
2204
2205                 info->uv_offset = fb->offsets[1];
2206                 info->plane[1].width = DIV_ROUND_UP(fb->pitches[1], tile_width * cpp);
2207                 info->plane[1].height = DIV_ROUND_UP(fb->height / 2, tile_height);
2208         }
2209 }
2210
2211 static unsigned int intel_linear_alignment(const struct drm_i915_private *dev_priv)
2212 {
2213         if (INTEL_INFO(dev_priv)->gen >= 9)
2214                 return 256 * 1024;
2215         else if (IS_BROADWATER(dev_priv) || IS_CRESTLINE(dev_priv) ||
2216                  IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv))
2217                 return 128 * 1024;
2218         else if (INTEL_INFO(dev_priv)->gen >= 4)
2219                 return 4 * 1024;
2220         else
2221                 return 0;
2222 }
2223
2224 static unsigned int intel_surf_alignment(const struct drm_i915_private *dev_priv,
2225                                          uint64_t fb_modifier)
2226 {
2227         switch (fb_modifier) {
2228         case DRM_FORMAT_MOD_NONE:
2229                 return intel_linear_alignment(dev_priv);
2230         case I915_FORMAT_MOD_X_TILED:
2231                 if (INTEL_INFO(dev_priv)->gen >= 9)
2232                         return 256 * 1024;
2233                 return 0;
2234         case I915_FORMAT_MOD_Y_TILED:
2235         case I915_FORMAT_MOD_Yf_TILED:
2236                 return 1 * 1024 * 1024;
2237         default:
2238                 MISSING_CASE(fb_modifier);
2239                 return 0;
2240         }
2241 }
2242
2243 int
2244 intel_pin_and_fence_fb_obj(struct drm_framebuffer *fb,
2245                            unsigned int rotation)
2246 {
2247         struct drm_device *dev = fb->dev;
2248         struct drm_i915_private *dev_priv = dev->dev_private;
2249         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
2250         struct i915_ggtt_view view;
2251         u32 alignment;
2252         int ret;
2253
2254         WARN_ON(!mutex_is_locked(&dev->struct_mutex));
2255
2256         alignment = intel_surf_alignment(dev_priv, fb->modifier[0]);
2257
2258         intel_fill_fb_ggtt_view(&view, fb, rotation);
2259
2260         /* Note that the w/a also requires 64 PTE of padding following the
2261          * bo. We currently fill all unused PTE with the shadow page and so
2262          * we should always have valid PTE following the scanout preventing
2263          * the VT-d warning.
2264          */
2265         if (need_vtd_wa(dev) && alignment < 256 * 1024)
2266                 alignment = 256 * 1024;
2267
2268         /*
2269          * Global gtt pte registers are special registers which actually forward
2270          * writes to a chunk of system memory. Which means that there is no risk
2271          * that the register values disappear as soon as we call
2272          * intel_runtime_pm_put(), so it is correct to wrap only the
2273          * pin/unpin/fence and not more.
2274          */
2275         intel_runtime_pm_get(dev_priv);
2276
2277         ret = i915_gem_object_pin_to_display_plane(obj, alignment,
2278                                                    &view);
2279         if (ret)
2280                 goto err_pm;
2281
2282         /* Install a fence for tiled scan-out. Pre-i965 always needs a
2283          * fence, whereas 965+ only requires a fence if using
2284          * framebuffer compression.  For simplicity, we always install
2285          * a fence as the cost is not that onerous.
2286          */
2287         if (view.type == I915_GGTT_VIEW_NORMAL) {
2288                 ret = i915_gem_object_get_fence(obj);
2289                 if (ret == -EDEADLK) {
2290                         /*
2291                          * -EDEADLK means there are no free fences
2292                          * no pending flips.
2293                          *
2294                          * This is propagated to atomic, but it uses
2295                          * -EDEADLK to force a locking recovery, so
2296                          * change the returned error to -EBUSY.
2297                          */
2298                         ret = -EBUSY;
2299                         goto err_unpin;
2300                 } else if (ret)
2301                         goto err_unpin;
2302
2303                 i915_gem_object_pin_fence(obj);
2304         }
2305
2306         intel_runtime_pm_put(dev_priv);
2307         return 0;
2308
2309 err_unpin:
2310         i915_gem_object_unpin_from_display_plane(obj, &view);
2311 err_pm:
2312         intel_runtime_pm_put(dev_priv);
2313         return ret;
2314 }
2315
2316 void intel_unpin_fb_obj(struct drm_framebuffer *fb, unsigned int rotation)
2317 {
2318         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
2319         struct i915_ggtt_view view;
2320
2321         WARN_ON(!mutex_is_locked(&obj->base.dev->struct_mutex));
2322
2323         intel_fill_fb_ggtt_view(&view, fb, rotation);
2324
2325         if (view.type == I915_GGTT_VIEW_NORMAL)
2326                 i915_gem_object_unpin_fence(obj);
2327
2328         i915_gem_object_unpin_from_display_plane(obj, &view);
2329 }
2330
2331 /*
2332  * Adjust the tile offset by moving the difference into
2333  * the x/y offsets.
2334  *
2335  * Input tile dimensions and pitch must already be
2336  * rotated to match x and y, and in pixel units.
2337  */
2338 static u32 intel_adjust_tile_offset(int *x, int *y,
2339                                     unsigned int tile_width,
2340                                     unsigned int tile_height,
2341                                     unsigned int tile_size,
2342                                     unsigned int pitch_tiles,
2343                                     u32 old_offset,
2344                                     u32 new_offset)
2345 {
2346         unsigned int tiles;
2347
2348         WARN_ON(old_offset & (tile_size - 1));
2349         WARN_ON(new_offset & (tile_size - 1));
2350         WARN_ON(new_offset > old_offset);
2351
2352         tiles = (old_offset - new_offset) / tile_size;
2353
2354         *y += tiles / pitch_tiles * tile_height;
2355         *x += tiles % pitch_tiles * tile_width;
2356
2357         return new_offset;
2358 }
2359
2360 /*
2361  * Computes the linear offset to the base tile and adjusts
2362  * x, y. bytes per pixel is assumed to be a power-of-two.
2363  *
2364  * In the 90/270 rotated case, x and y are assumed
2365  * to be already rotated to match the rotated GTT view, and
2366  * pitch is the tile_height aligned framebuffer height.
2367  */
2368 u32 intel_compute_tile_offset(int *x, int *y,
2369                               const struct drm_framebuffer *fb, int plane,
2370                               unsigned int pitch,
2371                               unsigned int rotation)
2372 {
2373         const struct drm_i915_private *dev_priv = to_i915(fb->dev);
2374         uint64_t fb_modifier = fb->modifier[plane];
2375         unsigned int cpp = drm_format_plane_cpp(fb->pixel_format, plane);
2376         u32 offset, offset_aligned, alignment;
2377
2378         alignment = intel_surf_alignment(dev_priv, fb_modifier);
2379         if (alignment)
2380                 alignment--;
2381
2382         if (fb_modifier != DRM_FORMAT_MOD_NONE) {
2383                 unsigned int tile_size, tile_width, tile_height;
2384                 unsigned int tile_rows, tiles, pitch_tiles;
2385
2386                 tile_size = intel_tile_size(dev_priv);
2387                 intel_tile_dims(dev_priv, &tile_width, &tile_height,
2388                                 fb_modifier, cpp);
2389
2390                 if (intel_rotation_90_or_270(rotation)) {
2391                         pitch_tiles = pitch / tile_height;
2392                         swap(tile_width, tile_height);
2393                 } else {
2394                         pitch_tiles = pitch / (tile_width * cpp);
2395                 }
2396
2397                 tile_rows = *y / tile_height;
2398                 *y %= tile_height;
2399
2400                 tiles = *x / tile_width;
2401                 *x %= tile_width;
2402
2403                 offset = (tile_rows * pitch_tiles + tiles) * tile_size;
2404                 offset_aligned = offset & ~alignment;
2405
2406                 intel_adjust_tile_offset(x, y, tile_width, tile_height,
2407                                          tile_size, pitch_tiles,
2408                                          offset, offset_aligned);
2409         } else {
2410                 offset = *y * pitch + *x * cpp;
2411                 offset_aligned = offset & ~alignment;
2412
2413                 *y = (offset & alignment) / pitch;
2414                 *x = ((offset & alignment) - *y * pitch) / cpp;
2415         }
2416
2417         return offset_aligned;
2418 }
2419
2420 static int i9xx_format_to_fourcc(int format)
2421 {
2422         switch (format) {
2423         case DISPPLANE_8BPP:
2424                 return DRM_FORMAT_C8;
2425         case DISPPLANE_BGRX555:
2426                 return DRM_FORMAT_XRGB1555;
2427         case DISPPLANE_BGRX565:
2428                 return DRM_FORMAT_RGB565;
2429         default:
2430         case DISPPLANE_BGRX888:
2431                 return DRM_FORMAT_XRGB8888;
2432         case DISPPLANE_RGBX888:
2433                 return DRM_FORMAT_XBGR8888;
2434         case DISPPLANE_BGRX101010:
2435                 return DRM_FORMAT_XRGB2101010;
2436         case DISPPLANE_RGBX101010:
2437                 return DRM_FORMAT_XBGR2101010;
2438         }
2439 }
2440
2441 static int skl_format_to_fourcc(int format, bool rgb_order, bool alpha)
2442 {
2443         switch (format) {
2444         case PLANE_CTL_FORMAT_RGB_565:
2445                 return DRM_FORMAT_RGB565;
2446         default:
2447         case PLANE_CTL_FORMAT_XRGB_8888:
2448                 if (rgb_order) {
2449                         if (alpha)
2450                                 return DRM_FORMAT_ABGR8888;
2451                         else
2452                                 return DRM_FORMAT_XBGR8888;
2453                 } else {
2454                         if (alpha)
2455                                 return DRM_FORMAT_ARGB8888;
2456                         else
2457                                 return DRM_FORMAT_XRGB8888;
2458                 }
2459         case PLANE_CTL_FORMAT_XRGB_2101010:
2460                 if (rgb_order)
2461                         return DRM_FORMAT_XBGR2101010;
2462                 else
2463                         return DRM_FORMAT_XRGB2101010;
2464         }
2465 }
2466
2467 static bool
2468 intel_alloc_initial_plane_obj(struct intel_crtc *crtc,
2469                               struct intel_initial_plane_config *plane_config)
2470 {
2471         struct drm_device *dev = crtc->base.dev;
2472         struct drm_i915_private *dev_priv = to_i915(dev);
2473         struct i915_ggtt *ggtt = &dev_priv->ggtt;
2474         struct drm_i915_gem_object *obj = NULL;
2475         struct drm_mode_fb_cmd2 mode_cmd = { 0 };
2476         struct drm_framebuffer *fb = &plane_config->fb->base;
2477         u32 base_aligned = round_down(plane_config->base, PAGE_SIZE);
2478         u32 size_aligned = round_up(plane_config->base + plane_config->size,
2479                                     PAGE_SIZE);
2480
2481         size_aligned -= base_aligned;
2482
2483         if (plane_config->size == 0)
2484                 return false;
2485
2486         /* If the FB is too big, just don't use it since fbdev is not very
2487          * important and we should probably use that space with FBC or other
2488          * features. */
2489         if (size_aligned * 2 > ggtt->stolen_usable_size)
2490                 return false;
2491
2492         mutex_lock(&dev->struct_mutex);
2493
2494         obj = i915_gem_object_create_stolen_for_preallocated(dev,
2495                                                              base_aligned,
2496                                                              base_aligned,
2497                                                              size_aligned);
2498         if (!obj) {
2499                 mutex_unlock(&dev->struct_mutex);
2500                 return false;
2501         }
2502
2503         obj->tiling_mode = plane_config->tiling;
2504         if (obj->tiling_mode == I915_TILING_X)
2505                 obj->stride = fb->pitches[0];
2506
2507         mode_cmd.pixel_format = fb->pixel_format;
2508         mode_cmd.width = fb->width;
2509         mode_cmd.height = fb->height;
2510         mode_cmd.pitches[0] = fb->pitches[0];
2511         mode_cmd.modifier[0] = fb->modifier[0];
2512         mode_cmd.flags = DRM_MODE_FB_MODIFIERS;
2513
2514         if (intel_framebuffer_init(dev, to_intel_framebuffer(fb),
2515                                    &mode_cmd, obj)) {
2516                 DRM_DEBUG_KMS("intel fb init failed\n");
2517                 goto out_unref_obj;
2518         }
2519
2520         mutex_unlock(&dev->struct_mutex);
2521
2522         DRM_DEBUG_KMS("initial plane fb obj %p\n", obj);
2523         return true;
2524
2525 out_unref_obj:
2526         drm_gem_object_unreference(&obj->base);
2527         mutex_unlock(&dev->struct_mutex);
2528         return false;
2529 }
2530
2531 /* Update plane->state->fb to match plane->fb after driver-internal updates */
2532 static void
2533 update_state_fb(struct drm_plane *plane)
2534 {
2535         if (plane->fb == plane->state->fb)
2536                 return;
2537
2538         if (plane->state->fb)
2539                 drm_framebuffer_unreference(plane->state->fb);
2540         plane->state->fb = plane->fb;
2541         if (plane->state->fb)
2542                 drm_framebuffer_reference(plane->state->fb);
2543 }
2544
2545 static void
2546 intel_find_initial_plane_obj(struct intel_crtc *intel_crtc,
2547                              struct intel_initial_plane_config *plane_config)
2548 {
2549         struct drm_device *dev = intel_crtc->base.dev;
2550         struct drm_i915_private *dev_priv = dev->dev_private;
2551         struct drm_crtc *c;
2552         struct intel_crtc *i;
2553         struct drm_i915_gem_object *obj;
2554         struct drm_plane *primary = intel_crtc->base.primary;
2555         struct drm_plane_state *plane_state = primary->state;
2556         struct drm_crtc_state *crtc_state = intel_crtc->base.state;
2557         struct intel_plane *intel_plane = to_intel_plane(primary);
2558         struct intel_plane_state *intel_state =
2559                 to_intel_plane_state(plane_state);
2560         struct drm_framebuffer *fb;
2561
2562         if (!plane_config->fb)
2563                 return;
2564
2565         if (intel_alloc_initial_plane_obj(intel_crtc, plane_config)) {
2566                 fb = &plane_config->fb->base;
2567                 goto valid_fb;
2568         }
2569
2570         kfree(plane_config->fb);
2571
2572         /*
2573          * Failed to alloc the obj, check to see if we should share
2574          * an fb with another CRTC instead
2575          */
2576         for_each_crtc(dev, c) {
2577                 i = to_intel_crtc(c);
2578
2579                 if (c == &intel_crtc->base)
2580                         continue;
2581
2582                 if (!i->active)
2583                         continue;
2584
2585                 fb = c->primary->fb;
2586                 if (!fb)
2587                         continue;
2588
2589                 obj = intel_fb_obj(fb);
2590                 if (i915_gem_obj_ggtt_offset(obj) == plane_config->base) {
2591                         drm_framebuffer_reference(fb);
2592                         goto valid_fb;
2593                 }
2594         }
2595
2596         /*
2597          * We've failed to reconstruct the BIOS FB.  Current display state
2598          * indicates that the primary plane is visible, but has a NULL FB,
2599          * which will lead to problems later if we don't fix it up.  The
2600          * simplest solution is to just disable the primary plane now and
2601          * pretend the BIOS never had it enabled.
2602          */
2603         to_intel_plane_state(plane_state)->visible = false;
2604         crtc_state->plane_mask &= ~(1 << drm_plane_index(primary));
2605         intel_pre_disable_primary_noatomic(&intel_crtc->base);
2606         intel_plane->disable_plane(primary, &intel_crtc->base);
2607
2608         return;
2609
2610 valid_fb:
2611         plane_state->src_x = 0;
2612         plane_state->src_y = 0;
2613         plane_state->src_w = fb->width << 16;
2614         plane_state->src_h = fb->height << 16;
2615
2616         plane_state->crtc_x = 0;
2617         plane_state->crtc_y = 0;
2618         plane_state->crtc_w = fb->width;
2619         plane_state->crtc_h = fb->height;
2620
2621         intel_state->src.x1 = plane_state->src_x;
2622         intel_state->src.y1 = plane_state->src_y;
2623         intel_state->src.x2 = plane_state->src_x + plane_state->src_w;
2624         intel_state->src.y2 = plane_state->src_y + plane_state->src_h;
2625         intel_state->dst.x1 = plane_state->crtc_x;
2626         intel_state->dst.y1 = plane_state->crtc_y;
2627         intel_state->dst.x2 = plane_state->crtc_x + plane_state->crtc_w;
2628         intel_state->dst.y2 = plane_state->crtc_y + plane_state->crtc_h;
2629
2630         obj = intel_fb_obj(fb);
2631         if (obj->tiling_mode != I915_TILING_NONE)
2632                 dev_priv->preserve_bios_swizzle = true;
2633
2634         drm_framebuffer_reference(fb);
2635         primary->fb = primary->state->fb = fb;
2636         primary->crtc = primary->state->crtc = &intel_crtc->base;
2637         intel_crtc->base.state->plane_mask |= (1 << drm_plane_index(primary));
2638         obj->frontbuffer_bits |= to_intel_plane(primary)->frontbuffer_bit;
2639 }
2640
2641 static void i9xx_update_primary_plane(struct drm_plane *primary,
2642                                       const struct intel_crtc_state *crtc_state,
2643                                       const struct intel_plane_state *plane_state)
2644 {
2645         struct drm_device *dev = primary->dev;
2646         struct drm_i915_private *dev_priv = dev->dev_private;
2647         struct intel_crtc *intel_crtc = to_intel_crtc(crtc_state->base.crtc);
2648         struct drm_framebuffer *fb = plane_state->base.fb;
2649         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
2650         int plane = intel_crtc->plane;
2651         u32 linear_offset;
2652         u32 dspcntr;
2653         i915_reg_t reg = DSPCNTR(plane);
2654         unsigned int rotation = plane_state->base.rotation;
2655         int cpp = drm_format_plane_cpp(fb->pixel_format, 0);
2656         int x = plane_state->src.x1 >> 16;
2657         int y = plane_state->src.y1 >> 16;
2658
2659         dspcntr = DISPPLANE_GAMMA_ENABLE;
2660
2661         dspcntr |= DISPLAY_PLANE_ENABLE;
2662
2663         if (INTEL_INFO(dev)->gen < 4) {
2664                 if (intel_crtc->pipe == PIPE_B)
2665                         dspcntr |= DISPPLANE_SEL_PIPE_B;
2666
2667                 /* pipesrc and dspsize control the size that is scaled from,
2668                  * which should always be the user's requested size.
2669                  */
2670                 I915_WRITE(DSPSIZE(plane),
2671                            ((crtc_state->pipe_src_h - 1) << 16) |
2672                            (crtc_state->pipe_src_w - 1));
2673                 I915_WRITE(DSPPOS(plane), 0);
2674         } else if (IS_CHERRYVIEW(dev) && plane == PLANE_B) {
2675                 I915_WRITE(PRIMSIZE(plane),
2676                            ((crtc_state->pipe_src_h - 1) << 16) |
2677                            (crtc_state->pipe_src_w - 1));
2678                 I915_WRITE(PRIMPOS(plane), 0);
2679                 I915_WRITE(PRIMCNSTALPHA(plane), 0);
2680         }
2681
2682         switch (fb->pixel_format) {
2683         case DRM_FORMAT_C8:
2684                 dspcntr |= DISPPLANE_8BPP;
2685                 break;
2686         case DRM_FORMAT_XRGB1555:
2687                 dspcntr |= DISPPLANE_BGRX555;
2688                 break;
2689         case DRM_FORMAT_RGB565:
2690                 dspcntr |= DISPPLANE_BGRX565;
2691                 break;
2692         case DRM_FORMAT_XRGB8888:
2693                 dspcntr |= DISPPLANE_BGRX888;
2694                 break;
2695         case DRM_FORMAT_XBGR8888:
2696                 dspcntr |= DISPPLANE_RGBX888;
2697                 break;
2698         case DRM_FORMAT_XRGB2101010:
2699                 dspcntr |= DISPPLANE_BGRX101010;
2700                 break;
2701         case DRM_FORMAT_XBGR2101010:
2702                 dspcntr |= DISPPLANE_RGBX101010;
2703                 break;
2704         default:
2705                 BUG();
2706         }
2707
2708         if (INTEL_INFO(dev)->gen >= 4 &&
2709             obj->tiling_mode != I915_TILING_NONE)
2710                 dspcntr |= DISPPLANE_TILED;
2711
2712         if (IS_G4X(dev))
2713                 dspcntr |= DISPPLANE_TRICKLE_FEED_DISABLE;
2714
2715         linear_offset = y * fb->pitches[0] + x * cpp;
2716
2717         if (INTEL_INFO(dev)->gen >= 4) {
2718                 intel_crtc->dspaddr_offset =
2719                         intel_compute_tile_offset(&x, &y, fb, 0,
2720                                                   fb->pitches[0], rotation);
2721                 linear_offset -= intel_crtc->dspaddr_offset;
2722         } else {
2723                 intel_crtc->dspaddr_offset = linear_offset;
2724         }
2725
2726         if (rotation == BIT(DRM_ROTATE_180)) {
2727                 dspcntr |= DISPPLANE_ROTATE_180;
2728
2729                 x += (crtc_state->pipe_src_w - 1);
2730                 y += (crtc_state->pipe_src_h - 1);
2731
2732                 /* Finding the last pixel of the last line of the display
2733                 data and adding to linear_offset*/
2734                 linear_offset +=
2735                         (crtc_state->pipe_src_h - 1) * fb->pitches[0] +
2736                         (crtc_state->pipe_src_w - 1) * cpp;
2737         }
2738
2739         intel_crtc->adjusted_x = x;
2740         intel_crtc->adjusted_y = y;
2741
2742         I915_WRITE(reg, dspcntr);
2743
2744         I915_WRITE(DSPSTRIDE(plane), fb->pitches[0]);
2745         if (INTEL_INFO(dev)->gen >= 4) {
2746                 I915_WRITE(DSPSURF(plane),
2747                            i915_gem_obj_ggtt_offset(obj) + intel_crtc->dspaddr_offset);
2748                 I915_WRITE(DSPTILEOFF(plane), (y << 16) | x);
2749                 I915_WRITE(DSPLINOFF(plane), linear_offset);
2750         } else
2751                 I915_WRITE(DSPADDR(plane), i915_gem_obj_ggtt_offset(obj) + linear_offset);
2752         POSTING_READ(reg);
2753 }
2754
2755 static void i9xx_disable_primary_plane(struct drm_plane *primary,
2756                                        struct drm_crtc *crtc)
2757 {
2758         struct drm_device *dev = crtc->dev;
2759         struct drm_i915_private *dev_priv = dev->dev_private;
2760         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
2761         int plane = intel_crtc->plane;
2762
2763         I915_WRITE(DSPCNTR(plane), 0);
2764         if (INTEL_INFO(dev_priv)->gen >= 4)
2765                 I915_WRITE(DSPSURF(plane), 0);
2766         else
2767                 I915_WRITE(DSPADDR(plane), 0);
2768         POSTING_READ(DSPCNTR(plane));
2769 }
2770
2771 static void ironlake_update_primary_plane(struct drm_plane *primary,
2772                                           const struct intel_crtc_state *crtc_state,
2773                                           const struct intel_plane_state *plane_state)
2774 {
2775         struct drm_device *dev = primary->dev;
2776         struct drm_i915_private *dev_priv = dev->dev_private;
2777         struct intel_crtc *intel_crtc = to_intel_crtc(crtc_state->base.crtc);
2778         struct drm_framebuffer *fb = plane_state->base.fb;
2779         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
2780         int plane = intel_crtc->plane;
2781         u32 linear_offset;
2782         u32 dspcntr;
2783         i915_reg_t reg = DSPCNTR(plane);
2784         unsigned int rotation = plane_state->base.rotation;
2785         int cpp = drm_format_plane_cpp(fb->pixel_format, 0);
2786         int x = plane_state->src.x1 >> 16;
2787         int y = plane_state->src.y1 >> 16;
2788
2789         dspcntr = DISPPLANE_GAMMA_ENABLE;
2790         dspcntr |= DISPLAY_PLANE_ENABLE;
2791
2792         if (IS_HASWELL(dev) || IS_BROADWELL(dev))
2793                 dspcntr |= DISPPLANE_PIPE_CSC_ENABLE;
2794
2795         switch (fb->pixel_format) {
2796         case DRM_FORMAT_C8:
2797                 dspcntr |= DISPPLANE_8BPP;
2798                 break;
2799         case DRM_FORMAT_RGB565:
2800                 dspcntr |= DISPPLANE_BGRX565;
2801                 break;
2802         case DRM_FORMAT_XRGB8888:
2803                 dspcntr |= DISPPLANE_BGRX888;
2804                 break;
2805         case DRM_FORMAT_XBGR8888:
2806                 dspcntr |= DISPPLANE_RGBX888;
2807                 break;
2808         case DRM_FORMAT_XRGB2101010:
2809                 dspcntr |= DISPPLANE_BGRX101010;
2810                 break;
2811         case DRM_FORMAT_XBGR2101010:
2812                 dspcntr |= DISPPLANE_RGBX101010;
2813                 break;
2814         default:
2815                 BUG();
2816         }
2817
2818         if (obj->tiling_mode != I915_TILING_NONE)
2819                 dspcntr |= DISPPLANE_TILED;
2820
2821         if (!IS_HASWELL(dev) && !IS_BROADWELL(dev))
2822                 dspcntr |= DISPPLANE_TRICKLE_FEED_DISABLE;
2823
2824         linear_offset = y * fb->pitches[0] + x * cpp;
2825         intel_crtc->dspaddr_offset =
2826                 intel_compute_tile_offset(&x, &y, fb, 0,
2827                                           fb->pitches[0], rotation);
2828         linear_offset -= intel_crtc->dspaddr_offset;
2829         if (rotation == BIT(DRM_ROTATE_180)) {
2830                 dspcntr |= DISPPLANE_ROTATE_180;
2831
2832                 if (!IS_HASWELL(dev) && !IS_BROADWELL(dev)) {
2833                         x += (crtc_state->pipe_src_w - 1);
2834                         y += (crtc_state->pipe_src_h - 1);
2835
2836                         /* Finding the last pixel of the last line of the display
2837                         data and adding to linear_offset*/
2838                         linear_offset +=
2839                                 (crtc_state->pipe_src_h - 1) * fb->pitches[0] +
2840                                 (crtc_state->pipe_src_w - 1) * cpp;
2841                 }
2842         }
2843
2844         intel_crtc->adjusted_x = x;
2845         intel_crtc->adjusted_y = y;
2846
2847         I915_WRITE(reg, dspcntr);
2848
2849         I915_WRITE(DSPSTRIDE(plane), fb->pitches[0]);
2850         I915_WRITE(DSPSURF(plane),
2851                    i915_gem_obj_ggtt_offset(obj) + intel_crtc->dspaddr_offset);
2852         if (IS_HASWELL(dev) || IS_BROADWELL(dev)) {
2853                 I915_WRITE(DSPOFFSET(plane), (y << 16) | x);
2854         } else {
2855                 I915_WRITE(DSPTILEOFF(plane), (y << 16) | x);
2856                 I915_WRITE(DSPLINOFF(plane), linear_offset);
2857         }
2858         POSTING_READ(reg);
2859 }
2860
2861 u32 intel_fb_stride_alignment(const struct drm_i915_private *dev_priv,
2862                               uint64_t fb_modifier, uint32_t pixel_format)
2863 {
2864         if (fb_modifier == DRM_FORMAT_MOD_NONE) {
2865                 return 64;
2866         } else {
2867                 int cpp = drm_format_plane_cpp(pixel_format, 0);
2868
2869                 return intel_tile_width_bytes(dev_priv, fb_modifier, cpp);
2870         }
2871 }
2872
2873 u32 intel_plane_obj_offset(struct intel_plane *intel_plane,
2874                            struct drm_i915_gem_object *obj,
2875                            unsigned int plane)
2876 {
2877         struct i915_ggtt_view view;
2878         struct i915_vma *vma;
2879         u64 offset;
2880
2881         intel_fill_fb_ggtt_view(&view, intel_plane->base.state->fb,
2882                                 intel_plane->base.state->rotation);
2883
2884         vma = i915_gem_obj_to_ggtt_view(obj, &view);
2885         if (WARN(!vma, "ggtt vma for display object not found! (view=%u)\n",
2886                 view.type))
2887                 return -1;
2888
2889         offset = vma->node.start;
2890
2891         if (plane == 1) {
2892                 offset += vma->ggtt_view.params.rotated.uv_start_page *
2893                           PAGE_SIZE;
2894         }
2895
2896         WARN_ON(upper_32_bits(offset));
2897
2898         return lower_32_bits(offset);
2899 }
2900
2901 static void skl_detach_scaler(struct intel_crtc *intel_crtc, int id)
2902 {
2903         struct drm_device *dev = intel_crtc->base.dev;
2904         struct drm_i915_private *dev_priv = dev->dev_private;
2905
2906         I915_WRITE(SKL_PS_CTRL(intel_crtc->pipe, id), 0);
2907         I915_WRITE(SKL_PS_WIN_POS(intel_crtc->pipe, id), 0);
2908         I915_WRITE(SKL_PS_WIN_SZ(intel_crtc->pipe, id), 0);
2909 }
2910
2911 /*
2912  * This function detaches (aka. unbinds) unused scalers in hardware
2913  */
2914 static void skl_detach_scalers(struct intel_crtc *intel_crtc)
2915 {
2916         struct intel_crtc_scaler_state *scaler_state;
2917         int i;
2918
2919         scaler_state = &intel_crtc->config->scaler_state;
2920
2921         /* loop through and disable scalers that aren't in use */
2922         for (i = 0; i < intel_crtc->num_scalers; i++) {
2923                 if (!scaler_state->scalers[i].in_use)
2924                         skl_detach_scaler(intel_crtc, i);
2925         }
2926 }
2927
2928 u32 skl_plane_ctl_format(uint32_t pixel_format)
2929 {
2930         switch (pixel_format) {
2931         case DRM_FORMAT_C8:
2932                 return PLANE_CTL_FORMAT_INDEXED;
2933         case DRM_FORMAT_RGB565:
2934                 return PLANE_CTL_FORMAT_RGB_565;
2935         case DRM_FORMAT_XBGR8888:
2936                 return PLANE_CTL_FORMAT_XRGB_8888 | PLANE_CTL_ORDER_RGBX;
2937         case DRM_FORMAT_XRGB8888:
2938                 return PLANE_CTL_FORMAT_XRGB_8888;
2939         /*
2940          * XXX: For ARBG/ABGR formats we default to expecting scanout buffers
2941          * to be already pre-multiplied. We need to add a knob (or a different
2942          * DRM_FORMAT) for user-space to configure that.
2943          */
2944         case DRM_FORMAT_ABGR8888:
2945                 return PLANE_CTL_FORMAT_XRGB_8888 | PLANE_CTL_ORDER_RGBX |
2946                         PLANE_CTL_ALPHA_SW_PREMULTIPLY;
2947         case DRM_FORMAT_ARGB8888:
2948                 return PLANE_CTL_FORMAT_XRGB_8888 |
2949                         PLANE_CTL_ALPHA_SW_PREMULTIPLY;
2950         case DRM_FORMAT_XRGB2101010:
2951                 return PLANE_CTL_FORMAT_XRGB_2101010;
2952         case DRM_FORMAT_XBGR2101010:
2953                 return PLANE_CTL_ORDER_RGBX | PLANE_CTL_FORMAT_XRGB_2101010;
2954         case DRM_FORMAT_YUYV:
2955                 return PLANE_CTL_FORMAT_YUV422 | PLANE_CTL_YUV422_YUYV;
2956         case DRM_FORMAT_YVYU:
2957                 return PLANE_CTL_FORMAT_YUV422 | PLANE_CTL_YUV422_YVYU;
2958         case DRM_FORMAT_UYVY:
2959                 return PLANE_CTL_FORMAT_YUV422 | PLANE_CTL_YUV422_UYVY;
2960         case DRM_FORMAT_VYUY:
2961                 return PLANE_CTL_FORMAT_YUV422 | PLANE_CTL_YUV422_VYUY;
2962         default:
2963                 MISSING_CASE(pixel_format);
2964         }
2965
2966         return 0;
2967 }
2968
2969 u32 skl_plane_ctl_tiling(uint64_t fb_modifier)
2970 {
2971         switch (fb_modifier) {
2972         case DRM_FORMAT_MOD_NONE:
2973                 break;
2974         case I915_FORMAT_MOD_X_TILED:
2975                 return PLANE_CTL_TILED_X;
2976         case I915_FORMAT_MOD_Y_TILED:
2977                 return PLANE_CTL_TILED_Y;
2978         case I915_FORMAT_MOD_Yf_TILED:
2979                 return PLANE_CTL_TILED_YF;
2980         default:
2981                 MISSING_CASE(fb_modifier);
2982         }
2983
2984         return 0;
2985 }
2986
2987 u32 skl_plane_ctl_rotation(unsigned int rotation)
2988 {
2989         switch (rotation) {
2990         case BIT(DRM_ROTATE_0):
2991                 break;
2992         /*
2993          * DRM_ROTATE_ is counter clockwise to stay compatible with Xrandr
2994          * while i915 HW rotation is clockwise, thats why this swapping.
2995          */
2996         case BIT(DRM_ROTATE_90):
2997                 return PLANE_CTL_ROTATE_270;
2998         case BIT(DRM_ROTATE_180):
2999                 return PLANE_CTL_ROTATE_180;
3000         case BIT(DRM_ROTATE_270):
3001                 return PLANE_CTL_ROTATE_90;
3002         default:
3003                 MISSING_CASE(rotation);
3004         }
3005
3006         return 0;
3007 }
3008
3009 static void skylake_update_primary_plane(struct drm_plane *plane,
3010                                          const struct intel_crtc_state *crtc_state,
3011                                          const struct intel_plane_state *plane_state)
3012 {
3013         struct drm_device *dev = plane->dev;
3014         struct drm_i915_private *dev_priv = dev->dev_private;
3015         struct intel_crtc *intel_crtc = to_intel_crtc(crtc_state->base.crtc);
3016         struct drm_framebuffer *fb = plane_state->base.fb;
3017         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
3018         int pipe = intel_crtc->pipe;
3019         u32 plane_ctl, stride_div, stride;
3020         u32 tile_height, plane_offset, plane_size;
3021         unsigned int rotation = plane_state->base.rotation;
3022         int x_offset, y_offset;
3023         u32 surf_addr;
3024         int scaler_id = plane_state->scaler_id;
3025         int src_x = plane_state->src.x1 >> 16;
3026         int src_y = plane_state->src.y1 >> 16;
3027         int src_w = drm_rect_width(&plane_state->src) >> 16;
3028         int src_h = drm_rect_height(&plane_state->src) >> 16;
3029         int dst_x = plane_state->dst.x1;
3030         int dst_y = plane_state->dst.y1;
3031         int dst_w = drm_rect_width(&plane_state->dst);
3032         int dst_h = drm_rect_height(&plane_state->dst);
3033
3034         plane_ctl = PLANE_CTL_ENABLE |
3035                     PLANE_CTL_PIPE_GAMMA_ENABLE |
3036                     PLANE_CTL_PIPE_CSC_ENABLE;
3037
3038         plane_ctl |= skl_plane_ctl_format(fb->pixel_format);
3039         plane_ctl |= skl_plane_ctl_tiling(fb->modifier[0]);
3040         plane_ctl |= PLANE_CTL_PLANE_GAMMA_DISABLE;
3041         plane_ctl |= skl_plane_ctl_rotation(rotation);
3042
3043         stride_div = intel_fb_stride_alignment(dev_priv, fb->modifier[0],
3044                                                fb->pixel_format);
3045         surf_addr = intel_plane_obj_offset(to_intel_plane(plane), obj, 0);
3046
3047         WARN_ON(drm_rect_width(&plane_state->src) == 0);
3048
3049         if (intel_rotation_90_or_270(rotation)) {
3050                 int cpp = drm_format_plane_cpp(fb->pixel_format, 0);
3051
3052                 /* stride = Surface height in tiles */
3053                 tile_height = intel_tile_height(dev_priv, fb->modifier[0], cpp);
3054                 stride = DIV_ROUND_UP(fb->height, tile_height);
3055                 x_offset = stride * tile_height - src_y - src_h;
3056                 y_offset = src_x;
3057                 plane_size = (src_w - 1) << 16 | (src_h - 1);
3058         } else {
3059                 stride = fb->pitches[0] / stride_div;
3060                 x_offset = src_x;
3061                 y_offset = src_y;
3062                 plane_size = (src_h - 1) << 16 | (src_w - 1);
3063         }
3064         plane_offset = y_offset << 16 | x_offset;
3065
3066         intel_crtc->adjusted_x = x_offset;
3067         intel_crtc->adjusted_y = y_offset;
3068
3069         I915_WRITE(PLANE_CTL(pipe, 0), plane_ctl);
3070         I915_WRITE(PLANE_OFFSET(pipe, 0), plane_offset);
3071         I915_WRITE(PLANE_SIZE(pipe, 0), plane_size);
3072         I915_WRITE(PLANE_STRIDE(pipe, 0), stride);
3073
3074         if (scaler_id >= 0) {
3075                 uint32_t ps_ctrl = 0;
3076
3077                 WARN_ON(!dst_w || !dst_h);
3078                 ps_ctrl = PS_SCALER_EN | PS_PLANE_SEL(0) |
3079                         crtc_state->scaler_state.scalers[scaler_id].mode;
3080                 I915_WRITE(SKL_PS_CTRL(pipe, scaler_id), ps_ctrl);
3081                 I915_WRITE(SKL_PS_PWR_GATE(pipe, scaler_id), 0);
3082                 I915_WRITE(SKL_PS_WIN_POS(pipe, scaler_id), (dst_x << 16) | dst_y);
3083                 I915_WRITE(SKL_PS_WIN_SZ(pipe, scaler_id), (dst_w << 16) | dst_h);
3084                 I915_WRITE(PLANE_POS(pipe, 0), 0);
3085         } else {
3086                 I915_WRITE(PLANE_POS(pipe, 0), (dst_y << 16) | dst_x);
3087         }
3088
3089         I915_WRITE(PLANE_SURF(pipe, 0), surf_addr);
3090
3091         POSTING_READ(PLANE_SURF(pipe, 0));
3092 }
3093
3094 static void skylake_disable_primary_plane(struct drm_plane *primary,
3095                                           struct drm_crtc *crtc)
3096 {
3097         struct drm_device *dev = crtc->dev;
3098         struct drm_i915_private *dev_priv = dev->dev_private;
3099         int pipe = to_intel_crtc(crtc)->pipe;
3100
3101         I915_WRITE(PLANE_CTL(pipe, 0), 0);
3102         I915_WRITE(PLANE_SURF(pipe, 0), 0);
3103         POSTING_READ(PLANE_SURF(pipe, 0));
3104 }
3105
3106 /* Assume fb object is pinned & idle & fenced and just update base pointers */
3107 static int
3108 intel_pipe_set_base_atomic(struct drm_crtc *crtc, struct drm_framebuffer *fb,
3109                            int x, int y, enum mode_set_atomic state)
3110 {
3111         /* Support for kgdboc is disabled, this needs a major rework. */
3112         DRM_ERROR("legacy panic handler not supported any more.\n");
3113
3114         return -ENODEV;
3115 }
3116
3117 static void intel_complete_page_flips(struct drm_i915_private *dev_priv)
3118 {
3119         struct intel_crtc *crtc;
3120
3121         for_each_intel_crtc(dev_priv->dev, crtc)
3122                 intel_finish_page_flip_cs(dev_priv, crtc->pipe);
3123 }
3124
3125 static void intel_update_primary_planes(struct drm_device *dev)
3126 {
3127         struct drm_crtc *crtc;
3128
3129         for_each_crtc(dev, crtc) {
3130                 struct intel_plane *plane = to_intel_plane(crtc->primary);
3131                 struct intel_plane_state *plane_state;
3132
3133                 drm_modeset_lock_crtc(crtc, &plane->base);
3134                 plane_state = to_intel_plane_state(plane->base.state);
3135
3136                 if (plane_state->visible)
3137                         plane->update_plane(&plane->base,
3138                                             to_intel_crtc_state(crtc->state),
3139                                             plane_state);
3140
3141                 drm_modeset_unlock_crtc(crtc);
3142         }
3143 }
3144
3145 void intel_prepare_reset(struct drm_i915_private *dev_priv)
3146 {
3147         /* no reset support for gen2 */
3148         if (IS_GEN2(dev_priv))
3149                 return;
3150
3151         /* reset doesn't touch the display */
3152         if (INTEL_GEN(dev_priv) >= 5 || IS_G4X(dev_priv))
3153                 return;
3154
3155         drm_modeset_lock_all(dev_priv->dev);
3156         /*
3157          * Disabling the crtcs gracefully seems nicer. Also the
3158          * g33 docs say we should at least disable all the planes.
3159          */
3160         intel_display_suspend(dev_priv->dev);
3161 }
3162
3163 void intel_finish_reset(struct drm_i915_private *dev_priv)
3164 {
3165         /*
3166          * Flips in the rings will be nuked by the reset,
3167          * so complete all pending flips so that user space
3168          * will get its events and not get stuck.
3169          */
3170         intel_complete_page_flips(dev_priv);
3171
3172         /* no reset support for gen2 */
3173         if (IS_GEN2(dev_priv))
3174                 return;
3175
3176         /* reset doesn't touch the display */
3177         if (INTEL_GEN(dev_priv) >= 5 || IS_G4X(dev_priv)) {
3178                 /*
3179                  * Flips in the rings have been nuked by the reset,
3180                  * so update the base address of all primary
3181                  * planes to the the last fb to make sure we're
3182                  * showing the correct fb after a reset.
3183                  *
3184                  * FIXME: Atomic will make this obsolete since we won't schedule
3185                  * CS-based flips (which might get lost in gpu resets) any more.
3186                  */
3187                 intel_update_primary_planes(dev_priv->dev);
3188                 return;
3189         }
3190
3191         /*
3192          * The display has been reset as well,
3193          * so need a full re-initialization.
3194          */
3195         intel_runtime_pm_disable_interrupts(dev_priv);
3196         intel_runtime_pm_enable_interrupts(dev_priv);
3197
3198         intel_modeset_init_hw(dev_priv->dev);
3199
3200         spin_lock_irq(&dev_priv->irq_lock);
3201         if (dev_priv->display.hpd_irq_setup)
3202                 dev_priv->display.hpd_irq_setup(dev_priv);
3203         spin_unlock_irq(&dev_priv->irq_lock);
3204
3205         intel_display_resume(dev_priv->dev);
3206
3207         intel_hpd_init(dev_priv);
3208
3209         drm_modeset_unlock_all(dev_priv->dev);
3210 }
3211
3212 static bool intel_crtc_has_pending_flip(struct drm_crtc *crtc)
3213 {
3214         struct drm_device *dev = crtc->dev;
3215         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
3216         unsigned reset_counter;
3217         bool pending;
3218
3219         reset_counter = i915_reset_counter(&to_i915(dev)->gpu_error);
3220         if (intel_crtc->reset_counter != reset_counter)
3221                 return false;
3222
3223         spin_lock_irq(&dev->event_lock);
3224         pending = to_intel_crtc(crtc)->flip_work != NULL;
3225         spin_unlock_irq(&dev->event_lock);
3226
3227         return pending;
3228 }
3229
3230 static void intel_update_pipe_config(struct intel_crtc *crtc,
3231                                      struct intel_crtc_state *old_crtc_state)
3232 {
3233         struct drm_device *dev = crtc->base.dev;
3234         struct drm_i915_private *dev_priv = dev->dev_private;
3235         struct intel_crtc_state *pipe_config =
3236                 to_intel_crtc_state(crtc->base.state);
3237
3238         /* drm_atomic_helper_update_legacy_modeset_state might not be called. */
3239         crtc->base.mode = crtc->base.state->mode;
3240
3241         DRM_DEBUG_KMS("Updating pipe size %ix%i -> %ix%i\n",
3242                       old_crtc_state->pipe_src_w, old_crtc_state->pipe_src_h,
3243                       pipe_config->pipe_src_w, pipe_config->pipe_src_h);
3244
3245         /*
3246          * Update pipe size and adjust fitter if needed: the reason for this is
3247          * that in compute_mode_changes we check the native mode (not the pfit
3248          * mode) to see if we can flip rather than do a full mode set. In the
3249          * fastboot case, we'll flip, but if we don't update the pipesrc and
3250          * pfit state, we'll end up with a big fb scanned out into the wrong
3251          * sized surface.
3252          */
3253
3254         I915_WRITE(PIPESRC(crtc->pipe),
3255                    ((pipe_config->pipe_src_w - 1) << 16) |
3256                    (pipe_config->pipe_src_h - 1));
3257
3258         /* on skylake this is done by detaching scalers */
3259         if (INTEL_INFO(dev)->gen >= 9) {
3260                 skl_detach_scalers(crtc);
3261
3262                 if (pipe_config->pch_pfit.enabled)
3263                         skylake_pfit_enable(crtc);
3264         } else if (HAS_PCH_SPLIT(dev)) {
3265                 if (pipe_config->pch_pfit.enabled)
3266                         ironlake_pfit_enable(crtc);
3267                 else if (old_crtc_state->pch_pfit.enabled)
3268                         ironlake_pfit_disable(crtc, true);
3269         }
3270 }
3271
3272 static void intel_fdi_normal_train(struct drm_crtc *crtc)
3273 {
3274         struct drm_device *dev = crtc->dev;
3275         struct drm_i915_private *dev_priv = dev->dev_private;
3276         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
3277         int pipe = intel_crtc->pipe;
3278         i915_reg_t reg;
3279         u32 temp;
3280
3281         /* enable normal train */
3282         reg = FDI_TX_CTL(pipe);
3283         temp = I915_READ(reg);
3284         if (IS_IVYBRIDGE(dev)) {
3285                 temp &= ~FDI_LINK_TRAIN_NONE_IVB;
3286                 temp |= FDI_LINK_TRAIN_NONE_IVB | FDI_TX_ENHANCE_FRAME_ENABLE;
3287         } else {
3288                 temp &= ~FDI_LINK_TRAIN_NONE;
3289                 temp |= FDI_LINK_TRAIN_NONE | FDI_TX_ENHANCE_FRAME_ENABLE;
3290         }
3291         I915_WRITE(reg, temp);
3292
3293         reg = FDI_RX_CTL(pipe);
3294         temp = I915_READ(reg);
3295         if (HAS_PCH_CPT(dev)) {
3296                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
3297                 temp |= FDI_LINK_TRAIN_NORMAL_CPT;
3298         } else {
3299                 temp &= ~FDI_LINK_TRAIN_NONE;
3300                 temp |= FDI_LINK_TRAIN_NONE;
3301         }
3302         I915_WRITE(reg, temp | FDI_RX_ENHANCE_FRAME_ENABLE);
3303
3304         /* wait one idle pattern time */
3305         POSTING_READ(reg);
3306         udelay(1000);
3307
3308         /* IVB wants error correction enabled */
3309         if (IS_IVYBRIDGE(dev))
3310                 I915_WRITE(reg, I915_READ(reg) | FDI_FS_ERRC_ENABLE |
3311                            FDI_FE_ERRC_ENABLE);
3312 }
3313
3314 /* The FDI link training functions for ILK/Ibexpeak. */
3315 static void ironlake_fdi_link_train(struct drm_crtc *crtc)
3316 {
3317         struct drm_device *dev = crtc->dev;
3318         struct drm_i915_private *dev_priv = dev->dev_private;
3319         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
3320         int pipe = intel_crtc->pipe;
3321         i915_reg_t reg;
3322         u32 temp, tries;
3323
3324         /* FDI needs bits from pipe first */
3325         assert_pipe_enabled(dev_priv, pipe);
3326
3327         /* Train 1: umask FDI RX Interrupt symbol_lock and bit_lock bit
3328            for train result */
3329         reg = FDI_RX_IMR(pipe);
3330         temp = I915_READ(reg);
3331         temp &= ~FDI_RX_SYMBOL_LOCK;
3332         temp &= ~FDI_RX_BIT_LOCK;
3333         I915_WRITE(reg, temp);
3334         I915_READ(reg);
3335         udelay(150);
3336
3337         /* enable CPU FDI TX and PCH FDI RX */
3338         reg = FDI_TX_CTL(pipe);
3339         temp = I915_READ(reg);
3340         temp &= ~FDI_DP_PORT_WIDTH_MASK;
3341         temp |= FDI_DP_PORT_WIDTH(intel_crtc->config->fdi_lanes);
3342         temp &= ~FDI_LINK_TRAIN_NONE;
3343         temp |= FDI_LINK_TRAIN_PATTERN_1;
3344         I915_WRITE(reg, temp | FDI_TX_ENABLE);
3345
3346         reg = FDI_RX_CTL(pipe);
3347         temp = I915_READ(reg);
3348         temp &= ~FDI_LINK_TRAIN_NONE;
3349         temp |= FDI_LINK_TRAIN_PATTERN_1;
3350         I915_WRITE(reg, temp | FDI_RX_ENABLE);
3351
3352         POSTING_READ(reg);
3353         udelay(150);
3354
3355         /* Ironlake workaround, enable clock pointer after FDI enable*/
3356         I915_WRITE(FDI_RX_CHICKEN(pipe), FDI_RX_PHASE_SYNC_POINTER_OVR);
3357         I915_WRITE(FDI_RX_CHICKEN(pipe), FDI_RX_PHASE_SYNC_POINTER_OVR |
3358                    FDI_RX_PHASE_SYNC_POINTER_EN);
3359
3360         reg = FDI_RX_IIR(pipe);
3361         for (tries = 0; tries < 5; tries++) {
3362                 temp = I915_READ(reg);
3363                 DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
3364
3365                 if ((temp & FDI_RX_BIT_LOCK)) {
3366                         DRM_DEBUG_KMS("FDI train 1 done.\n");
3367                         I915_WRITE(reg, temp | FDI_RX_BIT_LOCK);
3368                         break;
3369                 }
3370         }
3371         if (tries == 5)
3372                 DRM_ERROR("FDI train 1 fail!\n");
3373
3374         /* Train 2 */
3375         reg = FDI_TX_CTL(pipe);
3376         temp = I915_READ(reg);
3377         temp &= ~FDI_LINK_TRAIN_NONE;
3378         temp |= FDI_LINK_TRAIN_PATTERN_2;
3379         I915_WRITE(reg, temp);
3380
3381         reg = FDI_RX_CTL(pipe);
3382         temp = I915_READ(reg);
3383         temp &= ~FDI_LINK_TRAIN_NONE;
3384         temp |= FDI_LINK_TRAIN_PATTERN_2;
3385         I915_WRITE(reg, temp);
3386
3387         POSTING_READ(reg);
3388         udelay(150);
3389
3390         reg = FDI_RX_IIR(pipe);
3391         for (tries = 0; tries < 5; tries++) {
3392                 temp = I915_READ(reg);
3393                 DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
3394
3395                 if (temp & FDI_RX_SYMBOL_LOCK) {
3396                         I915_WRITE(reg, temp | FDI_RX_SYMBOL_LOCK);
3397                         DRM_DEBUG_KMS("FDI train 2 done.\n");
3398                         break;
3399                 }
3400         }
3401         if (tries == 5)
3402                 DRM_ERROR("FDI train 2 fail!\n");
3403
3404         DRM_DEBUG_KMS("FDI train done\n");
3405
3406 }
3407
3408 static const int snb_b_fdi_train_param[] = {
3409         FDI_LINK_TRAIN_400MV_0DB_SNB_B,
3410         FDI_LINK_TRAIN_400MV_6DB_SNB_B,
3411         FDI_LINK_TRAIN_600MV_3_5DB_SNB_B,
3412         FDI_LINK_TRAIN_800MV_0DB_SNB_B,
3413 };
3414
3415 /* The FDI link training functions for SNB/Cougarpoint. */
3416 static void gen6_fdi_link_train(struct drm_crtc *crtc)
3417 {
3418         struct drm_device *dev = crtc->dev;
3419         struct drm_i915_private *dev_priv = dev->dev_private;
3420         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
3421         int pipe = intel_crtc->pipe;
3422         i915_reg_t reg;
3423         u32 temp, i, retry;
3424
3425         /* Train 1: umask FDI RX Interrupt symbol_lock and bit_lock bit
3426            for train result */
3427         reg = FDI_RX_IMR(pipe);
3428         temp = I915_READ(reg);
3429         temp &= ~FDI_RX_SYMBOL_LOCK;
3430         temp &= ~FDI_RX_BIT_LOCK;
3431         I915_WRITE(reg, temp);
3432
3433         POSTING_READ(reg);
3434         udelay(150);
3435
3436         /* enable CPU FDI TX and PCH FDI RX */
3437         reg = FDI_TX_CTL(pipe);
3438         temp = I915_READ(reg);
3439         temp &= ~FDI_DP_PORT_WIDTH_MASK;
3440         temp |= FDI_DP_PORT_WIDTH(intel_crtc->config->fdi_lanes);
3441         temp &= ~FDI_LINK_TRAIN_NONE;
3442         temp |= FDI_LINK_TRAIN_PATTERN_1;
3443         temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
3444         /* SNB-B */
3445         temp |= FDI_LINK_TRAIN_400MV_0DB_SNB_B;
3446         I915_WRITE(reg, temp | FDI_TX_ENABLE);
3447
3448         I915_WRITE(FDI_RX_MISC(pipe),
3449                    FDI_RX_TP1_TO_TP2_48 | FDI_RX_FDI_DELAY_90);
3450
3451         reg = FDI_RX_CTL(pipe);
3452         temp = I915_READ(reg);
3453         if (HAS_PCH_CPT(dev)) {
3454                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
3455                 temp |= FDI_LINK_TRAIN_PATTERN_1_CPT;
3456         } else {
3457                 temp &= ~FDI_LINK_TRAIN_NONE;
3458                 temp |= FDI_LINK_TRAIN_PATTERN_1;
3459         }
3460         I915_WRITE(reg, temp | FDI_RX_ENABLE);
3461
3462         POSTING_READ(reg);
3463         udelay(150);
3464
3465         for (i = 0; i < 4; i++) {
3466                 reg = FDI_TX_CTL(pipe);
3467                 temp = I915_READ(reg);
3468                 temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
3469                 temp |= snb_b_fdi_train_param[i];
3470                 I915_WRITE(reg, temp);
3471
3472                 POSTING_READ(reg);
3473                 udelay(500);
3474
3475                 for (retry = 0; retry < 5; retry++) {
3476                         reg = FDI_RX_IIR(pipe);
3477                         temp = I915_READ(reg);
3478                         DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
3479                         if (temp & FDI_RX_BIT_LOCK) {
3480                                 I915_WRITE(reg, temp | FDI_RX_BIT_LOCK);
3481                                 DRM_DEBUG_KMS("FDI train 1 done.\n");
3482                                 break;
3483                         }
3484                         udelay(50);
3485                 }
3486                 if (retry < 5)
3487                         break;
3488         }
3489         if (i == 4)
3490                 DRM_ERROR("FDI train 1 fail!\n");
3491
3492         /* Train 2 */
3493         reg = FDI_TX_CTL(pipe);
3494         temp = I915_READ(reg);
3495         temp &= ~FDI_LINK_TRAIN_NONE;
3496         temp |= FDI_LINK_TRAIN_PATTERN_2;
3497         if (IS_GEN6(dev)) {
3498                 temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
3499                 /* SNB-B */
3500                 temp |= FDI_LINK_TRAIN_400MV_0DB_SNB_B;
3501         }
3502         I915_WRITE(reg, temp);
3503
3504         reg = FDI_RX_CTL(pipe);
3505         temp = I915_READ(reg);
3506         if (HAS_PCH_CPT(dev)) {
3507                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
3508                 temp |= FDI_LINK_TRAIN_PATTERN_2_CPT;
3509         } else {
3510                 temp &= ~FDI_LINK_TRAIN_NONE;
3511                 temp |= FDI_LINK_TRAIN_PATTERN_2;
3512         }
3513         I915_WRITE(reg, temp);
3514
3515         POSTING_READ(reg);
3516         udelay(150);
3517
3518         for (i = 0; i < 4; i++) {
3519                 reg = FDI_TX_CTL(pipe);
3520                 temp = I915_READ(reg);
3521                 temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
3522                 temp |= snb_b_fdi_train_param[i];
3523                 I915_WRITE(reg, temp);
3524
3525                 POSTING_READ(reg);
3526                 udelay(500);
3527
3528                 for (retry = 0; retry < 5; retry++) {
3529                         reg = FDI_RX_IIR(pipe);
3530                         temp = I915_READ(reg);
3531                         DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
3532                         if (temp & FDI_RX_SYMBOL_LOCK) {
3533                                 I915_WRITE(reg, temp | FDI_RX_SYMBOL_LOCK);
3534                                 DRM_DEBUG_KMS("FDI train 2 done.\n");
3535                                 break;
3536                         }
3537                         udelay(50);
3538                 }
3539                 if (retry < 5)
3540                         break;
3541         }
3542         if (i == 4)
3543                 DRM_ERROR("FDI train 2 fail!\n");
3544
3545         DRM_DEBUG_KMS("FDI train done.\n");
3546 }
3547
3548 /* Manual link training for Ivy Bridge A0 parts */
3549 static void ivb_manual_fdi_link_train(struct drm_crtc *crtc)
3550 {
3551         struct drm_device *dev = crtc->dev;
3552         struct drm_i915_private *dev_priv = dev->dev_private;
3553         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
3554         int pipe = intel_crtc->pipe;
3555         i915_reg_t reg;
3556         u32 temp, i, j;
3557
3558         /* Train 1: umask FDI RX Interrupt symbol_lock and bit_lock bit
3559            for train result */
3560         reg = FDI_RX_IMR(pipe);
3561         temp = I915_READ(reg);
3562         temp &= ~FDI_RX_SYMBOL_LOCK;
3563         temp &= ~FDI_RX_BIT_LOCK;
3564         I915_WRITE(reg, temp);
3565
3566         POSTING_READ(reg);
3567         udelay(150);
3568
3569         DRM_DEBUG_KMS("FDI_RX_IIR before link train 0x%x\n",
3570                       I915_READ(FDI_RX_IIR(pipe)));
3571
3572         /* Try each vswing and preemphasis setting twice before moving on */
3573         for (j = 0; j < ARRAY_SIZE(snb_b_fdi_train_param) * 2; j++) {
3574                 /* disable first in case we need to retry */
3575                 reg = FDI_TX_CTL(pipe);
3576                 temp = I915_READ(reg);
3577                 temp &= ~(FDI_LINK_TRAIN_AUTO | FDI_LINK_TRAIN_NONE_IVB);
3578                 temp &= ~FDI_TX_ENABLE;
3579                 I915_WRITE(reg, temp);
3580
3581                 reg = FDI_RX_CTL(pipe);
3582                 temp = I915_READ(reg);
3583                 temp &= ~FDI_LINK_TRAIN_AUTO;
3584                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
3585                 temp &= ~FDI_RX_ENABLE;
3586                 I915_WRITE(reg, temp);
3587
3588                 /* enable CPU FDI TX and PCH FDI RX */
3589                 reg = FDI_TX_CTL(pipe);
3590                 temp = I915_READ(reg);
3591                 temp &= ~FDI_DP_PORT_WIDTH_MASK;
3592                 temp |= FDI_DP_PORT_WIDTH(intel_crtc->config->fdi_lanes);
3593                 temp |= FDI_LINK_TRAIN_PATTERN_1_IVB;
3594                 temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
3595                 temp |= snb_b_fdi_train_param[j/2];
3596                 temp |= FDI_COMPOSITE_SYNC;
3597                 I915_WRITE(reg, temp | FDI_TX_ENABLE);
3598
3599                 I915_WRITE(FDI_RX_MISC(pipe),
3600                            FDI_RX_TP1_TO_TP2_48 | FDI_RX_FDI_DELAY_90);
3601
3602                 reg = FDI_RX_CTL(pipe);
3603                 temp = I915_READ(reg);
3604                 temp |= FDI_LINK_TRAIN_PATTERN_1_CPT;
3605                 temp |= FDI_COMPOSITE_SYNC;
3606                 I915_WRITE(reg, temp | FDI_RX_ENABLE);
3607
3608                 POSTING_READ(reg);
3609                 udelay(1); /* should be 0.5us */
3610
3611                 for (i = 0; i < 4; i++) {
3612                         reg = FDI_RX_IIR(pipe);
3613                         temp = I915_READ(reg);
3614                         DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
3615
3616                         if (temp & FDI_RX_BIT_LOCK ||
3617                             (I915_READ(reg) & FDI_RX_BIT_LOCK)) {
3618                                 I915_WRITE(reg, temp | FDI_RX_BIT_LOCK);
3619                                 DRM_DEBUG_KMS("FDI train 1 done, level %i.\n",
3620                                               i);
3621                                 break;
3622                         }
3623                         udelay(1); /* should be 0.5us */
3624                 }
3625                 if (i == 4) {
3626                         DRM_DEBUG_KMS("FDI train 1 fail on vswing %d\n", j / 2);
3627                         continue;
3628                 }
3629
3630                 /* Train 2 */
3631                 reg = FDI_TX_CTL(pipe);
3632                 temp = I915_READ(reg);
3633                 temp &= ~FDI_LINK_TRAIN_NONE_IVB;
3634                 temp |= FDI_LINK_TRAIN_PATTERN_2_IVB;
3635                 I915_WRITE(reg, temp);
3636
3637                 reg = FDI_RX_CTL(pipe);
3638                 temp = I915_READ(reg);
3639                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
3640                 temp |= FDI_LINK_TRAIN_PATTERN_2_CPT;
3641                 I915_WRITE(reg, temp);
3642
3643                 POSTING_READ(reg);
3644                 udelay(2); /* should be 1.5us */
3645
3646                 for (i = 0; i < 4; i++) {
3647                         reg = FDI_RX_IIR(pipe);
3648                         temp = I915_READ(reg);
3649                         DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
3650
3651                         if (temp & FDI_RX_SYMBOL_LOCK ||
3652                             (I915_READ(reg) & FDI_RX_SYMBOL_LOCK)) {
3653                                 I915_WRITE(reg, temp | FDI_RX_SYMBOL_LOCK);
3654                                 DRM_DEBUG_KMS("FDI train 2 done, level %i.\n",
3655                                               i);
3656                                 goto train_done;
3657                         }
3658                         udelay(2); /* should be 1.5us */
3659                 }
3660                 if (i == 4)
3661                         DRM_DEBUG_KMS("FDI train 2 fail on vswing %d\n", j / 2);
3662         }
3663
3664 train_done:
3665         DRM_DEBUG_KMS("FDI train done.\n");
3666 }
3667
3668 static void ironlake_fdi_pll_enable(struct intel_crtc *intel_crtc)
3669 {
3670         struct drm_device *dev = intel_crtc->base.dev;
3671         struct drm_i915_private *dev_priv = dev->dev_private;
3672         int pipe = intel_crtc->pipe;
3673         i915_reg_t reg;
3674         u32 temp;
3675
3676         /* enable PCH FDI RX PLL, wait warmup plus DMI latency */
3677         reg = FDI_RX_CTL(pipe);
3678         temp = I915_READ(reg);
3679         temp &= ~(FDI_DP_PORT_WIDTH_MASK | (0x7 << 16));
3680         temp |= FDI_DP_PORT_WIDTH(intel_crtc->config->fdi_lanes);
3681         temp |= (I915_READ(PIPECONF(pipe)) & PIPECONF_BPC_MASK) << 11;
3682         I915_WRITE(reg, temp | FDI_RX_PLL_ENABLE);
3683
3684         POSTING_READ(reg);
3685         udelay(200);
3686
3687         /* Switch from Rawclk to PCDclk */
3688         temp = I915_READ(reg);
3689         I915_WRITE(reg, temp | FDI_PCDCLK);
3690
3691         POSTING_READ(reg);
3692         udelay(200);
3693
3694         /* Enable CPU FDI TX PLL, always on for Ironlake */
3695         reg = FDI_TX_CTL(pipe);
3696         temp = I915_READ(reg);
3697         if ((temp & FDI_TX_PLL_ENABLE) == 0) {
3698                 I915_WRITE(reg, temp | FDI_TX_PLL_ENABLE);
3699
3700                 POSTING_READ(reg);
3701                 udelay(100);
3702         }
3703 }
3704
3705 static void ironlake_fdi_pll_disable(struct intel_crtc *intel_crtc)
3706 {
3707         struct drm_device *dev = intel_crtc->base.dev;
3708         struct drm_i915_private *dev_priv = dev->dev_private;
3709         int pipe = intel_crtc->pipe;
3710         i915_reg_t reg;
3711         u32 temp;
3712
3713         /* Switch from PCDclk to Rawclk */
3714         reg = FDI_RX_CTL(pipe);
3715         temp = I915_READ(reg);
3716         I915_WRITE(reg, temp & ~FDI_PCDCLK);
3717
3718         /* Disable CPU FDI TX PLL */
3719         reg = FDI_TX_CTL(pipe);
3720         temp = I915_READ(reg);
3721         I915_WRITE(reg, temp & ~FDI_TX_PLL_ENABLE);
3722
3723         POSTING_READ(reg);
3724         udelay(100);
3725
3726         reg = FDI_RX_CTL(pipe);
3727         temp = I915_READ(reg);
3728         I915_WRITE(reg, temp & ~FDI_RX_PLL_ENABLE);
3729
3730         /* Wait for the clocks to turn off. */
3731         POSTING_READ(reg);
3732         udelay(100);
3733 }
3734
3735 static void ironlake_fdi_disable(struct drm_crtc *crtc)
3736 {
3737         struct drm_device *dev = crtc->dev;
3738         struct drm_i915_private *dev_priv = dev->dev_private;
3739         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
3740         int pipe = intel_crtc->pipe;
3741         i915_reg_t reg;
3742         u32 temp;
3743
3744         /* disable CPU FDI tx and PCH FDI rx */
3745         reg = FDI_TX_CTL(pipe);
3746         temp = I915_READ(reg);
3747         I915_WRITE(reg, temp & ~FDI_TX_ENABLE);
3748         POSTING_READ(reg);
3749
3750         reg = FDI_RX_CTL(pipe);
3751         temp = I915_READ(reg);
3752         temp &= ~(0x7 << 16);
3753         temp |= (I915_READ(PIPECONF(pipe)) & PIPECONF_BPC_MASK) << 11;
3754         I915_WRITE(reg, temp & ~FDI_RX_ENABLE);
3755
3756         POSTING_READ(reg);
3757         udelay(100);
3758
3759         /* Ironlake workaround, disable clock pointer after downing FDI */
3760         if (HAS_PCH_IBX(dev))
3761                 I915_WRITE(FDI_RX_CHICKEN(pipe), FDI_RX_PHASE_SYNC_POINTER_OVR);
3762
3763         /* still set train pattern 1 */
3764         reg = FDI_TX_CTL(pipe);
3765         temp = I915_READ(reg);
3766         temp &= ~FDI_LINK_TRAIN_NONE;
3767         temp |= FDI_LINK_TRAIN_PATTERN_1;
3768         I915_WRITE(reg, temp);
3769
3770         reg = FDI_RX_CTL(pipe);
3771         temp = I915_READ(reg);
3772         if (HAS_PCH_CPT(dev)) {
3773                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
3774                 temp |= FDI_LINK_TRAIN_PATTERN_1_CPT;
3775         } else {
3776                 temp &= ~FDI_LINK_TRAIN_NONE;
3777                 temp |= FDI_LINK_TRAIN_PATTERN_1;
3778         }
3779         /* BPC in FDI rx is consistent with that in PIPECONF */
3780         temp &= ~(0x07 << 16);
3781         temp |= (I915_READ(PIPECONF(pipe)) & PIPECONF_BPC_MASK) << 11;
3782         I915_WRITE(reg, temp);
3783
3784         POSTING_READ(reg);
3785         udelay(100);
3786 }
3787
3788 bool intel_has_pending_fb_unpin(struct drm_device *dev)
3789 {
3790         struct intel_crtc *crtc;
3791
3792         /* Note that we don't need to be called with mode_config.lock here
3793          * as our list of CRTC objects is static for the lifetime of the
3794          * device and so cannot disappear as we iterate. Similarly, we can
3795          * happily treat the predicates as racy, atomic checks as userspace
3796          * cannot claim and pin a new fb without at least acquring the
3797          * struct_mutex and so serialising with us.
3798          */
3799         for_each_intel_crtc(dev, crtc) {
3800                 if (atomic_read(&crtc->unpin_work_count) == 0)
3801                         continue;
3802
3803                 if (crtc->flip_work)
3804                         intel_wait_for_vblank(dev, crtc->pipe);
3805
3806                 return true;
3807         }
3808
3809         return false;
3810 }
3811
3812 static void page_flip_completed(struct intel_crtc *intel_crtc)
3813 {
3814         struct drm_i915_private *dev_priv = to_i915(intel_crtc->base.dev);
3815         struct intel_flip_work *work = intel_crtc->flip_work;
3816
3817         intel_crtc->flip_work = NULL;
3818
3819         if (work->event)
3820                 drm_crtc_send_vblank_event(&intel_crtc->base, work->event);
3821
3822         drm_crtc_vblank_put(&intel_crtc->base);
3823
3824         wake_up_all(&dev_priv->pending_flip_queue);
3825         queue_work(dev_priv->wq, &work->unpin_work);
3826
3827         trace_i915_flip_complete(intel_crtc->plane,
3828                                  work->pending_flip_obj);
3829 }
3830
3831 static int intel_crtc_wait_for_pending_flips(struct drm_crtc *crtc)
3832 {
3833         struct drm_device *dev = crtc->dev;
3834         struct drm_i915_private *dev_priv = dev->dev_private;
3835         long ret;
3836
3837         WARN_ON(waitqueue_active(&dev_priv->pending_flip_queue));
3838
3839         ret = wait_event_interruptible_timeout(
3840                                         dev_priv->pending_flip_queue,
3841                                         !intel_crtc_has_pending_flip(crtc),
3842                                         60*HZ);
3843
3844         if (ret < 0)
3845                 return ret;
3846
3847         if (ret == 0) {
3848                 struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
3849                 struct intel_flip_work *work;
3850
3851                 spin_lock_irq(&dev->event_lock);
3852                 work = intel_crtc->flip_work;
3853                 if (work && !is_mmio_work(work)) {
3854                         WARN_ONCE(1, "Removing stuck page flip\n");
3855                         page_flip_completed(intel_crtc);
3856                 }
3857                 spin_unlock_irq(&dev->event_lock);
3858         }
3859
3860         return 0;
3861 }
3862
3863 static void lpt_disable_iclkip(struct drm_i915_private *dev_priv)
3864 {
3865         u32 temp;
3866
3867         I915_WRITE(PIXCLK_GATE, PIXCLK_GATE_GATE);
3868
3869         mutex_lock(&dev_priv->sb_lock);
3870
3871         temp = intel_sbi_read(dev_priv, SBI_SSCCTL6, SBI_ICLK);
3872         temp |= SBI_SSCCTL_DISABLE;
3873         intel_sbi_write(dev_priv, SBI_SSCCTL6, temp, SBI_ICLK);
3874
3875         mutex_unlock(&dev_priv->sb_lock);
3876 }
3877
3878 /* Program iCLKIP clock to the desired frequency */
3879 static void lpt_program_iclkip(struct drm_crtc *crtc)
3880 {
3881         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
3882         int clock = to_intel_crtc(crtc)->config->base.adjusted_mode.crtc_clock;
3883         u32 divsel, phaseinc, auxdiv, phasedir = 0;
3884         u32 temp;
3885
3886         lpt_disable_iclkip(dev_priv);
3887
3888         /* The iCLK virtual clock root frequency is in MHz,
3889          * but the adjusted_mode->crtc_clock in in KHz. To get the
3890          * divisors, it is necessary to divide one by another, so we
3891          * convert the virtual clock precision to KHz here for higher
3892          * precision.
3893          */
3894         for (auxdiv = 0; auxdiv < 2; auxdiv++) {
3895                 u32 iclk_virtual_root_freq = 172800 * 1000;
3896                 u32 iclk_pi_range = 64;
3897                 u32 desired_divisor;
3898
3899                 desired_divisor = DIV_ROUND_CLOSEST(iclk_virtual_root_freq,
3900                                                     clock << auxdiv);
3901                 divsel = (desired_divisor / iclk_pi_range) - 2;
3902                 phaseinc = desired_divisor % iclk_pi_range;
3903
3904                 /*
3905                  * Near 20MHz is a corner case which is
3906                  * out of range for the 7-bit divisor
3907                  */
3908                 if (divsel <= 0x7f)
3909                         break;
3910         }
3911
3912         /* This should not happen with any sane values */
3913         WARN_ON(SBI_SSCDIVINTPHASE_DIVSEL(divsel) &
3914                 ~SBI_SSCDIVINTPHASE_DIVSEL_MASK);
3915         WARN_ON(SBI_SSCDIVINTPHASE_DIR(phasedir) &
3916                 ~SBI_SSCDIVINTPHASE_INCVAL_MASK);
3917
3918         DRM_DEBUG_KMS("iCLKIP clock: found settings for %dKHz refresh rate: auxdiv=%x, divsel=%x, phasedir=%x, phaseinc=%x\n",
3919                         clock,
3920                         auxdiv,
3921                         divsel,
3922                         phasedir,
3923                         phaseinc);
3924
3925         mutex_lock(&dev_priv->sb_lock);
3926
3927         /* Program SSCDIVINTPHASE6 */
3928         temp = intel_sbi_read(dev_priv, SBI_SSCDIVINTPHASE6, SBI_ICLK);
3929         temp &= ~SBI_SSCDIVINTPHASE_DIVSEL_MASK;
3930         temp |= SBI_SSCDIVINTPHASE_DIVSEL(divsel);
3931         temp &= ~SBI_SSCDIVINTPHASE_INCVAL_MASK;
3932         temp |= SBI_SSCDIVINTPHASE_INCVAL(phaseinc);
3933         temp |= SBI_SSCDIVINTPHASE_DIR(phasedir);
3934         temp |= SBI_SSCDIVINTPHASE_PROPAGATE;
3935         intel_sbi_write(dev_priv, SBI_SSCDIVINTPHASE6, temp, SBI_ICLK);
3936
3937         /* Program SSCAUXDIV */
3938         temp = intel_sbi_read(dev_priv, SBI_SSCAUXDIV6, SBI_ICLK);
3939         temp &= ~SBI_SSCAUXDIV_FINALDIV2SEL(1);
3940         temp |= SBI_SSCAUXDIV_FINALDIV2SEL(auxdiv);
3941         intel_sbi_write(dev_priv, SBI_SSCAUXDIV6, temp, SBI_ICLK);
3942
3943         /* Enable modulator and associated divider */
3944         temp = intel_sbi_read(dev_priv, SBI_SSCCTL6, SBI_ICLK);
3945         temp &= ~SBI_SSCCTL_DISABLE;
3946         intel_sbi_write(dev_priv, SBI_SSCCTL6, temp, SBI_ICLK);
3947
3948         mutex_unlock(&dev_priv->sb_lock);
3949
3950         /* Wait for initialization time */
3951         udelay(24);
3952
3953         I915_WRITE(PIXCLK_GATE, PIXCLK_GATE_UNGATE);
3954 }
3955
3956 int lpt_get_iclkip(struct drm_i915_private *dev_priv)
3957 {
3958         u32 divsel, phaseinc, auxdiv;
3959         u32 iclk_virtual_root_freq = 172800 * 1000;
3960         u32 iclk_pi_range = 64;
3961         u32 desired_divisor;
3962         u32 temp;
3963
3964         if ((I915_READ(PIXCLK_GATE) & PIXCLK_GATE_UNGATE) == 0)
3965                 return 0;
3966
3967         mutex_lock(&dev_priv->sb_lock);
3968
3969         temp = intel_sbi_read(dev_priv, SBI_SSCCTL6, SBI_ICLK);
3970         if (temp & SBI_SSCCTL_DISABLE) {
3971                 mutex_unlock(&dev_priv->sb_lock);
3972                 return 0;
3973         }
3974
3975         temp = intel_sbi_read(dev_priv, SBI_SSCDIVINTPHASE6, SBI_ICLK);
3976         divsel = (temp & SBI_SSCDIVINTPHASE_DIVSEL_MASK) >>
3977                 SBI_SSCDIVINTPHASE_DIVSEL_SHIFT;
3978         phaseinc = (temp & SBI_SSCDIVINTPHASE_INCVAL_MASK) >>
3979                 SBI_SSCDIVINTPHASE_INCVAL_SHIFT;
3980
3981         temp = intel_sbi_read(dev_priv, SBI_SSCAUXDIV6, SBI_ICLK);
3982         auxdiv = (temp & SBI_SSCAUXDIV_FINALDIV2SEL_MASK) >>
3983                 SBI_SSCAUXDIV_FINALDIV2SEL_SHIFT;
3984
3985         mutex_unlock(&dev_priv->sb_lock);
3986
3987         desired_divisor = (divsel + 2) * iclk_pi_range + phaseinc;
3988
3989         return DIV_ROUND_CLOSEST(iclk_virtual_root_freq,
3990                                  desired_divisor << auxdiv);
3991 }
3992
3993 static void ironlake_pch_transcoder_set_timings(struct intel_crtc *crtc,
3994                                                 enum pipe pch_transcoder)
3995 {
3996         struct drm_device *dev = crtc->base.dev;
3997         struct drm_i915_private *dev_priv = dev->dev_private;
3998         enum transcoder cpu_transcoder = crtc->config->cpu_transcoder;
3999
4000         I915_WRITE(PCH_TRANS_HTOTAL(pch_transcoder),
4001                    I915_READ(HTOTAL(cpu_transcoder)));
4002         I915_WRITE(PCH_TRANS_HBLANK(pch_transcoder),
4003                    I915_READ(HBLANK(cpu_transcoder)));
4004         I915_WRITE(PCH_TRANS_HSYNC(pch_transcoder),
4005                    I915_READ(HSYNC(cpu_transcoder)));
4006
4007         I915_WRITE(PCH_TRANS_VTOTAL(pch_transcoder),
4008                    I915_READ(VTOTAL(cpu_transcoder)));
4009         I915_WRITE(PCH_TRANS_VBLANK(pch_transcoder),
4010                    I915_READ(VBLANK(cpu_transcoder)));
4011         I915_WRITE(PCH_TRANS_VSYNC(pch_transcoder),
4012                    I915_READ(VSYNC(cpu_transcoder)));
4013         I915_WRITE(PCH_TRANS_VSYNCSHIFT(pch_transcoder),
4014                    I915_READ(VSYNCSHIFT(cpu_transcoder)));
4015 }
4016
4017 static void cpt_set_fdi_bc_bifurcation(struct drm_device *dev, bool enable)
4018 {
4019         struct drm_i915_private *dev_priv = dev->dev_private;
4020         uint32_t temp;
4021
4022         temp = I915_READ(SOUTH_CHICKEN1);
4023         if (!!(temp & FDI_BC_BIFURCATION_SELECT) == enable)
4024                 return;
4025
4026         WARN_ON(I915_READ(FDI_RX_CTL(PIPE_B)) & FDI_RX_ENABLE);
4027         WARN_ON(I915_READ(FDI_RX_CTL(PIPE_C)) & FDI_RX_ENABLE);
4028
4029         temp &= ~FDI_BC_BIFURCATION_SELECT;
4030         if (enable)
4031                 temp |= FDI_BC_BIFURCATION_SELECT;
4032
4033         DRM_DEBUG_KMS("%sabling fdi C rx\n", enable ? "en" : "dis");
4034         I915_WRITE(SOUTH_CHICKEN1, temp);
4035         POSTING_READ(SOUTH_CHICKEN1);
4036 }
4037
4038 static void ivybridge_update_fdi_bc_bifurcation(struct intel_crtc *intel_crtc)
4039 {
4040         struct drm_device *dev = intel_crtc->base.dev;
4041
4042         switch (intel_crtc->pipe) {
4043         case PIPE_A:
4044                 break;
4045         case PIPE_B:
4046                 if (intel_crtc->config->fdi_lanes > 2)
4047                         cpt_set_fdi_bc_bifurcation(dev, false);
4048                 else
4049                         cpt_set_fdi_bc_bifurcation(dev, true);
4050
4051                 break;
4052         case PIPE_C:
4053                 cpt_set_fdi_bc_bifurcation(dev, true);
4054
4055                 break;
4056         default:
4057                 BUG();
4058         }
4059 }
4060
4061 /* Return which DP Port should be selected for Transcoder DP control */
4062 static enum port
4063 intel_trans_dp_port_sel(struct drm_crtc *crtc)
4064 {
4065         struct drm_device *dev = crtc->dev;
4066         struct intel_encoder *encoder;
4067
4068         for_each_encoder_on_crtc(dev, crtc, encoder) {
4069                 if (encoder->type == INTEL_OUTPUT_DISPLAYPORT ||
4070                     encoder->type == INTEL_OUTPUT_EDP)
4071                         return enc_to_dig_port(&encoder->base)->port;
4072         }
4073
4074         return -1;
4075 }
4076
4077 /*
4078  * Enable PCH resources required for PCH ports:
4079  *   - PCH PLLs
4080  *   - FDI training & RX/TX
4081  *   - update transcoder timings
4082  *   - DP transcoding bits
4083  *   - transcoder
4084  */
4085 static void ironlake_pch_enable(struct drm_crtc *crtc)
4086 {
4087         struct drm_device *dev = crtc->dev;
4088         struct drm_i915_private *dev_priv = dev->dev_private;
4089         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4090         int pipe = intel_crtc->pipe;
4091         u32 temp;
4092
4093         assert_pch_transcoder_disabled(dev_priv, pipe);
4094
4095         if (IS_IVYBRIDGE(dev))
4096                 ivybridge_update_fdi_bc_bifurcation(intel_crtc);
4097
4098         /* Write the TU size bits before fdi link training, so that error
4099          * detection works. */
4100         I915_WRITE(FDI_RX_TUSIZE1(pipe),
4101                    I915_READ(PIPE_DATA_M1(pipe)) & TU_SIZE_MASK);
4102
4103         /* For PCH output, training FDI link */
4104         dev_priv->display.fdi_link_train(crtc);
4105
4106         /* We need to program the right clock selection before writing the pixel
4107          * mutliplier into the DPLL. */
4108         if (HAS_PCH_CPT(dev)) {
4109                 u32 sel;
4110
4111                 temp = I915_READ(PCH_DPLL_SEL);
4112                 temp |= TRANS_DPLL_ENABLE(pipe);
4113                 sel = TRANS_DPLLB_SEL(pipe);
4114                 if (intel_crtc->config->shared_dpll ==
4115                     intel_get_shared_dpll_by_id(dev_priv, DPLL_ID_PCH_PLL_B))
4116                         temp |= sel;
4117                 else
4118                         temp &= ~sel;
4119                 I915_WRITE(PCH_DPLL_SEL, temp);
4120         }
4121
4122         /* XXX: pch pll's can be enabled any time before we enable the PCH
4123          * transcoder, and we actually should do this to not upset any PCH
4124          * transcoder that already use the clock when we share it.
4125          *
4126          * Note that enable_shared_dpll tries to do the right thing, but
4127          * get_shared_dpll unconditionally resets the pll - we need that to have
4128          * the right LVDS enable sequence. */
4129         intel_enable_shared_dpll(intel_crtc);
4130
4131         /* set transcoder timing, panel must allow it */
4132         assert_panel_unlocked(dev_priv, pipe);
4133         ironlake_pch_transcoder_set_timings(intel_crtc, pipe);
4134
4135         intel_fdi_normal_train(crtc);
4136
4137         /* For PCH DP, enable TRANS_DP_CTL */
4138         if (HAS_PCH_CPT(dev) && intel_crtc->config->has_dp_encoder) {
4139                 const struct drm_display_mode *adjusted_mode =
4140                         &intel_crtc->config->base.adjusted_mode;
4141                 u32 bpc = (I915_READ(PIPECONF(pipe)) & PIPECONF_BPC_MASK) >> 5;
4142                 i915_reg_t reg = TRANS_DP_CTL(pipe);
4143                 temp = I915_READ(reg);
4144                 temp &= ~(TRANS_DP_PORT_SEL_MASK |
4145                           TRANS_DP_SYNC_MASK |
4146                           TRANS_DP_BPC_MASK);
4147                 temp |= TRANS_DP_OUTPUT_ENABLE;
4148                 temp |= bpc << 9; /* same format but at 11:9 */
4149
4150                 if (adjusted_mode->flags & DRM_MODE_FLAG_PHSYNC)
4151                         temp |= TRANS_DP_HSYNC_ACTIVE_HIGH;
4152                 if (adjusted_mode->flags & DRM_MODE_FLAG_PVSYNC)
4153                         temp |= TRANS_DP_VSYNC_ACTIVE_HIGH;
4154
4155                 switch (intel_trans_dp_port_sel(crtc)) {
4156                 case PORT_B:
4157                         temp |= TRANS_DP_PORT_SEL_B;
4158                         break;
4159                 case PORT_C:
4160                         temp |= TRANS_DP_PORT_SEL_C;
4161                         break;
4162                 case PORT_D:
4163                         temp |= TRANS_DP_PORT_SEL_D;
4164                         break;
4165                 default:
4166                         BUG();
4167                 }
4168
4169                 I915_WRITE(reg, temp);
4170         }
4171
4172         ironlake_enable_pch_transcoder(dev_priv, pipe);
4173 }
4174
4175 static void lpt_pch_enable(struct drm_crtc *crtc)
4176 {
4177         struct drm_device *dev = crtc->dev;
4178         struct drm_i915_private *dev_priv = dev->dev_private;
4179         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4180         enum transcoder cpu_transcoder = intel_crtc->config->cpu_transcoder;
4181
4182         assert_pch_transcoder_disabled(dev_priv, TRANSCODER_A);
4183
4184         lpt_program_iclkip(crtc);
4185
4186         /* Set transcoder timing. */
4187         ironlake_pch_transcoder_set_timings(intel_crtc, PIPE_A);
4188
4189         lpt_enable_pch_transcoder(dev_priv, cpu_transcoder);
4190 }
4191
4192 static void cpt_verify_modeset(struct drm_device *dev, int pipe)
4193 {
4194         struct drm_i915_private *dev_priv = dev->dev_private;
4195         i915_reg_t dslreg = PIPEDSL(pipe);
4196         u32 temp;
4197
4198         temp = I915_READ(dslreg);
4199         udelay(500);
4200         if (wait_for(I915_READ(dslreg) != temp, 5)) {
4201                 if (wait_for(I915_READ(dslreg) != temp, 5))
4202                         DRM_ERROR("mode set failed: pipe %c stuck\n", pipe_name(pipe));
4203         }
4204 }
4205
4206 static int
4207 skl_update_scaler(struct intel_crtc_state *crtc_state, bool force_detach,
4208                   unsigned scaler_user, int *scaler_id, unsigned int rotation,
4209                   int src_w, int src_h, int dst_w, int dst_h)
4210 {
4211         struct intel_crtc_scaler_state *scaler_state =
4212                 &crtc_state->scaler_state;
4213         struct intel_crtc *intel_crtc =
4214                 to_intel_crtc(crtc_state->base.crtc);
4215         int need_scaling;
4216
4217         need_scaling = intel_rotation_90_or_270(rotation) ?
4218                 (src_h != dst_w || src_w != dst_h):
4219                 (src_w != dst_w || src_h != dst_h);
4220
4221         /*
4222          * if plane is being disabled or scaler is no more required or force detach
4223          *  - free scaler binded to this plane/crtc
4224          *  - in order to do this, update crtc->scaler_usage
4225          *
4226          * Here scaler state in crtc_state is set free so that
4227          * scaler can be assigned to other user. Actual register
4228          * update to free the scaler is done in plane/panel-fit programming.
4229          * For this purpose crtc/plane_state->scaler_id isn't reset here.
4230          */
4231         if (force_detach || !need_scaling) {
4232                 if (*scaler_id >= 0) {
4233                         scaler_state->scaler_users &= ~(1 << scaler_user);
4234                         scaler_state->scalers[*scaler_id].in_use = 0;
4235
4236                         DRM_DEBUG_KMS("scaler_user index %u.%u: "
4237                                 "Staged freeing scaler id %d scaler_users = 0x%x\n",
4238                                 intel_crtc->pipe, scaler_user, *scaler_id,
4239                                 scaler_state->scaler_users);
4240                         *scaler_id = -1;
4241                 }
4242                 return 0;
4243         }
4244
4245         /* range checks */
4246         if (src_w < SKL_MIN_SRC_W || src_h < SKL_MIN_SRC_H ||
4247                 dst_w < SKL_MIN_DST_W || dst_h < SKL_MIN_DST_H ||
4248
4249                 src_w > SKL_MAX_SRC_W || src_h > SKL_MAX_SRC_H ||
4250                 dst_w > SKL_MAX_DST_W || dst_h > SKL_MAX_DST_H) {
4251                 DRM_DEBUG_KMS("scaler_user index %u.%u: src %ux%u dst %ux%u "
4252                         "size is out of scaler range\n",
4253                         intel_crtc->pipe, scaler_user, src_w, src_h, dst_w, dst_h);
4254                 return -EINVAL;
4255         }
4256
4257         /* mark this plane as a scaler user in crtc_state */
4258         scaler_state->scaler_users |= (1 << scaler_user);
4259         DRM_DEBUG_KMS("scaler_user index %u.%u: "
4260                 "staged scaling request for %ux%u->%ux%u scaler_users = 0x%x\n",
4261                 intel_crtc->pipe, scaler_user, src_w, src_h, dst_w, dst_h,
4262                 scaler_state->scaler_users);
4263
4264         return 0;
4265 }
4266
4267 /**
4268  * skl_update_scaler_crtc - Stages update to scaler state for a given crtc.
4269  *
4270  * @state: crtc's scaler state
4271  *
4272  * Return
4273  *     0 - scaler_usage updated successfully
4274  *    error - requested scaling cannot be supported or other error condition
4275  */
4276 int skl_update_scaler_crtc(struct intel_crtc_state *state)
4277 {
4278         struct intel_crtc *intel_crtc = to_intel_crtc(state->base.crtc);
4279         const struct drm_display_mode *adjusted_mode = &state->base.adjusted_mode;
4280
4281         DRM_DEBUG_KMS("Updating scaler for [CRTC:%d:%s] scaler_user index %u.%u\n",
4282                       intel_crtc->base.base.id, intel_crtc->base.name,
4283                       intel_crtc->pipe, SKL_CRTC_INDEX);
4284
4285         return skl_update_scaler(state, !state->base.active, SKL_CRTC_INDEX,
4286                 &state->scaler_state.scaler_id, BIT(DRM_ROTATE_0),
4287                 state->pipe_src_w, state->pipe_src_h,
4288                 adjusted_mode->crtc_hdisplay, adjusted_mode->crtc_vdisplay);
4289 }
4290
4291 /**
4292  * skl_update_scaler_plane - Stages update to scaler state for a given plane.
4293  *
4294  * @state: crtc's scaler state
4295  * @plane_state: atomic plane state to update
4296  *
4297  * Return
4298  *     0 - scaler_usage updated successfully
4299  *    error - requested scaling cannot be supported or other error condition
4300  */
4301 static int skl_update_scaler_plane(struct intel_crtc_state *crtc_state,
4302                                    struct intel_plane_state *plane_state)
4303 {
4304
4305         struct intel_crtc *intel_crtc = to_intel_crtc(crtc_state->base.crtc);
4306         struct intel_plane *intel_plane =
4307                 to_intel_plane(plane_state->base.plane);
4308         struct drm_framebuffer *fb = plane_state->base.fb;
4309         int ret;
4310
4311         bool force_detach = !fb || !plane_state->visible;
4312
4313         DRM_DEBUG_KMS("Updating scaler for [PLANE:%d:%s] scaler_user index %u.%u\n",
4314                       intel_plane->base.base.id, intel_plane->base.name,
4315                       intel_crtc->pipe, drm_plane_index(&intel_plane->base));
4316
4317         ret = skl_update_scaler(crtc_state, force_detach,
4318                                 drm_plane_index(&intel_plane->base),
4319                                 &plane_state->scaler_id,
4320                                 plane_state->base.rotation,
4321                                 drm_rect_width(&plane_state->src) >> 16,
4322                                 drm_rect_height(&plane_state->src) >> 16,
4323                                 drm_rect_width(&plane_state->dst),
4324                                 drm_rect_height(&plane_state->dst));
4325
4326         if (ret || plane_state->scaler_id < 0)
4327                 return ret;
4328
4329         /* check colorkey */
4330         if (plane_state->ckey.flags != I915_SET_COLORKEY_NONE) {
4331                 DRM_DEBUG_KMS("[PLANE:%d:%s] scaling with color key not allowed",
4332                               intel_plane->base.base.id,
4333                               intel_plane->base.name);
4334                 return -EINVAL;
4335         }
4336
4337         /* Check src format */
4338         switch (fb->pixel_format) {
4339         case DRM_FORMAT_RGB565:
4340         case DRM_FORMAT_XBGR8888:
4341         case DRM_FORMAT_XRGB8888:
4342         case DRM_FORMAT_ABGR8888:
4343         case DRM_FORMAT_ARGB8888:
4344         case DRM_FORMAT_XRGB2101010:
4345         case DRM_FORMAT_XBGR2101010:
4346         case DRM_FORMAT_YUYV:
4347         case DRM_FORMAT_YVYU:
4348         case DRM_FORMAT_UYVY:
4349         case DRM_FORMAT_VYUY:
4350                 break;
4351         default:
4352                 DRM_DEBUG_KMS("[PLANE:%d:%s] FB:%d unsupported scaling format 0x%x\n",
4353                               intel_plane->base.base.id, intel_plane->base.name,
4354                               fb->base.id, fb->pixel_format);
4355                 return -EINVAL;
4356         }
4357
4358         return 0;
4359 }
4360
4361 static void skylake_scaler_disable(struct intel_crtc *crtc)
4362 {
4363         int i;
4364
4365         for (i = 0; i < crtc->num_scalers; i++)
4366                 skl_detach_scaler(crtc, i);
4367 }
4368
4369 static void skylake_pfit_enable(struct intel_crtc *crtc)
4370 {
4371         struct drm_device *dev = crtc->base.dev;
4372         struct drm_i915_private *dev_priv = dev->dev_private;
4373         int pipe = crtc->pipe;
4374         struct intel_crtc_scaler_state *scaler_state =
4375                 &crtc->config->scaler_state;
4376
4377         DRM_DEBUG_KMS("for crtc_state = %p\n", crtc->config);
4378
4379         if (crtc->config->pch_pfit.enabled) {
4380                 int id;
4381
4382                 if (WARN_ON(crtc->config->scaler_state.scaler_id < 0)) {
4383                         DRM_ERROR("Requesting pfit without getting a scaler first\n");
4384                         return;
4385                 }
4386
4387                 id = scaler_state->scaler_id;
4388                 I915_WRITE(SKL_PS_CTRL(pipe, id), PS_SCALER_EN |
4389                         PS_FILTER_MEDIUM | scaler_state->scalers[id].mode);
4390                 I915_WRITE(SKL_PS_WIN_POS(pipe, id), crtc->config->pch_pfit.pos);
4391                 I915_WRITE(SKL_PS_WIN_SZ(pipe, id), crtc->config->pch_pfit.size);
4392
4393                 DRM_DEBUG_KMS("for crtc_state = %p scaler_id = %d\n", crtc->config, id);
4394         }
4395 }
4396
4397 static void ironlake_pfit_enable(struct intel_crtc *crtc)
4398 {
4399         struct drm_device *dev = crtc->base.dev;
4400         struct drm_i915_private *dev_priv = dev->dev_private;
4401         int pipe = crtc->pipe;
4402
4403         if (crtc->config->pch_pfit.enabled) {
4404                 /* Force use of hard-coded filter coefficients
4405                  * as some pre-programmed values are broken,
4406                  * e.g. x201.
4407                  */
4408                 if (IS_IVYBRIDGE(dev) || IS_HASWELL(dev))
4409                         I915_WRITE(PF_CTL(pipe), PF_ENABLE | PF_FILTER_MED_3x3 |
4410                                                  PF_PIPE_SEL_IVB(pipe));
4411                 else
4412                         I915_WRITE(PF_CTL(pipe), PF_ENABLE | PF_FILTER_MED_3x3);
4413                 I915_WRITE(PF_WIN_POS(pipe), crtc->config->pch_pfit.pos);
4414                 I915_WRITE(PF_WIN_SZ(pipe), crtc->config->pch_pfit.size);
4415         }
4416 }
4417
4418 void hsw_enable_ips(struct intel_crtc *crtc)
4419 {
4420         struct drm_device *dev = crtc->base.dev;
4421         struct drm_i915_private *dev_priv = dev->dev_private;
4422
4423         if (!crtc->config->ips_enabled)
4424                 return;
4425
4426         /*
4427          * We can only enable IPS after we enable a plane and wait for a vblank
4428          * This function is called from post_plane_update, which is run after
4429          * a vblank wait.
4430          */
4431
4432         assert_plane_enabled(dev_priv, crtc->plane);
4433         if (IS_BROADWELL(dev)) {
4434                 mutex_lock(&dev_priv->rps.hw_lock);
4435                 WARN_ON(sandybridge_pcode_write(dev_priv, DISPLAY_IPS_CONTROL, 0xc0000000));
4436                 mutex_unlock(&dev_priv->rps.hw_lock);
4437                 /* Quoting Art Runyan: "its not safe to expect any particular
4438                  * value in IPS_CTL bit 31 after enabling IPS through the
4439                  * mailbox." Moreover, the mailbox may return a bogus state,
4440                  * so we need to just enable it and continue on.
4441                  */
4442         } else {
4443                 I915_WRITE(IPS_CTL, IPS_ENABLE);
4444                 /* The bit only becomes 1 in the next vblank, so this wait here
4445                  * is essentially intel_wait_for_vblank. If we don't have this
4446                  * and don't wait for vblanks until the end of crtc_enable, then
4447                  * the HW state readout code will complain that the expected
4448                  * IPS_CTL value is not the one we read. */
4449                 if (wait_for(I915_READ_NOTRACE(IPS_CTL) & IPS_ENABLE, 50))
4450                         DRM_ERROR("Timed out waiting for IPS enable\n");
4451         }
4452 }
4453
4454 void hsw_disable_ips(struct intel_crtc *crtc)
4455 {
4456         struct drm_device *dev = crtc->base.dev;
4457         struct drm_i915_private *dev_priv = dev->dev_private;
4458
4459         if (!crtc->config->ips_enabled)
4460                 return;
4461
4462         assert_plane_enabled(dev_priv, crtc->plane);
4463         if (IS_BROADWELL(dev)) {
4464                 mutex_lock(&dev_priv->rps.hw_lock);
4465                 WARN_ON(sandybridge_pcode_write(dev_priv, DISPLAY_IPS_CONTROL, 0));
4466                 mutex_unlock(&dev_priv->rps.hw_lock);
4467                 /* wait for pcode to finish disabling IPS, which may take up to 42ms */
4468                 if (wait_for((I915_READ(IPS_CTL) & IPS_ENABLE) == 0, 42))
4469                         DRM_ERROR("Timed out waiting for IPS disable\n");
4470         } else {
4471                 I915_WRITE(IPS_CTL, 0);
4472                 POSTING_READ(IPS_CTL);
4473         }
4474
4475         /* We need to wait for a vblank before we can disable the plane. */
4476         intel_wait_for_vblank(dev, crtc->pipe);
4477 }
4478
4479 static void intel_crtc_dpms_overlay_disable(struct intel_crtc *intel_crtc)
4480 {
4481         if (intel_crtc->overlay) {
4482                 struct drm_device *dev = intel_crtc->base.dev;
4483                 struct drm_i915_private *dev_priv = dev->dev_private;
4484
4485                 mutex_lock(&dev->struct_mutex);
4486                 dev_priv->mm.interruptible = false;
4487                 (void) intel_overlay_switch_off(intel_crtc->overlay);
4488                 dev_priv->mm.interruptible = true;
4489                 mutex_unlock(&dev->struct_mutex);
4490         }
4491
4492         /* Let userspace switch the overlay on again. In most cases userspace
4493          * has to recompute where to put it anyway.
4494          */
4495 }
4496
4497 /**
4498  * intel_post_enable_primary - Perform operations after enabling primary plane
4499  * @crtc: the CRTC whose primary plane was just enabled
4500  *
4501  * Performs potentially sleeping operations that must be done after the primary
4502  * plane is enabled, such as updating FBC and IPS.  Note that this may be
4503  * called due to an explicit primary plane update, or due to an implicit
4504  * re-enable that is caused when a sprite plane is updated to no longer
4505  * completely hide the primary plane.
4506  */
4507 static void
4508 intel_post_enable_primary(struct drm_crtc *crtc)
4509 {
4510         struct drm_device *dev = crtc->dev;
4511         struct drm_i915_private *dev_priv = dev->dev_private;
4512         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4513         int pipe = intel_crtc->pipe;
4514
4515         /*
4516          * FIXME IPS should be fine as long as one plane is
4517          * enabled, but in practice it seems to have problems
4518          * when going from primary only to sprite only and vice
4519          * versa.
4520          */
4521         hsw_enable_ips(intel_crtc);
4522
4523         /*
4524          * Gen2 reports pipe underruns whenever all planes are disabled.
4525          * So don't enable underrun reporting before at least some planes
4526          * are enabled.
4527          * FIXME: Need to fix the logic to work when we turn off all planes
4528          * but leave the pipe running.
4529          */
4530         if (IS_GEN2(dev))
4531                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
4532
4533         /* Underruns don't always raise interrupts, so check manually. */
4534         intel_check_cpu_fifo_underruns(dev_priv);
4535         intel_check_pch_fifo_underruns(dev_priv);
4536 }
4537
4538 /* FIXME move all this to pre_plane_update() with proper state tracking */
4539 static void
4540 intel_pre_disable_primary(struct drm_crtc *crtc)
4541 {
4542         struct drm_device *dev = crtc->dev;
4543         struct drm_i915_private *dev_priv = dev->dev_private;
4544         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4545         int pipe = intel_crtc->pipe;
4546
4547         /*
4548          * Gen2 reports pipe underruns whenever all planes are disabled.
4549          * So diasble underrun reporting before all the planes get disabled.
4550          * FIXME: Need to fix the logic to work when we turn off all planes
4551          * but leave the pipe running.
4552          */
4553         if (IS_GEN2(dev))
4554                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, false);
4555
4556         /*
4557          * FIXME IPS should be fine as long as one plane is
4558          * enabled, but in practice it seems to have problems
4559          * when going from primary only to sprite only and vice
4560          * versa.
4561          */
4562         hsw_disable_ips(intel_crtc);
4563 }
4564
4565 /* FIXME get rid of this and use pre_plane_update */
4566 static void
4567 intel_pre_disable_primary_noatomic(struct drm_crtc *crtc)
4568 {
4569         struct drm_device *dev = crtc->dev;
4570         struct drm_i915_private *dev_priv = dev->dev_private;
4571         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4572         int pipe = intel_crtc->pipe;
4573
4574         intel_pre_disable_primary(crtc);
4575
4576         /*
4577          * Vblank time updates from the shadow to live plane control register
4578          * are blocked if the memory self-refresh mode is active at that
4579          * moment. So to make sure the plane gets truly disabled, disable
4580          * first the self-refresh mode. The self-refresh enable bit in turn
4581          * will be checked/applied by the HW only at the next frame start
4582          * event which is after the vblank start event, so we need to have a
4583          * wait-for-vblank between disabling the plane and the pipe.
4584          */
4585         if (HAS_GMCH_DISPLAY(dev)) {
4586                 intel_set_memory_cxsr(dev_priv, false);
4587                 dev_priv->wm.vlv.cxsr = false;
4588                 intel_wait_for_vblank(dev, pipe);
4589         }
4590 }
4591
4592 static void intel_post_plane_update(struct intel_crtc_state *old_crtc_state)
4593 {
4594         struct intel_crtc *crtc = to_intel_crtc(old_crtc_state->base.crtc);
4595         struct drm_atomic_state *old_state = old_crtc_state->base.state;
4596         struct intel_crtc_state *pipe_config =
4597                 to_intel_crtc_state(crtc->base.state);
4598         struct drm_device *dev = crtc->base.dev;
4599         struct drm_plane *primary = crtc->base.primary;
4600         struct drm_plane_state *old_pri_state =
4601                 drm_atomic_get_existing_plane_state(old_state, primary);
4602
4603         intel_frontbuffer_flip(dev, pipe_config->fb_bits);
4604
4605         crtc->wm.cxsr_allowed = true;
4606
4607         if (pipe_config->update_wm_post && pipe_config->base.active)
4608                 intel_update_watermarks(&crtc->base);
4609
4610         if (old_pri_state) {
4611                 struct intel_plane_state *primary_state =
4612                         to_intel_plane_state(primary->state);
4613                 struct intel_plane_state *old_primary_state =
4614                         to_intel_plane_state(old_pri_state);
4615
4616                 intel_fbc_post_update(crtc);
4617
4618                 if (primary_state->visible &&
4619                     (needs_modeset(&pipe_config->base) ||
4620                      !old_primary_state->visible))
4621                         intel_post_enable_primary(&crtc->base);
4622         }
4623 }
4624
4625 static void intel_pre_plane_update(struct intel_crtc_state *old_crtc_state)
4626 {
4627         struct intel_crtc *crtc = to_intel_crtc(old_crtc_state->base.crtc);
4628         struct drm_device *dev = crtc->base.dev;
4629         struct drm_i915_private *dev_priv = dev->dev_private;
4630         struct intel_crtc_state *pipe_config =
4631                 to_intel_crtc_state(crtc->base.state);
4632         struct drm_atomic_state *old_state = old_crtc_state->base.state;
4633         struct drm_plane *primary = crtc->base.primary;
4634         struct drm_plane_state *old_pri_state =
4635                 drm_atomic_get_existing_plane_state(old_state, primary);
4636         bool modeset = needs_modeset(&pipe_config->base);
4637
4638         if (old_pri_state) {
4639                 struct intel_plane_state *primary_state =
4640                         to_intel_plane_state(primary->state);
4641                 struct intel_plane_state *old_primary_state =
4642                         to_intel_plane_state(old_pri_state);
4643
4644                 intel_fbc_pre_update(crtc);
4645
4646                 if (old_primary_state->visible &&
4647                     (modeset || !primary_state->visible))
4648                         intel_pre_disable_primary(&crtc->base);
4649         }
4650
4651         if (pipe_config->disable_cxsr && HAS_GMCH_DISPLAY(dev)) {
4652                 crtc->wm.cxsr_allowed = false;
4653
4654                 /*
4655                  * Vblank time updates from the shadow to live plane control register
4656                  * are blocked if the memory self-refresh mode is active at that
4657                  * moment. So to make sure the plane gets truly disabled, disable
4658                  * first the self-refresh mode. The self-refresh enable bit in turn
4659                  * will be checked/applied by the HW only at the next frame start
4660                  * event which is after the vblank start event, so we need to have a
4661                  * wait-for-vblank between disabling the plane and the pipe.
4662                  */
4663                 if (old_crtc_state->base.active) {
4664                         intel_set_memory_cxsr(dev_priv, false);
4665                         dev_priv->wm.vlv.cxsr = false;
4666                         intel_wait_for_vblank(dev, crtc->pipe);
4667                 }
4668         }
4669
4670         /*
4671          * IVB workaround: must disable low power watermarks for at least
4672          * one frame before enabling scaling.  LP watermarks can be re-enabled
4673          * when scaling is disabled.
4674          *
4675          * WaCxSRDisabledForSpriteScaling:ivb
4676          */
4677         if (pipe_config->disable_lp_wm) {
4678                 ilk_disable_lp_wm(dev);
4679                 intel_wait_for_vblank(dev, crtc->pipe);
4680         }
4681
4682         /*
4683          * If we're doing a modeset, we're done.  No need to do any pre-vblank
4684          * watermark programming here.
4685          */
4686         if (needs_modeset(&pipe_config->base))
4687                 return;
4688
4689         /*
4690          * For platforms that support atomic watermarks, program the
4691          * 'intermediate' watermarks immediately.  On pre-gen9 platforms, these
4692          * will be the intermediate values that are safe for both pre- and
4693          * post- vblank; when vblank happens, the 'active' values will be set
4694          * to the final 'target' values and we'll do this again to get the
4695          * optimal watermarks.  For gen9+ platforms, the values we program here
4696          * will be the final target values which will get automatically latched
4697          * at vblank time; no further programming will be necessary.
4698          *
4699          * If a platform hasn't been transitioned to atomic watermarks yet,
4700          * we'll continue to update watermarks the old way, if flags tell
4701          * us to.
4702          */
4703         if (dev_priv->display.initial_watermarks != NULL)
4704                 dev_priv->display.initial_watermarks(pipe_config);
4705         else if (pipe_config->update_wm_pre)
4706                 intel_update_watermarks(&crtc->base);
4707 }
4708
4709 static void intel_crtc_disable_planes(struct drm_crtc *crtc, unsigned plane_mask)
4710 {
4711         struct drm_device *dev = crtc->dev;
4712         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4713         struct drm_plane *p;
4714         int pipe = intel_crtc->pipe;
4715
4716         intel_crtc_dpms_overlay_disable(intel_crtc);
4717
4718         drm_for_each_plane_mask(p, dev, plane_mask)
4719                 to_intel_plane(p)->disable_plane(p, crtc);
4720
4721         /*
4722          * FIXME: Once we grow proper nuclear flip support out of this we need
4723          * to compute the mask of flip planes precisely. For the time being
4724          * consider this a flip to a NULL plane.
4725          */
4726         intel_frontbuffer_flip(dev, INTEL_FRONTBUFFER_ALL_MASK(pipe));
4727 }
4728
4729 static void ironlake_crtc_enable(struct drm_crtc *crtc)
4730 {
4731         struct drm_device *dev = crtc->dev;
4732         struct drm_i915_private *dev_priv = dev->dev_private;
4733         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4734         struct intel_encoder *encoder;
4735         int pipe = intel_crtc->pipe;
4736         struct intel_crtc_state *pipe_config =
4737                 to_intel_crtc_state(crtc->state);
4738
4739         if (WARN_ON(intel_crtc->active))
4740                 return;
4741
4742         /*
4743          * Sometimes spurious CPU pipe underruns happen during FDI
4744          * training, at least with VGA+HDMI cloning. Suppress them.
4745          *
4746          * On ILK we get an occasional spurious CPU pipe underruns
4747          * between eDP port A enable and vdd enable. Also PCH port
4748          * enable seems to result in the occasional CPU pipe underrun.
4749          *
4750          * Spurious PCH underruns also occur during PCH enabling.
4751          */
4752         if (intel_crtc->config->has_pch_encoder || IS_GEN5(dev_priv))
4753                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, false);
4754         if (intel_crtc->config->has_pch_encoder)
4755                 intel_set_pch_fifo_underrun_reporting(dev_priv, pipe, false);
4756
4757         if (intel_crtc->config->has_pch_encoder)
4758                 intel_prepare_shared_dpll(intel_crtc);
4759
4760         if (intel_crtc->config->has_dp_encoder)
4761                 intel_dp_set_m_n(intel_crtc, M1_N1);
4762
4763         intel_set_pipe_timings(intel_crtc);
4764         intel_set_pipe_src_size(intel_crtc);
4765
4766         if (intel_crtc->config->has_pch_encoder) {
4767                 intel_cpu_transcoder_set_m_n(intel_crtc,
4768                                      &intel_crtc->config->fdi_m_n, NULL);
4769         }
4770
4771         ironlake_set_pipeconf(crtc);
4772
4773         intel_crtc->active = true;
4774
4775         for_each_encoder_on_crtc(dev, crtc, encoder)
4776                 if (encoder->pre_enable)
4777                         encoder->pre_enable(encoder);
4778
4779         if (intel_crtc->config->has_pch_encoder) {
4780                 /* Note: FDI PLL enabling _must_ be done before we enable the
4781                  * cpu pipes, hence this is separate from all the other fdi/pch
4782                  * enabling. */
4783                 ironlake_fdi_pll_enable(intel_crtc);
4784         } else {
4785                 assert_fdi_tx_disabled(dev_priv, pipe);
4786                 assert_fdi_rx_disabled(dev_priv, pipe);
4787         }
4788
4789         ironlake_pfit_enable(intel_crtc);
4790
4791         /*
4792          * On ILK+ LUT must be loaded before the pipe is running but with
4793          * clocks enabled
4794          */
4795         intel_color_load_luts(&pipe_config->base);
4796
4797         if (dev_priv->display.initial_watermarks != NULL)
4798                 dev_priv->display.initial_watermarks(intel_crtc->config);
4799         intel_enable_pipe(intel_crtc);
4800
4801         if (intel_crtc->config->has_pch_encoder)
4802                 ironlake_pch_enable(crtc);
4803
4804         assert_vblank_disabled(crtc);
4805         drm_crtc_vblank_on(crtc);
4806
4807         for_each_encoder_on_crtc(dev, crtc, encoder)
4808                 encoder->enable(encoder);
4809
4810         if (HAS_PCH_CPT(dev))
4811                 cpt_verify_modeset(dev, intel_crtc->pipe);
4812
4813         /* Must wait for vblank to avoid spurious PCH FIFO underruns */
4814         if (intel_crtc->config->has_pch_encoder)
4815                 intel_wait_for_vblank(dev, pipe);
4816         intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
4817         intel_set_pch_fifo_underrun_reporting(dev_priv, pipe, true);
4818 }
4819
4820 /* IPS only exists on ULT machines and is tied to pipe A. */
4821 static bool hsw_crtc_supports_ips(struct intel_crtc *crtc)
4822 {
4823         return HAS_IPS(crtc->base.dev) && crtc->pipe == PIPE_A;
4824 }
4825
4826 static void haswell_crtc_enable(struct drm_crtc *crtc)
4827 {
4828         struct drm_device *dev = crtc->dev;
4829         struct drm_i915_private *dev_priv = dev->dev_private;
4830         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4831         struct intel_encoder *encoder;
4832         int pipe = intel_crtc->pipe, hsw_workaround_pipe;
4833         enum transcoder cpu_transcoder = intel_crtc->config->cpu_transcoder;
4834         struct intel_crtc_state *pipe_config =
4835                 to_intel_crtc_state(crtc->state);
4836
4837         if (WARN_ON(intel_crtc->active))
4838                 return;
4839
4840         if (intel_crtc->config->has_pch_encoder)
4841                 intel_set_pch_fifo_underrun_reporting(dev_priv, TRANSCODER_A,
4842                                                       false);
4843
4844         if (intel_crtc->config->shared_dpll)
4845                 intel_enable_shared_dpll(intel_crtc);
4846
4847         if (intel_crtc->config->has_dp_encoder)
4848                 intel_dp_set_m_n(intel_crtc, M1_N1);
4849
4850         if (!intel_crtc->config->has_dsi_encoder)
4851                 intel_set_pipe_timings(intel_crtc);
4852
4853         intel_set_pipe_src_size(intel_crtc);
4854
4855         if (cpu_transcoder != TRANSCODER_EDP &&
4856             !transcoder_is_dsi(cpu_transcoder)) {
4857                 I915_WRITE(PIPE_MULT(cpu_transcoder),
4858                            intel_crtc->config->pixel_multiplier - 1);
4859         }
4860
4861         if (intel_crtc->config->has_pch_encoder) {
4862                 intel_cpu_transcoder_set_m_n(intel_crtc,
4863                                      &intel_crtc->config->fdi_m_n, NULL);
4864         }
4865
4866         if (!intel_crtc->config->has_dsi_encoder)
4867                 haswell_set_pipeconf(crtc);
4868
4869         haswell_set_pipemisc(crtc);
4870
4871         intel_color_set_csc(&pipe_config->base);
4872
4873         intel_crtc->active = true;
4874
4875         if (intel_crtc->config->has_pch_encoder)
4876                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, false);
4877         else
4878                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
4879
4880         for_each_encoder_on_crtc(dev, crtc, encoder) {
4881                 if (encoder->pre_enable)
4882                         encoder->pre_enable(encoder);
4883         }
4884
4885         if (intel_crtc->config->has_pch_encoder)
4886                 dev_priv->display.fdi_link_train(crtc);
4887
4888         if (!intel_crtc->config->has_dsi_encoder)
4889                 intel_ddi_enable_pipe_clock(intel_crtc);
4890
4891         if (INTEL_INFO(dev)->gen >= 9)
4892                 skylake_pfit_enable(intel_crtc);
4893         else
4894                 ironlake_pfit_enable(intel_crtc);
4895
4896         /*
4897          * On ILK+ LUT must be loaded before the pipe is running but with
4898          * clocks enabled
4899          */
4900         intel_color_load_luts(&pipe_config->base);
4901
4902         intel_ddi_set_pipe_settings(crtc);
4903         if (!intel_crtc->config->has_dsi_encoder)
4904                 intel_ddi_enable_transcoder_func(crtc);
4905
4906         if (dev_priv->display.initial_watermarks != NULL)
4907                 dev_priv->display.initial_watermarks(pipe_config);
4908         else
4909                 intel_update_watermarks(crtc);
4910
4911         /* XXX: Do the pipe assertions at the right place for BXT DSI. */
4912         if (!intel_crtc->config->has_dsi_encoder)
4913                 intel_enable_pipe(intel_crtc);
4914
4915         if (intel_crtc->config->has_pch_encoder)
4916                 lpt_pch_enable(crtc);
4917
4918         if (intel_crtc->config->dp_encoder_is_mst)
4919                 intel_ddi_set_vc_payload_alloc(crtc, true);
4920
4921         assert_vblank_disabled(crtc);
4922         drm_crtc_vblank_on(crtc);
4923
4924         for_each_encoder_on_crtc(dev, crtc, encoder) {
4925                 encoder->enable(encoder);
4926                 intel_opregion_notify_encoder(encoder, true);
4927         }
4928
4929         if (intel_crtc->config->has_pch_encoder) {
4930                 intel_wait_for_vblank(dev, pipe);
4931                 intel_wait_for_vblank(dev, pipe);
4932                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
4933                 intel_set_pch_fifo_underrun_reporting(dev_priv, TRANSCODER_A,
4934                                                       true);
4935         }
4936
4937         /* If we change the relative order between pipe/planes enabling, we need
4938          * to change the workaround. */
4939         hsw_workaround_pipe = pipe_config->hsw_workaround_pipe;
4940         if (IS_HASWELL(dev) && hsw_workaround_pipe != INVALID_PIPE) {
4941                 intel_wait_for_vblank(dev, hsw_workaround_pipe);
4942                 intel_wait_for_vblank(dev, hsw_workaround_pipe);
4943         }
4944 }
4945
4946 static void ironlake_pfit_disable(struct intel_crtc *crtc, bool force)
4947 {
4948         struct drm_device *dev = crtc->base.dev;
4949         struct drm_i915_private *dev_priv = dev->dev_private;
4950         int pipe = crtc->pipe;
4951
4952         /* To avoid upsetting the power well on haswell only disable the pfit if
4953          * it's in use. The hw state code will make sure we get this right. */
4954         if (force || crtc->config->pch_pfit.enabled) {
4955                 I915_WRITE(PF_CTL(pipe), 0);
4956                 I915_WRITE(PF_WIN_POS(pipe), 0);
4957                 I915_WRITE(PF_WIN_SZ(pipe), 0);
4958         }
4959 }
4960
4961 static void ironlake_crtc_disable(struct drm_crtc *crtc)
4962 {
4963         struct drm_device *dev = crtc->dev;
4964         struct drm_i915_private *dev_priv = dev->dev_private;
4965         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4966         struct intel_encoder *encoder;
4967         int pipe = intel_crtc->pipe;
4968
4969         /*
4970          * Sometimes spurious CPU pipe underruns happen when the
4971          * pipe is already disabled, but FDI RX/TX is still enabled.
4972          * Happens at least with VGA+HDMI cloning. Suppress them.
4973          */
4974         if (intel_crtc->config->has_pch_encoder) {
4975                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, false);
4976                 intel_set_pch_fifo_underrun_reporting(dev_priv, pipe, false);
4977         }
4978
4979         for_each_encoder_on_crtc(dev, crtc, encoder)
4980                 encoder->disable(encoder);
4981
4982         drm_crtc_vblank_off(crtc);
4983         assert_vblank_disabled(crtc);
4984
4985         intel_disable_pipe(intel_crtc);
4986
4987         ironlake_pfit_disable(intel_crtc, false);
4988
4989         if (intel_crtc->config->has_pch_encoder)
4990                 ironlake_fdi_disable(crtc);
4991
4992         for_each_encoder_on_crtc(dev, crtc, encoder)
4993                 if (encoder->post_disable)
4994                         encoder->post_disable(encoder);
4995
4996         if (intel_crtc->config->has_pch_encoder) {
4997                 ironlake_disable_pch_transcoder(dev_priv, pipe);
4998
4999                 if (HAS_PCH_CPT(dev)) {
5000                         i915_reg_t reg;
5001                         u32 temp;
5002
5003                         /* disable TRANS_DP_CTL */
5004                         reg = TRANS_DP_CTL(pipe);
5005                         temp = I915_READ(reg);
5006                         temp &= ~(TRANS_DP_OUTPUT_ENABLE |
5007                                   TRANS_DP_PORT_SEL_MASK);
5008                         temp |= TRANS_DP_PORT_SEL_NONE;
5009                         I915_WRITE(reg, temp);
5010
5011                         /* disable DPLL_SEL */
5012                         temp = I915_READ(PCH_DPLL_SEL);
5013                         temp &= ~(TRANS_DPLL_ENABLE(pipe) | TRANS_DPLLB_SEL(pipe));
5014                         I915_WRITE(PCH_DPLL_SEL, temp);
5015                 }
5016
5017                 ironlake_fdi_pll_disable(intel_crtc);
5018         }
5019
5020         intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
5021         intel_set_pch_fifo_underrun_reporting(dev_priv, pipe, true);
5022 }
5023
5024 static void haswell_crtc_disable(struct drm_crtc *crtc)
5025 {
5026         struct drm_device *dev = crtc->dev;
5027         struct drm_i915_private *dev_priv = dev->dev_private;
5028         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5029         struct intel_encoder *encoder;
5030         enum transcoder cpu_transcoder = intel_crtc->config->cpu_transcoder;
5031
5032         if (intel_crtc->config->has_pch_encoder)
5033                 intel_set_pch_fifo_underrun_reporting(dev_priv, TRANSCODER_A,
5034                                                       false);
5035
5036         for_each_encoder_on_crtc(dev, crtc, encoder) {
5037                 intel_opregion_notify_encoder(encoder, false);
5038                 encoder->disable(encoder);
5039         }
5040
5041         drm_crtc_vblank_off(crtc);
5042         assert_vblank_disabled(crtc);
5043
5044         /* XXX: Do the pipe assertions at the right place for BXT DSI. */
5045         if (!intel_crtc->config->has_dsi_encoder)
5046                 intel_disable_pipe(intel_crtc);
5047
5048         if (intel_crtc->config->dp_encoder_is_mst)
5049                 intel_ddi_set_vc_payload_alloc(crtc, false);
5050
5051         if (!intel_crtc->config->has_dsi_encoder)
5052                 intel_ddi_disable_transcoder_func(dev_priv, cpu_transcoder);
5053
5054         if (INTEL_INFO(dev)->gen >= 9)
5055                 skylake_scaler_disable(intel_crtc);
5056         else
5057                 ironlake_pfit_disable(intel_crtc, false);
5058
5059         if (!intel_crtc->config->has_dsi_encoder)
5060                 intel_ddi_disable_pipe_clock(intel_crtc);
5061
5062         for_each_encoder_on_crtc(dev, crtc, encoder)
5063                 if (encoder->post_disable)
5064                         encoder->post_disable(encoder);
5065
5066         if (intel_crtc->config->has_pch_encoder) {
5067                 lpt_disable_pch_transcoder(dev_priv);
5068                 lpt_disable_iclkip(dev_priv);
5069                 intel_ddi_fdi_disable(crtc);
5070
5071                 intel_set_pch_fifo_underrun_reporting(dev_priv, TRANSCODER_A,
5072                                                       true);
5073         }
5074 }
5075
5076 static void i9xx_pfit_enable(struct intel_crtc *crtc)
5077 {
5078         struct drm_device *dev = crtc->base.dev;
5079         struct drm_i915_private *dev_priv = dev->dev_private;
5080         struct intel_crtc_state *pipe_config = crtc->config;
5081
5082         if (!pipe_config->gmch_pfit.control)
5083                 return;
5084
5085         /*
5086          * The panel fitter should only be adjusted whilst the pipe is disabled,
5087          * according to register description and PRM.
5088          */
5089         WARN_ON(I915_READ(PFIT_CONTROL) & PFIT_ENABLE);
5090         assert_pipe_disabled(dev_priv, crtc->pipe);
5091
5092         I915_WRITE(PFIT_PGM_RATIOS, pipe_config->gmch_pfit.pgm_ratios);
5093         I915_WRITE(PFIT_CONTROL, pipe_config->gmch_pfit.control);
5094
5095         /* Border color in case we don't scale up to the full screen. Black by
5096          * default, change to something else for debugging. */
5097         I915_WRITE(BCLRPAT(crtc->pipe), 0);
5098 }
5099
5100 static enum intel_display_power_domain port_to_power_domain(enum port port)
5101 {
5102         switch (port) {
5103         case PORT_A:
5104                 return POWER_DOMAIN_PORT_DDI_A_LANES;
5105         case PORT_B:
5106                 return POWER_DOMAIN_PORT_DDI_B_LANES;
5107         case PORT_C:
5108                 return POWER_DOMAIN_PORT_DDI_C_LANES;
5109         case PORT_D:
5110                 return POWER_DOMAIN_PORT_DDI_D_LANES;
5111         case PORT_E:
5112                 return POWER_DOMAIN_PORT_DDI_E_LANES;
5113         default:
5114                 MISSING_CASE(port);
5115                 return POWER_DOMAIN_PORT_OTHER;
5116         }
5117 }
5118
5119 static enum intel_display_power_domain port_to_aux_power_domain(enum port port)
5120 {
5121         switch (port) {
5122         case PORT_A:
5123                 return POWER_DOMAIN_AUX_A;
5124         case PORT_B:
5125                 return POWER_DOMAIN_AUX_B;
5126         case PORT_C:
5127                 return POWER_DOMAIN_AUX_C;
5128         case PORT_D:
5129                 return POWER_DOMAIN_AUX_D;
5130         case PORT_E:
5131                 /* FIXME: Check VBT for actual wiring of PORT E */
5132                 return POWER_DOMAIN_AUX_D;
5133         default:
5134                 MISSING_CASE(port);
5135                 return POWER_DOMAIN_AUX_A;
5136         }
5137 }
5138
5139 enum intel_display_power_domain
5140 intel_display_port_power_domain(struct intel_encoder *intel_encoder)
5141 {
5142         struct drm_device *dev = intel_encoder->base.dev;
5143         struct intel_digital_port *intel_dig_port;
5144
5145         switch (intel_encoder->type) {
5146         case INTEL_OUTPUT_UNKNOWN:
5147                 /* Only DDI platforms should ever use this output type */
5148                 WARN_ON_ONCE(!HAS_DDI(dev));
5149         case INTEL_OUTPUT_DISPLAYPORT:
5150         case INTEL_OUTPUT_HDMI:
5151         case INTEL_OUTPUT_EDP:
5152                 intel_dig_port = enc_to_dig_port(&intel_encoder->base);
5153                 return port_to_power_domain(intel_dig_port->port);
5154         case INTEL_OUTPUT_DP_MST:
5155                 intel_dig_port = enc_to_mst(&intel_encoder->base)->primary;
5156                 return port_to_power_domain(intel_dig_port->port);
5157         case INTEL_OUTPUT_ANALOG:
5158                 return POWER_DOMAIN_PORT_CRT;
5159         case INTEL_OUTPUT_DSI:
5160                 return POWER_DOMAIN_PORT_DSI;
5161         default:
5162                 return POWER_DOMAIN_PORT_OTHER;
5163         }
5164 }
5165
5166 enum intel_display_power_domain
5167 intel_display_port_aux_power_domain(struct intel_encoder *intel_encoder)
5168 {
5169         struct drm_device *dev = intel_encoder->base.dev;
5170         struct intel_digital_port *intel_dig_port;
5171
5172         switch (intel_encoder->type) {
5173         case INTEL_OUTPUT_UNKNOWN:
5174         case INTEL_OUTPUT_HDMI:
5175                 /*
5176                  * Only DDI platforms should ever use these output types.
5177                  * We can get here after the HDMI detect code has already set
5178                  * the type of the shared encoder. Since we can't be sure
5179                  * what's the status of the given connectors, play safe and
5180                  * run the DP detection too.
5181                  */
5182                 WARN_ON_ONCE(!HAS_DDI(dev));
5183         case INTEL_OUTPUT_DISPLAYPORT:
5184         case INTEL_OUTPUT_EDP:
5185                 intel_dig_port = enc_to_dig_port(&intel_encoder->base);
5186                 return port_to_aux_power_domain(intel_dig_port->port);
5187         case INTEL_OUTPUT_DP_MST:
5188                 intel_dig_port = enc_to_mst(&intel_encoder->base)->primary;
5189                 return port_to_aux_power_domain(intel_dig_port->port);
5190         default:
5191                 MISSING_CASE(intel_encoder->type);
5192                 return POWER_DOMAIN_AUX_A;
5193         }
5194 }
5195
5196 static unsigned long get_crtc_power_domains(struct drm_crtc *crtc,
5197                                             struct intel_crtc_state *crtc_state)
5198 {
5199         struct drm_device *dev = crtc->dev;
5200         struct drm_encoder *encoder;
5201         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5202         enum pipe pipe = intel_crtc->pipe;
5203         unsigned long mask;
5204         enum transcoder transcoder = crtc_state->cpu_transcoder;
5205
5206         if (!crtc_state->base.active)
5207                 return 0;
5208
5209         mask = BIT(POWER_DOMAIN_PIPE(pipe));
5210         mask |= BIT(POWER_DOMAIN_TRANSCODER(transcoder));
5211         if (crtc_state->pch_pfit.enabled ||
5212             crtc_state->pch_pfit.force_thru)
5213                 mask |= BIT(POWER_DOMAIN_PIPE_PANEL_FITTER(pipe));
5214
5215         drm_for_each_encoder_mask(encoder, dev, crtc_state->base.encoder_mask) {
5216                 struct intel_encoder *intel_encoder = to_intel_encoder(encoder);
5217
5218                 mask |= BIT(intel_display_port_power_domain(intel_encoder));
5219         }
5220
5221         if (crtc_state->shared_dpll)
5222                 mask |= BIT(POWER_DOMAIN_PLLS);
5223
5224         return mask;
5225 }
5226
5227 static unsigned long
5228 modeset_get_crtc_power_domains(struct drm_crtc *crtc,
5229                                struct intel_crtc_state *crtc_state)
5230 {
5231         struct drm_i915_private *dev_priv = crtc->dev->dev_private;
5232         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5233         enum intel_display_power_domain domain;
5234         unsigned long domains, new_domains, old_domains;
5235
5236         old_domains = intel_crtc->enabled_power_domains;
5237         intel_crtc->enabled_power_domains = new_domains =
5238                 get_crtc_power_domains(crtc, crtc_state);
5239
5240         domains = new_domains & ~old_domains;
5241
5242         for_each_power_domain(domain, domains)
5243                 intel_display_power_get(dev_priv, domain);
5244
5245         return old_domains & ~new_domains;
5246 }
5247
5248 static void modeset_put_power_domains(struct drm_i915_private *dev_priv,
5249                                       unsigned long domains)
5250 {
5251         enum intel_display_power_domain domain;
5252
5253         for_each_power_domain(domain, domains)
5254                 intel_display_power_put(dev_priv, domain);
5255 }
5256
5257 static int intel_compute_max_dotclk(struct drm_i915_private *dev_priv)
5258 {
5259         int max_cdclk_freq = dev_priv->max_cdclk_freq;
5260
5261         if (INTEL_INFO(dev_priv)->gen >= 9 ||
5262             IS_HASWELL(dev_priv) || IS_BROADWELL(dev_priv))
5263                 return max_cdclk_freq;
5264         else if (IS_CHERRYVIEW(dev_priv))
5265                 return max_cdclk_freq*95/100;
5266         else if (INTEL_INFO(dev_priv)->gen < 4)
5267                 return 2*max_cdclk_freq*90/100;
5268         else
5269                 return max_cdclk_freq*90/100;
5270 }
5271
5272 static int skl_calc_cdclk(int max_pixclk, int vco);
5273
5274 static void intel_update_max_cdclk(struct drm_device *dev)
5275 {
5276         struct drm_i915_private *dev_priv = dev->dev_private;
5277
5278         if (IS_SKYLAKE(dev) || IS_KABYLAKE(dev)) {
5279                 u32 limit = I915_READ(SKL_DFSM) & SKL_DFSM_CDCLK_LIMIT_MASK;
5280                 int max_cdclk, vco;
5281
5282                 vco = dev_priv->skl_preferred_vco_freq;
5283                 WARN_ON(vco != 8100000 && vco != 8640000);
5284
5285                 /*
5286                  * Use the lower (vco 8640) cdclk values as a
5287                  * first guess. skl_calc_cdclk() will correct it
5288                  * if the preferred vco is 8100 instead.
5289                  */
5290                 if (limit == SKL_DFSM_CDCLK_LIMIT_675)
5291                         max_cdclk = 617143;
5292                 else if (limit == SKL_DFSM_CDCLK_LIMIT_540)
5293                         max_cdclk = 540000;
5294                 else if (limit == SKL_DFSM_CDCLK_LIMIT_450)
5295                         max_cdclk = 432000;
5296                 else
5297                         max_cdclk = 308571;
5298
5299                 dev_priv->max_cdclk_freq = skl_calc_cdclk(max_cdclk, vco);
5300         } else if (IS_BROXTON(dev)) {
5301                 dev_priv->max_cdclk_freq = 624000;
5302         } else if (IS_BROADWELL(dev))  {
5303                 /*
5304                  * FIXME with extra cooling we can allow
5305                  * 540 MHz for ULX and 675 Mhz for ULT.
5306                  * How can we know if extra cooling is
5307                  * available? PCI ID, VTB, something else?
5308                  */
5309                 if (I915_READ(FUSE_STRAP) & HSW_CDCLK_LIMIT)
5310                         dev_priv->max_cdclk_freq = 450000;
5311                 else if (IS_BDW_ULX(dev))
5312                         dev_priv->max_cdclk_freq = 450000;
5313                 else if (IS_BDW_ULT(dev))
5314                         dev_priv->max_cdclk_freq = 540000;
5315                 else
5316                         dev_priv->max_cdclk_freq = 675000;
5317         } else if (IS_CHERRYVIEW(dev)) {
5318                 dev_priv->max_cdclk_freq = 320000;
5319         } else if (IS_VALLEYVIEW(dev)) {
5320                 dev_priv->max_cdclk_freq = 400000;
5321         } else {
5322                 /* otherwise assume cdclk is fixed */
5323                 dev_priv->max_cdclk_freq = dev_priv->cdclk_freq;
5324         }
5325
5326         dev_priv->max_dotclk_freq = intel_compute_max_dotclk(dev_priv);
5327
5328         DRM_DEBUG_DRIVER("Max CD clock rate: %d kHz\n",
5329                          dev_priv->max_cdclk_freq);
5330
5331         DRM_DEBUG_DRIVER("Max dotclock rate: %d kHz\n",
5332                          dev_priv->max_dotclk_freq);
5333 }
5334
5335 static void intel_update_cdclk(struct drm_device *dev)
5336 {
5337         struct drm_i915_private *dev_priv = dev->dev_private;
5338
5339         dev_priv->cdclk_freq = dev_priv->display.get_display_clock_speed(dev);
5340
5341         if (INTEL_GEN(dev_priv) >= 9)
5342                 DRM_DEBUG_DRIVER("Current CD clock rate: %d kHz, VCO: %d kHz, ref: %d kHz\n",
5343                                  dev_priv->cdclk_freq, dev_priv->cdclk_pll.vco,
5344                                  dev_priv->cdclk_pll.ref);
5345         else
5346                 DRM_DEBUG_DRIVER("Current CD clock rate: %d kHz\n",
5347                                  dev_priv->cdclk_freq);
5348
5349         /*
5350          * 9:0 CMBUS [sic] CDCLK frequency (cdfreq):
5351          * Programmng [sic] note: bit[9:2] should be programmed to the number
5352          * of cdclk that generates 4MHz reference clock freq which is used to
5353          * generate GMBus clock. This will vary with the cdclk freq.
5354          */
5355         if (IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv))
5356                 I915_WRITE(GMBUSFREQ_VLV, DIV_ROUND_UP(dev_priv->cdclk_freq, 1000));
5357 }
5358
5359 /* convert from kHz to .1 fixpoint MHz with -1MHz offset */
5360 static int skl_cdclk_decimal(int cdclk)
5361 {
5362         return DIV_ROUND_CLOSEST(cdclk - 1000, 500);
5363 }
5364
5365 static int bxt_de_pll_vco(struct drm_i915_private *dev_priv, int cdclk)
5366 {
5367         int ratio;
5368
5369         if (cdclk == dev_priv->cdclk_pll.ref)
5370                 return 0;
5371
5372         switch (cdclk) {
5373         default:
5374                 MISSING_CASE(cdclk);
5375         case 144000:
5376         case 288000:
5377         case 384000:
5378         case 576000:
5379                 ratio = 60;
5380                 break;
5381         case 624000:
5382                 ratio = 65;
5383                 break;
5384         }
5385
5386         return dev_priv->cdclk_pll.ref * ratio;
5387 }
5388
5389 static void bxt_de_pll_disable(struct drm_i915_private *dev_priv)
5390 {
5391         I915_WRITE(BXT_DE_PLL_ENABLE, 0);
5392
5393         /* Timeout 200us */
5394         if (wait_for((I915_READ(BXT_DE_PLL_ENABLE) & BXT_DE_PLL_LOCK) == 0, 1))
5395                 DRM_ERROR("timeout waiting for DE PLL unlock\n");
5396
5397         dev_priv->cdclk_pll.vco = 0;
5398 }
5399
5400 static void bxt_de_pll_enable(struct drm_i915_private *dev_priv, int vco)
5401 {
5402         int ratio = DIV_ROUND_CLOSEST(vco, dev_priv->cdclk_pll.ref);
5403         u32 val;
5404
5405         val = I915_READ(BXT_DE_PLL_CTL);
5406         val &= ~BXT_DE_PLL_RATIO_MASK;
5407         val |= BXT_DE_PLL_RATIO(ratio);
5408         I915_WRITE(BXT_DE_PLL_CTL, val);
5409
5410         I915_WRITE(BXT_DE_PLL_ENABLE, BXT_DE_PLL_PLL_ENABLE);
5411
5412         /* Timeout 200us */
5413         if (wait_for((I915_READ(BXT_DE_PLL_ENABLE) & BXT_DE_PLL_LOCK) != 0, 1))
5414                 DRM_ERROR("timeout waiting for DE PLL lock\n");
5415
5416         dev_priv->cdclk_pll.vco = vco;
5417 }
5418
5419 static void broxton_set_cdclk(struct drm_i915_private *dev_priv, int cdclk)
5420 {
5421         u32 val, divider;
5422         int vco, ret;
5423
5424         vco = bxt_de_pll_vco(dev_priv, cdclk);
5425
5426         DRM_DEBUG_DRIVER("Changing CDCLK to %d kHz (VCO %d kHz)\n", cdclk, vco);
5427
5428         /* cdclk = vco / 2 / div{1,1.5,2,4} */
5429         switch (DIV_ROUND_CLOSEST(vco, cdclk)) {
5430         case 8:
5431                 divider = BXT_CDCLK_CD2X_DIV_SEL_4;
5432                 break;
5433         case 4:
5434                 divider = BXT_CDCLK_CD2X_DIV_SEL_2;
5435                 break;
5436         case 3:
5437                 divider = BXT_CDCLK_CD2X_DIV_SEL_1_5;
5438                 break;
5439         case 2:
5440                 divider = BXT_CDCLK_CD2X_DIV_SEL_1;
5441                 break;
5442         default:
5443                 WARN_ON(cdclk != dev_priv->cdclk_pll.ref);
5444                 WARN_ON(vco != 0);
5445
5446                 divider = BXT_CDCLK_CD2X_DIV_SEL_1;
5447                 break;
5448         }
5449
5450         /* Inform power controller of upcoming frequency change */
5451         mutex_lock(&dev_priv->rps.hw_lock);
5452         ret = sandybridge_pcode_write(dev_priv, HSW_PCODE_DE_WRITE_FREQ_REQ,
5453                                       0x80000000);
5454         mutex_unlock(&dev_priv->rps.hw_lock);
5455
5456         if (ret) {
5457                 DRM_ERROR("PCode CDCLK freq change notify failed (err %d, freq %d)\n",
5458                           ret, cdclk);
5459                 return;
5460         }
5461
5462         if (dev_priv->cdclk_pll.vco != 0 &&
5463             dev_priv->cdclk_pll.vco != vco)
5464                 bxt_de_pll_disable(dev_priv);
5465
5466         if (dev_priv->cdclk_pll.vco != vco)
5467                 bxt_de_pll_enable(dev_priv, vco);
5468
5469         val = divider | skl_cdclk_decimal(cdclk);
5470         /*
5471          * FIXME if only the cd2x divider needs changing, it could be done
5472          * without shutting off the pipe (if only one pipe is active).
5473          */
5474         val |= BXT_CDCLK_CD2X_PIPE_NONE;
5475         /*
5476          * Disable SSA Precharge when CD clock frequency < 500 MHz,
5477          * enable otherwise.
5478          */
5479         if (cdclk >= 500000)
5480                 val |= BXT_CDCLK_SSA_PRECHARGE_ENABLE;
5481         I915_WRITE(CDCLK_CTL, val);
5482
5483         mutex_lock(&dev_priv->rps.hw_lock);
5484         ret = sandybridge_pcode_write(dev_priv, HSW_PCODE_DE_WRITE_FREQ_REQ,
5485                                       DIV_ROUND_UP(cdclk, 25000));
5486         mutex_unlock(&dev_priv->rps.hw_lock);
5487
5488         if (ret) {
5489                 DRM_ERROR("PCode CDCLK freq set failed, (err %d, freq %d)\n",
5490                           ret, cdclk);
5491                 return;
5492         }
5493
5494         intel_update_cdclk(dev_priv->dev);
5495 }
5496
5497 static void bxt_sanitize_cdclk(struct drm_i915_private *dev_priv)
5498 {
5499         u32 cdctl, expected;
5500
5501         intel_update_cdclk(dev_priv->dev);
5502
5503         if (dev_priv->cdclk_pll.vco == 0 ||
5504             dev_priv->cdclk_freq == dev_priv->cdclk_pll.ref)
5505                 goto sanitize;
5506
5507         /* DPLL okay; verify the cdclock
5508          *
5509          * Some BIOS versions leave an incorrect decimal frequency value and
5510          * set reserved MBZ bits in CDCLK_CTL at least during exiting from S4,
5511          * so sanitize this register.
5512          */
5513         cdctl = I915_READ(CDCLK_CTL);
5514         /*
5515          * Let's ignore the pipe field, since BIOS could have configured the
5516          * dividers both synching to an active pipe, or asynchronously
5517          * (PIPE_NONE).
5518          */
5519         cdctl &= ~BXT_CDCLK_CD2X_PIPE_NONE;
5520
5521         expected = (cdctl & BXT_CDCLK_CD2X_DIV_SEL_MASK) |
5522                    skl_cdclk_decimal(dev_priv->cdclk_freq);
5523         /*
5524          * Disable SSA Precharge when CD clock frequency < 500 MHz,
5525          * enable otherwise.
5526          */
5527         if (dev_priv->cdclk_freq >= 500000)
5528                 expected |= BXT_CDCLK_SSA_PRECHARGE_ENABLE;
5529
5530         if (cdctl == expected)
5531                 /* All well; nothing to sanitize */
5532                 return;
5533
5534 sanitize:
5535         DRM_DEBUG_KMS("Sanitizing cdclk programmed by pre-os\n");
5536
5537         /* force cdclk programming */
5538         dev_priv->cdclk_freq = 0;
5539
5540         /* force full PLL disable + enable */
5541         dev_priv->cdclk_pll.vco = -1;
5542 }
5543
5544 void broxton_init_cdclk(struct drm_i915_private *dev_priv)
5545 {
5546         bxt_sanitize_cdclk(dev_priv);
5547
5548         if (dev_priv->cdclk_freq != 0 && dev_priv->cdclk_pll.vco != 0)
5549                 return;
5550
5551         /*
5552          * FIXME:
5553          * - The initial CDCLK needs to be read from VBT.
5554          *   Need to make this change after VBT has changes for BXT.
5555          */
5556         broxton_set_cdclk(dev_priv, broxton_calc_cdclk(0));
5557 }
5558
5559 void broxton_uninit_cdclk(struct drm_i915_private *dev_priv)
5560 {
5561         broxton_set_cdclk(dev_priv, dev_priv->cdclk_pll.ref);
5562 }
5563
5564 static int skl_calc_cdclk(int max_pixclk, int vco)
5565 {
5566         if (vco == 8640000) {
5567                 if (max_pixclk > 540000)
5568                         return 617143;
5569                 else if (max_pixclk > 432000)
5570                         return 540000;
5571                 else if (max_pixclk > 308571)
5572                         return 432000;
5573                 else
5574                         return 308571;
5575         } else {
5576                 if (max_pixclk > 540000)
5577                         return 675000;
5578                 else if (max_pixclk > 450000)
5579                         return 540000;
5580                 else if (max_pixclk > 337500)
5581                         return 450000;
5582                 else
5583                         return 337500;
5584         }
5585 }
5586
5587 static void
5588 skl_dpll0_update(struct drm_i915_private *dev_priv)
5589 {
5590         u32 val;
5591
5592         dev_priv->cdclk_pll.ref = 24000;
5593         dev_priv->cdclk_pll.vco = 0;
5594
5595         val = I915_READ(LCPLL1_CTL);
5596         if ((val & LCPLL_PLL_ENABLE) == 0)
5597                 return;
5598
5599         if (WARN_ON((val & LCPLL_PLL_LOCK) == 0))
5600                 return;
5601
5602         val = I915_READ(DPLL_CTRL1);
5603
5604         if (WARN_ON((val & (DPLL_CTRL1_HDMI_MODE(SKL_DPLL0) |
5605                             DPLL_CTRL1_SSC(SKL_DPLL0) |
5606                             DPLL_CTRL1_OVERRIDE(SKL_DPLL0))) !=
5607                     DPLL_CTRL1_OVERRIDE(SKL_DPLL0)))
5608                 return;
5609
5610         switch (val & DPLL_CTRL1_LINK_RATE_MASK(SKL_DPLL0)) {
5611         case DPLL_CTRL1_LINK_RATE(DPLL_CTRL1_LINK_RATE_810, SKL_DPLL0):
5612         case DPLL_CTRL1_LINK_RATE(DPLL_CTRL1_LINK_RATE_1350, SKL_DPLL0):
5613         case DPLL_CTRL1_LINK_RATE(DPLL_CTRL1_LINK_RATE_1620, SKL_DPLL0):
5614         case DPLL_CTRL1_LINK_RATE(DPLL_CTRL1_LINK_RATE_2700, SKL_DPLL0):
5615                 dev_priv->cdclk_pll.vco = 8100000;
5616                 break;
5617         case DPLL_CTRL1_LINK_RATE(DPLL_CTRL1_LINK_RATE_1080, SKL_DPLL0):
5618         case DPLL_CTRL1_LINK_RATE(DPLL_CTRL1_LINK_RATE_2160, SKL_DPLL0):
5619                 dev_priv->cdclk_pll.vco = 8640000;
5620                 break;
5621         default:
5622                 MISSING_CASE(val & DPLL_CTRL1_LINK_RATE_MASK(SKL_DPLL0));
5623                 break;
5624         }
5625 }
5626
5627 void skl_set_preferred_cdclk_vco(struct drm_i915_private *dev_priv, int vco)
5628 {
5629         bool changed = dev_priv->skl_preferred_vco_freq != vco;
5630
5631         dev_priv->skl_preferred_vco_freq = vco;
5632
5633         if (changed)
5634                 intel_update_max_cdclk(dev_priv->dev);
5635 }
5636
5637 static void
5638 skl_dpll0_enable(struct drm_i915_private *dev_priv, int vco)
5639 {
5640         int min_cdclk = skl_calc_cdclk(0, vco);
5641         u32 val;
5642
5643         WARN_ON(vco != 8100000 && vco != 8640000);
5644
5645         /* select the minimum CDCLK before enabling DPLL 0 */
5646         val = CDCLK_FREQ_337_308 | skl_cdclk_decimal(min_cdclk);
5647         I915_WRITE(CDCLK_CTL, val);
5648         POSTING_READ(CDCLK_CTL);
5649
5650         /*
5651          * We always enable DPLL0 with the lowest link rate possible, but still
5652          * taking into account the VCO required to operate the eDP panel at the
5653          * desired frequency. The usual DP link rates operate with a VCO of
5654          * 8100 while the eDP 1.4 alternate link rates need a VCO of 8640.
5655          * The modeset code is responsible for the selection of the exact link
5656          * rate later on, with the constraint of choosing a frequency that
5657          * works with vco.
5658          */
5659         val = I915_READ(DPLL_CTRL1);
5660
5661         val &= ~(DPLL_CTRL1_HDMI_MODE(SKL_DPLL0) | DPLL_CTRL1_SSC(SKL_DPLL0) |
5662                  DPLL_CTRL1_LINK_RATE_MASK(SKL_DPLL0));
5663         val |= DPLL_CTRL1_OVERRIDE(SKL_DPLL0);
5664         if (vco == 8640000)
5665                 val |= DPLL_CTRL1_LINK_RATE(DPLL_CTRL1_LINK_RATE_1080,
5666                                             SKL_DPLL0);
5667         else
5668                 val |= DPLL_CTRL1_LINK_RATE(DPLL_CTRL1_LINK_RATE_810,
5669                                             SKL_DPLL0);
5670
5671         I915_WRITE(DPLL_CTRL1, val);
5672         POSTING_READ(DPLL_CTRL1);
5673
5674         I915_WRITE(LCPLL1_CTL, I915_READ(LCPLL1_CTL) | LCPLL_PLL_ENABLE);
5675
5676         if (wait_for(I915_READ(LCPLL1_CTL) & LCPLL_PLL_LOCK, 5))
5677                 DRM_ERROR("DPLL0 not locked\n");
5678
5679         dev_priv->cdclk_pll.vco = vco;
5680
5681         /* We'll want to keep using the current vco from now on. */
5682         skl_set_preferred_cdclk_vco(dev_priv, vco);
5683 }
5684
5685 static void
5686 skl_dpll0_disable(struct drm_i915_private *dev_priv)
5687 {
5688         I915_WRITE(LCPLL1_CTL, I915_READ(LCPLL1_CTL) & ~LCPLL_PLL_ENABLE);
5689         if (wait_for(!(I915_READ(LCPLL1_CTL) & LCPLL_PLL_LOCK), 1))
5690                 DRM_ERROR("Couldn't disable DPLL0\n");
5691
5692         dev_priv->cdclk_pll.vco = 0;
5693 }
5694
5695 static bool skl_cdclk_pcu_ready(struct drm_i915_private *dev_priv)
5696 {
5697         int ret;
5698         u32 val;
5699
5700         /* inform PCU we want to change CDCLK */
5701         val = SKL_CDCLK_PREPARE_FOR_CHANGE;
5702         mutex_lock(&dev_priv->rps.hw_lock);
5703         ret = sandybridge_pcode_read(dev_priv, SKL_PCODE_CDCLK_CONTROL, &val);
5704         mutex_unlock(&dev_priv->rps.hw_lock);
5705
5706         return ret == 0 && (val & SKL_CDCLK_READY_FOR_CHANGE);
5707 }
5708
5709 static bool skl_cdclk_wait_for_pcu_ready(struct drm_i915_private *dev_priv)
5710 {
5711         unsigned int i;
5712
5713         for (i = 0; i < 15; i++) {
5714                 if (skl_cdclk_pcu_ready(dev_priv))
5715                         return true;
5716                 udelay(10);
5717         }
5718
5719         return false;
5720 }
5721
5722 static void skl_set_cdclk(struct drm_i915_private *dev_priv, int cdclk, int vco)
5723 {
5724         struct drm_device *dev = dev_priv->dev;
5725         u32 freq_select, pcu_ack;
5726
5727         WARN_ON((cdclk == 24000) != (vco == 0));
5728
5729         DRM_DEBUG_DRIVER("Changing CDCLK to %d kHz (VCO %d kHz)\n", cdclk, vco);
5730
5731         if (!skl_cdclk_wait_for_pcu_ready(dev_priv)) {
5732                 DRM_ERROR("failed to inform PCU about cdclk change\n");
5733                 return;
5734         }
5735
5736         /* set CDCLK_CTL */
5737         switch (cdclk) {
5738         case 450000:
5739         case 432000:
5740                 freq_select = CDCLK_FREQ_450_432;
5741                 pcu_ack = 1;
5742                 break;
5743         case 540000:
5744                 freq_select = CDCLK_FREQ_540;
5745                 pcu_ack = 2;
5746                 break;
5747         case 308571:
5748         case 337500:
5749         default:
5750                 freq_select = CDCLK_FREQ_337_308;
5751                 pcu_ack = 0;
5752                 break;
5753         case 617143:
5754         case 675000:
5755                 freq_select = CDCLK_FREQ_675_617;
5756                 pcu_ack = 3;
5757                 break;
5758         }
5759
5760         if (dev_priv->cdclk_pll.vco != 0 &&
5761             dev_priv->cdclk_pll.vco != vco)
5762                 skl_dpll0_disable(dev_priv);
5763
5764         if (dev_priv->cdclk_pll.vco != vco)
5765                 skl_dpll0_enable(dev_priv, vco);
5766
5767         I915_WRITE(CDCLK_CTL, freq_select | skl_cdclk_decimal(cdclk));
5768         POSTING_READ(CDCLK_CTL);
5769
5770         /* inform PCU of the change */
5771         mutex_lock(&dev_priv->rps.hw_lock);
5772         sandybridge_pcode_write(dev_priv, SKL_PCODE_CDCLK_CONTROL, pcu_ack);
5773         mutex_unlock(&dev_priv->rps.hw_lock);
5774
5775         intel_update_cdclk(dev);
5776 }
5777
5778 static void skl_sanitize_cdclk(struct drm_i915_private *dev_priv);
5779
5780 void skl_uninit_cdclk(struct drm_i915_private *dev_priv)
5781 {
5782         skl_set_cdclk(dev_priv, dev_priv->cdclk_pll.ref, 0);
5783 }
5784
5785 void skl_init_cdclk(struct drm_i915_private *dev_priv)
5786 {
5787         int cdclk, vco;
5788
5789         skl_sanitize_cdclk(dev_priv);
5790
5791         if (dev_priv->cdclk_freq != 0 && dev_priv->cdclk_pll.vco != 0) {
5792                 /*
5793                  * Use the current vco as our initial
5794                  * guess as to what the preferred vco is.
5795                  */
5796                 if (dev_priv->skl_preferred_vco_freq == 0)
5797                         skl_set_preferred_cdclk_vco(dev_priv,
5798                                                     dev_priv->cdclk_pll.vco);
5799                 return;
5800         }
5801
5802         vco = dev_priv->skl_preferred_vco_freq;
5803         if (vco == 0)
5804                 vco = 8100000;
5805         cdclk = skl_calc_cdclk(0, vco);
5806
5807         skl_set_cdclk(dev_priv, cdclk, vco);
5808 }
5809
5810 static void skl_sanitize_cdclk(struct drm_i915_private *dev_priv)
5811 {
5812         uint32_t cdctl, expected;
5813
5814         /*
5815          * check if the pre-os intialized the display
5816          * There is SWF18 scratchpad register defined which is set by the
5817          * pre-os which can be used by the OS drivers to check the status
5818          */
5819         if ((I915_READ(SWF_ILK(0x18)) & 0x00FFFFFF) == 0)
5820                 goto sanitize;
5821
5822         intel_update_cdclk(dev_priv->dev);
5823         /* Is PLL enabled and locked ? */
5824         if (dev_priv->cdclk_pll.vco == 0 ||
5825             dev_priv->cdclk_freq == dev_priv->cdclk_pll.ref)
5826                 goto sanitize;
5827
5828         /* DPLL okay; verify the cdclock
5829          *
5830          * Noticed in some instances that the freq selection is correct but
5831          * decimal part is programmed wrong from BIOS where pre-os does not
5832          * enable display. Verify the same as well.
5833          */
5834         cdctl = I915_READ(CDCLK_CTL);
5835         expected = (cdctl & CDCLK_FREQ_SEL_MASK) |
5836                 skl_cdclk_decimal(dev_priv->cdclk_freq);
5837         if (cdctl == expected)
5838                 /* All well; nothing to sanitize */
5839                 return;
5840
5841 sanitize:
5842         DRM_DEBUG_KMS("Sanitizing cdclk programmed by pre-os\n");
5843
5844         /* force cdclk programming */
5845         dev_priv->cdclk_freq = 0;
5846         /* force full PLL disable + enable */
5847         dev_priv->cdclk_pll.vco = -1;
5848 }
5849
5850 /* Adjust CDclk dividers to allow high res or save power if possible */
5851 static void valleyview_set_cdclk(struct drm_device *dev, int cdclk)
5852 {
5853         struct drm_i915_private *dev_priv = dev->dev_private;
5854         u32 val, cmd;
5855
5856         WARN_ON(dev_priv->display.get_display_clock_speed(dev)
5857                                         != dev_priv->cdclk_freq);
5858
5859         if (cdclk >= 320000) /* jump to highest voltage for 400MHz too */
5860                 cmd = 2;
5861         else if (cdclk == 266667)
5862                 cmd = 1;
5863         else
5864                 cmd = 0;
5865
5866         mutex_lock(&dev_priv->rps.hw_lock);
5867         val = vlv_punit_read(dev_priv, PUNIT_REG_DSPFREQ);
5868         val &= ~DSPFREQGUAR_MASK;
5869         val |= (cmd << DSPFREQGUAR_SHIFT);
5870         vlv_punit_write(dev_priv, PUNIT_REG_DSPFREQ, val);
5871         if (wait_for((vlv_punit_read(dev_priv, PUNIT_REG_DSPFREQ) &
5872                       DSPFREQSTAT_MASK) == (cmd << DSPFREQSTAT_SHIFT),
5873                      50)) {
5874                 DRM_ERROR("timed out waiting for CDclk change\n");
5875         }
5876         mutex_unlock(&dev_priv->rps.hw_lock);
5877
5878         mutex_lock(&dev_priv->sb_lock);
5879
5880         if (cdclk == 400000) {
5881                 u32 divider;
5882
5883                 divider = DIV_ROUND_CLOSEST(dev_priv->hpll_freq << 1, cdclk) - 1;
5884
5885                 /* adjust cdclk divider */
5886                 val = vlv_cck_read(dev_priv, CCK_DISPLAY_CLOCK_CONTROL);
5887                 val &= ~CCK_FREQUENCY_VALUES;
5888                 val |= divider;
5889                 vlv_cck_write(dev_priv, CCK_DISPLAY_CLOCK_CONTROL, val);
5890
5891                 if (wait_for((vlv_cck_read(dev_priv, CCK_DISPLAY_CLOCK_CONTROL) &
5892                               CCK_FREQUENCY_STATUS) == (divider << CCK_FREQUENCY_STATUS_SHIFT),
5893                              50))
5894                         DRM_ERROR("timed out waiting for CDclk change\n");
5895         }
5896
5897         /* adjust self-refresh exit latency value */
5898         val = vlv_bunit_read(dev_priv, BUNIT_REG_BISOC);
5899         val &= ~0x7f;
5900
5901         /*
5902          * For high bandwidth configs, we set a higher latency in the bunit
5903          * so that the core display fetch happens in time to avoid underruns.
5904          */
5905         if (cdclk == 400000)
5906                 val |= 4500 / 250; /* 4.5 usec */
5907         else
5908                 val |= 3000 / 250; /* 3.0 usec */
5909         vlv_bunit_write(dev_priv, BUNIT_REG_BISOC, val);
5910
5911         mutex_unlock(&dev_priv->sb_lock);
5912
5913         intel_update_cdclk(dev);
5914 }
5915
5916 static void cherryview_set_cdclk(struct drm_device *dev, int cdclk)
5917 {
5918         struct drm_i915_private *dev_priv = dev->dev_private;
5919         u32 val, cmd;
5920
5921         WARN_ON(dev_priv->display.get_display_clock_speed(dev)
5922                                                 != dev_priv->cdclk_freq);
5923
5924         switch (cdclk) {
5925         case 333333:
5926         case 320000:
5927         case 266667:
5928         case 200000:
5929                 break;
5930         default:
5931                 MISSING_CASE(cdclk);
5932                 return;
5933         }
5934
5935         /*
5936          * Specs are full of misinformation, but testing on actual
5937          * hardware has shown that we just need to write the desired
5938          * CCK divider into the Punit register.
5939          */
5940         cmd = DIV_ROUND_CLOSEST(dev_priv->hpll_freq << 1, cdclk) - 1;
5941
5942         mutex_lock(&dev_priv->rps.hw_lock);
5943         val = vlv_punit_read(dev_priv, PUNIT_REG_DSPFREQ);
5944         val &= ~DSPFREQGUAR_MASK_CHV;
5945         val |= (cmd << DSPFREQGUAR_SHIFT_CHV);
5946         vlv_punit_write(dev_priv, PUNIT_REG_DSPFREQ, val);
5947         if (wait_for((vlv_punit_read(dev_priv, PUNIT_REG_DSPFREQ) &
5948                       DSPFREQSTAT_MASK_CHV) == (cmd << DSPFREQSTAT_SHIFT_CHV),
5949                      50)) {
5950                 DRM_ERROR("timed out waiting for CDclk change\n");
5951         }
5952         mutex_unlock(&dev_priv->rps.hw_lock);
5953
5954         intel_update_cdclk(dev);
5955 }
5956
5957 static int valleyview_calc_cdclk(struct drm_i915_private *dev_priv,
5958                                  int max_pixclk)
5959 {
5960         int freq_320 = (dev_priv->hpll_freq <<  1) % 320000 != 0 ? 333333 : 320000;
5961         int limit = IS_CHERRYVIEW(dev_priv) ? 95 : 90;
5962
5963         /*
5964          * Really only a few cases to deal with, as only 4 CDclks are supported:
5965          *   200MHz
5966          *   267MHz
5967          *   320/333MHz (depends on HPLL freq)
5968          *   400MHz (VLV only)
5969          * So we check to see whether we're above 90% (VLV) or 95% (CHV)
5970          * of the lower bin and adjust if needed.
5971          *
5972          * We seem to get an unstable or solid color picture at 200MHz.
5973          * Not sure what's wrong. For now use 200MHz only when all pipes
5974          * are off.
5975          */
5976         if (!IS_CHERRYVIEW(dev_priv) &&
5977             max_pixclk > freq_320*limit/100)
5978                 return 400000;
5979         else if (max_pixclk > 266667*limit/100)
5980                 return freq_320;
5981         else if (max_pixclk > 0)
5982                 return 266667;
5983         else
5984                 return 200000;
5985 }
5986
5987 static int broxton_calc_cdclk(int max_pixclk)
5988 {
5989         if (max_pixclk > 576000)
5990                 return 624000;
5991         else if (max_pixclk > 384000)
5992                 return 576000;
5993         else if (max_pixclk > 288000)
5994                 return 384000;
5995         else if (max_pixclk > 144000)
5996                 return 288000;
5997         else
5998                 return 144000;
5999 }
6000
6001 /* Compute the max pixel clock for new configuration. */
6002 static int intel_mode_max_pixclk(struct drm_device *dev,
6003                                  struct drm_atomic_state *state)
6004 {
6005         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
6006         struct drm_i915_private *dev_priv = dev->dev_private;
6007         struct drm_crtc *crtc;
6008         struct drm_crtc_state *crtc_state;
6009         unsigned max_pixclk = 0, i;
6010         enum pipe pipe;
6011
6012         memcpy(intel_state->min_pixclk, dev_priv->min_pixclk,
6013                sizeof(intel_state->min_pixclk));
6014
6015         for_each_crtc_in_state(state, crtc, crtc_state, i) {
6016                 int pixclk = 0;
6017
6018                 if (crtc_state->enable)
6019                         pixclk = crtc_state->adjusted_mode.crtc_clock;
6020
6021                 intel_state->min_pixclk[i] = pixclk;
6022         }
6023
6024         for_each_pipe(dev_priv, pipe)
6025                 max_pixclk = max(intel_state->min_pixclk[pipe], max_pixclk);
6026
6027         return max_pixclk;
6028 }
6029
6030 static int valleyview_modeset_calc_cdclk(struct drm_atomic_state *state)
6031 {
6032         struct drm_device *dev = state->dev;
6033         struct drm_i915_private *dev_priv = dev->dev_private;
6034         int max_pixclk = intel_mode_max_pixclk(dev, state);
6035         struct intel_atomic_state *intel_state =
6036                 to_intel_atomic_state(state);
6037
6038         intel_state->cdclk = intel_state->dev_cdclk =
6039                 valleyview_calc_cdclk(dev_priv, max_pixclk);
6040
6041         if (!intel_state->active_crtcs)
6042                 intel_state->dev_cdclk = valleyview_calc_cdclk(dev_priv, 0);
6043
6044         return 0;
6045 }
6046
6047 static int broxton_modeset_calc_cdclk(struct drm_atomic_state *state)
6048 {
6049         int max_pixclk = ilk_max_pixel_rate(state);
6050         struct intel_atomic_state *intel_state =
6051                 to_intel_atomic_state(state);
6052
6053         intel_state->cdclk = intel_state->dev_cdclk =
6054                 broxton_calc_cdclk(max_pixclk);
6055
6056         if (!intel_state->active_crtcs)
6057                 intel_state->dev_cdclk = broxton_calc_cdclk(0);
6058
6059         return 0;
6060 }
6061
6062 static void vlv_program_pfi_credits(struct drm_i915_private *dev_priv)
6063 {
6064         unsigned int credits, default_credits;
6065
6066         if (IS_CHERRYVIEW(dev_priv))
6067                 default_credits = PFI_CREDIT(12);
6068         else
6069                 default_credits = PFI_CREDIT(8);
6070
6071         if (dev_priv->cdclk_freq >= dev_priv->czclk_freq) {
6072                 /* CHV suggested value is 31 or 63 */
6073                 if (IS_CHERRYVIEW(dev_priv))
6074                         credits = PFI_CREDIT_63;
6075                 else
6076                         credits = PFI_CREDIT(15);
6077         } else {
6078                 credits = default_credits;
6079         }
6080
6081         /*
6082          * WA - write default credits before re-programming
6083          * FIXME: should we also set the resend bit here?
6084          */
6085         I915_WRITE(GCI_CONTROL, VGA_FAST_MODE_DISABLE |
6086                    default_credits);
6087
6088         I915_WRITE(GCI_CONTROL, VGA_FAST_MODE_DISABLE |
6089                    credits | PFI_CREDIT_RESEND);
6090
6091         /*
6092          * FIXME is this guaranteed to clear
6093          * immediately or should we poll for it?
6094          */
6095         WARN_ON(I915_READ(GCI_CONTROL) & PFI_CREDIT_RESEND);
6096 }
6097
6098 static void valleyview_modeset_commit_cdclk(struct drm_atomic_state *old_state)
6099 {
6100         struct drm_device *dev = old_state->dev;
6101         struct drm_i915_private *dev_priv = dev->dev_private;
6102         struct intel_atomic_state *old_intel_state =
6103                 to_intel_atomic_state(old_state);
6104         unsigned req_cdclk = old_intel_state->dev_cdclk;
6105
6106         /*
6107          * FIXME: We can end up here with all power domains off, yet
6108          * with a CDCLK frequency other than the minimum. To account
6109          * for this take the PIPE-A power domain, which covers the HW
6110          * blocks needed for the following programming. This can be
6111          * removed once it's guaranteed that we get here either with
6112          * the minimum CDCLK set, or the required power domains
6113          * enabled.
6114          */
6115         intel_display_power_get(dev_priv, POWER_DOMAIN_PIPE_A);
6116
6117         if (IS_CHERRYVIEW(dev))
6118                 cherryview_set_cdclk(dev, req_cdclk);
6119         else
6120                 valleyview_set_cdclk(dev, req_cdclk);
6121
6122         vlv_program_pfi_credits(dev_priv);
6123
6124         intel_display_power_put(dev_priv, POWER_DOMAIN_PIPE_A);
6125 }
6126
6127 static void valleyview_crtc_enable(struct drm_crtc *crtc)
6128 {
6129         struct drm_device *dev = crtc->dev;
6130         struct drm_i915_private *dev_priv = to_i915(dev);
6131         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
6132         struct intel_encoder *encoder;
6133         struct intel_crtc_state *pipe_config =
6134                 to_intel_crtc_state(crtc->state);
6135         int pipe = intel_crtc->pipe;
6136
6137         if (WARN_ON(intel_crtc->active))
6138                 return;
6139
6140         if (intel_crtc->config->has_dp_encoder)
6141                 intel_dp_set_m_n(intel_crtc, M1_N1);
6142
6143         intel_set_pipe_timings(intel_crtc);
6144         intel_set_pipe_src_size(intel_crtc);
6145
6146         if (IS_CHERRYVIEW(dev) && pipe == PIPE_B) {
6147                 struct drm_i915_private *dev_priv = dev->dev_private;
6148
6149                 I915_WRITE(CHV_BLEND(pipe), CHV_BLEND_LEGACY);
6150                 I915_WRITE(CHV_CANVAS(pipe), 0);
6151         }
6152
6153         i9xx_set_pipeconf(intel_crtc);
6154
6155         intel_crtc->active = true;
6156
6157         intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
6158
6159         for_each_encoder_on_crtc(dev, crtc, encoder)
6160                 if (encoder->pre_pll_enable)
6161                         encoder->pre_pll_enable(encoder);
6162
6163         if (IS_CHERRYVIEW(dev)) {
6164                 chv_prepare_pll(intel_crtc, intel_crtc->config);
6165                 chv_enable_pll(intel_crtc, intel_crtc->config);
6166         } else {
6167                 vlv_prepare_pll(intel_crtc, intel_crtc->config);
6168                 vlv_enable_pll(intel_crtc, intel_crtc->config);
6169         }
6170
6171         for_each_encoder_on_crtc(dev, crtc, encoder)
6172                 if (encoder->pre_enable)
6173                         encoder->pre_enable(encoder);
6174
6175         i9xx_pfit_enable(intel_crtc);
6176
6177         intel_color_load_luts(&pipe_config->base);
6178
6179         intel_update_watermarks(crtc);
6180         intel_enable_pipe(intel_crtc);
6181
6182         assert_vblank_disabled(crtc);
6183         drm_crtc_vblank_on(crtc);
6184
6185         for_each_encoder_on_crtc(dev, crtc, encoder)
6186                 encoder->enable(encoder);
6187 }
6188
6189 static void i9xx_set_pll_dividers(struct intel_crtc *crtc)
6190 {
6191         struct drm_device *dev = crtc->base.dev;
6192         struct drm_i915_private *dev_priv = dev->dev_private;
6193
6194         I915_WRITE(FP0(crtc->pipe), crtc->config->dpll_hw_state.fp0);
6195         I915_WRITE(FP1(crtc->pipe), crtc->config->dpll_hw_state.fp1);
6196 }
6197
6198 static void i9xx_crtc_enable(struct drm_crtc *crtc)
6199 {
6200         struct drm_device *dev = crtc->dev;
6201         struct drm_i915_private *dev_priv = to_i915(dev);
6202         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
6203         struct intel_encoder *encoder;
6204         struct intel_crtc_state *pipe_config =
6205                 to_intel_crtc_state(crtc->state);
6206         enum pipe pipe = intel_crtc->pipe;
6207
6208         if (WARN_ON(intel_crtc->active))
6209                 return;
6210
6211         i9xx_set_pll_dividers(intel_crtc);
6212
6213         if (intel_crtc->config->has_dp_encoder)
6214                 intel_dp_set_m_n(intel_crtc, M1_N1);
6215
6216         intel_set_pipe_timings(intel_crtc);
6217         intel_set_pipe_src_size(intel_crtc);
6218
6219         i9xx_set_pipeconf(intel_crtc);
6220
6221         intel_crtc->active = true;
6222
6223         if (!IS_GEN2(dev))
6224                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
6225
6226         for_each_encoder_on_crtc(dev, crtc, encoder)
6227                 if (encoder->pre_enable)
6228                         encoder->pre_enable(encoder);
6229
6230         i9xx_enable_pll(intel_crtc);
6231
6232         i9xx_pfit_enable(intel_crtc);
6233
6234         intel_color_load_luts(&pipe_config->base);
6235
6236         intel_update_watermarks(crtc);
6237         intel_enable_pipe(intel_crtc);
6238
6239         assert_vblank_disabled(crtc);
6240         drm_crtc_vblank_on(crtc);
6241
6242         for_each_encoder_on_crtc(dev, crtc, encoder)
6243                 encoder->enable(encoder);
6244 }
6245
6246 static void i9xx_pfit_disable(struct intel_crtc *crtc)
6247 {
6248         struct drm_device *dev = crtc->base.dev;
6249         struct drm_i915_private *dev_priv = dev->dev_private;
6250
6251         if (!crtc->config->gmch_pfit.control)
6252                 return;
6253
6254         assert_pipe_disabled(dev_priv, crtc->pipe);
6255
6256         DRM_DEBUG_DRIVER("disabling pfit, current: 0x%08x\n",
6257                          I915_READ(PFIT_CONTROL));
6258         I915_WRITE(PFIT_CONTROL, 0);
6259 }
6260
6261 static void i9xx_crtc_disable(struct drm_crtc *crtc)
6262 {
6263         struct drm_device *dev = crtc->dev;
6264         struct drm_i915_private *dev_priv = dev->dev_private;
6265         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
6266         struct intel_encoder *encoder;
6267         int pipe = intel_crtc->pipe;
6268
6269         /*
6270          * On gen2 planes are double buffered but the pipe isn't, so we must
6271          * wait for planes to fully turn off before disabling the pipe.
6272          */
6273         if (IS_GEN2(dev))
6274                 intel_wait_for_vblank(dev, pipe);
6275
6276         for_each_encoder_on_crtc(dev, crtc, encoder)
6277                 encoder->disable(encoder);
6278
6279         drm_crtc_vblank_off(crtc);
6280         assert_vblank_disabled(crtc);
6281
6282         intel_disable_pipe(intel_crtc);
6283
6284         i9xx_pfit_disable(intel_crtc);
6285
6286         for_each_encoder_on_crtc(dev, crtc, encoder)
6287                 if (encoder->post_disable)
6288                         encoder->post_disable(encoder);
6289
6290         if (!intel_crtc->config->has_dsi_encoder) {
6291                 if (IS_CHERRYVIEW(dev))
6292                         chv_disable_pll(dev_priv, pipe);
6293                 else if (IS_VALLEYVIEW(dev))
6294                         vlv_disable_pll(dev_priv, pipe);
6295                 else
6296                         i9xx_disable_pll(intel_crtc);
6297         }
6298
6299         for_each_encoder_on_crtc(dev, crtc, encoder)
6300                 if (encoder->post_pll_disable)
6301                         encoder->post_pll_disable(encoder);
6302
6303         if (!IS_GEN2(dev))
6304                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, false);
6305 }
6306
6307 static void intel_crtc_disable_noatomic(struct drm_crtc *crtc)
6308 {
6309         struct intel_encoder *encoder;
6310         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
6311         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
6312         enum intel_display_power_domain domain;
6313         unsigned long domains;
6314
6315         if (!intel_crtc->active)
6316                 return;
6317
6318         if (to_intel_plane_state(crtc->primary->state)->visible) {
6319                 WARN_ON(intel_crtc->flip_work);
6320
6321                 intel_pre_disable_primary_noatomic(crtc);
6322
6323                 intel_crtc_disable_planes(crtc, 1 << drm_plane_index(crtc->primary));
6324                 to_intel_plane_state(crtc->primary->state)->visible = false;
6325         }
6326
6327         dev_priv->display.crtc_disable(crtc);
6328
6329         DRM_DEBUG_KMS("[CRTC:%d:%s] hw state adjusted, was enabled, now disabled\n",
6330                       crtc->base.id, crtc->name);
6331
6332         WARN_ON(drm_atomic_set_mode_for_crtc(crtc->state, NULL) < 0);
6333         crtc->state->active = false;
6334         intel_crtc->active = false;
6335         crtc->enabled = false;
6336         crtc->state->connector_mask = 0;
6337         crtc->state->encoder_mask = 0;
6338
6339         for_each_encoder_on_crtc(crtc->dev, crtc, encoder)
6340                 encoder->base.crtc = NULL;
6341
6342         intel_fbc_disable(intel_crtc);
6343         intel_update_watermarks(crtc);
6344         intel_disable_shared_dpll(intel_crtc);
6345
6346         domains = intel_crtc->enabled_power_domains;
6347         for_each_power_domain(domain, domains)
6348                 intel_display_power_put(dev_priv, domain);
6349         intel_crtc->enabled_power_domains = 0;
6350
6351         dev_priv->active_crtcs &= ~(1 << intel_crtc->pipe);
6352         dev_priv->min_pixclk[intel_crtc->pipe] = 0;
6353 }
6354
6355 /*
6356  * turn all crtc's off, but do not adjust state
6357  * This has to be paired with a call to intel_modeset_setup_hw_state.
6358  */
6359 int intel_display_suspend(struct drm_device *dev)
6360 {
6361         struct drm_i915_private *dev_priv = to_i915(dev);
6362         struct drm_atomic_state *state;
6363         int ret;
6364
6365         state = drm_atomic_helper_suspend(dev);
6366         ret = PTR_ERR_OR_ZERO(state);
6367         if (ret)
6368                 DRM_ERROR("Suspending crtc's failed with %i\n", ret);
6369         else
6370                 dev_priv->modeset_restore_state = state;
6371         return ret;
6372 }
6373
6374 void intel_encoder_destroy(struct drm_encoder *encoder)
6375 {
6376         struct intel_encoder *intel_encoder = to_intel_encoder(encoder);
6377
6378         drm_encoder_cleanup(encoder);
6379         kfree(intel_encoder);
6380 }
6381
6382 /* Cross check the actual hw state with our own modeset state tracking (and it's
6383  * internal consistency). */
6384 static void intel_connector_verify_state(struct intel_connector *connector)
6385 {
6386         struct drm_crtc *crtc = connector->base.state->crtc;
6387
6388         DRM_DEBUG_KMS("[CONNECTOR:%d:%s]\n",
6389                       connector->base.base.id,
6390                       connector->base.name);
6391
6392         if (connector->get_hw_state(connector)) {
6393                 struct intel_encoder *encoder = connector->encoder;
6394                 struct drm_connector_state *conn_state = connector->base.state;
6395
6396                 I915_STATE_WARN(!crtc,
6397                          "connector enabled without attached crtc\n");
6398
6399                 if (!crtc)
6400                         return;
6401
6402                 I915_STATE_WARN(!crtc->state->active,
6403                       "connector is active, but attached crtc isn't\n");
6404
6405                 if (!encoder || encoder->type == INTEL_OUTPUT_DP_MST)
6406                         return;
6407
6408                 I915_STATE_WARN(conn_state->best_encoder != &encoder->base,
6409                         "atomic encoder doesn't match attached encoder\n");
6410
6411                 I915_STATE_WARN(conn_state->crtc != encoder->base.crtc,
6412                         "attached encoder crtc differs from connector crtc\n");
6413         } else {
6414                 I915_STATE_WARN(crtc && crtc->state->active,
6415                         "attached crtc is active, but connector isn't\n");
6416                 I915_STATE_WARN(!crtc && connector->base.state->best_encoder,
6417                         "best encoder set without crtc!\n");
6418         }
6419 }
6420
6421 int intel_connector_init(struct intel_connector *connector)
6422 {
6423         drm_atomic_helper_connector_reset(&connector->base);
6424
6425         if (!connector->base.state)
6426                 return -ENOMEM;
6427
6428         return 0;
6429 }
6430
6431 struct intel_connector *intel_connector_alloc(void)
6432 {
6433         struct intel_connector *connector;
6434
6435         connector = kzalloc(sizeof *connector, GFP_KERNEL);
6436         if (!connector)
6437                 return NULL;
6438
6439         if (intel_connector_init(connector) < 0) {
6440                 kfree(connector);
6441                 return NULL;
6442         }
6443
6444         return connector;
6445 }
6446
6447 /* Simple connector->get_hw_state implementation for encoders that support only
6448  * one connector and no cloning and hence the encoder state determines the state
6449  * of the connector. */
6450 bool intel_connector_get_hw_state(struct intel_connector *connector)
6451 {
6452         enum pipe pipe = 0;
6453         struct intel_encoder *encoder = connector->encoder;
6454
6455         return encoder->get_hw_state(encoder, &pipe);
6456 }
6457
6458 static int pipe_required_fdi_lanes(struct intel_crtc_state *crtc_state)
6459 {
6460         if (crtc_state->base.enable && crtc_state->has_pch_encoder)
6461                 return crtc_state->fdi_lanes;
6462
6463         return 0;
6464 }
6465
6466 static int ironlake_check_fdi_lanes(struct drm_device *dev, enum pipe pipe,
6467                                      struct intel_crtc_state *pipe_config)
6468 {
6469         struct drm_atomic_state *state = pipe_config->base.state;
6470         struct intel_crtc *other_crtc;
6471         struct intel_crtc_state *other_crtc_state;
6472
6473         DRM_DEBUG_KMS("checking fdi config on pipe %c, lanes %i\n",
6474                       pipe_name(pipe), pipe_config->fdi_lanes);
6475         if (pipe_config->fdi_lanes > 4) {
6476                 DRM_DEBUG_KMS("invalid fdi lane config on pipe %c: %i lanes\n",
6477                               pipe_name(pipe), pipe_config->fdi_lanes);
6478                 return -EINVAL;
6479         }
6480
6481         if (IS_HASWELL(dev) || IS_BROADWELL(dev)) {
6482                 if (pipe_config->fdi_lanes > 2) {
6483                         DRM_DEBUG_KMS("only 2 lanes on haswell, required: %i lanes\n",
6484                                       pipe_config->fdi_lanes);
6485                         return -EINVAL;
6486                 } else {
6487                         return 0;
6488                 }
6489         }
6490
6491         if (INTEL_INFO(dev)->num_pipes == 2)
6492                 return 0;
6493
6494         /* Ivybridge 3 pipe is really complicated */
6495         switch (pipe) {
6496         case PIPE_A:
6497                 return 0;
6498         case PIPE_B:
6499                 if (pipe_config->fdi_lanes <= 2)
6500                         return 0;
6501
6502                 other_crtc = to_intel_crtc(intel_get_crtc_for_pipe(dev, PIPE_C));
6503                 other_crtc_state =
6504                         intel_atomic_get_crtc_state(state, other_crtc);
6505                 if (IS_ERR(other_crtc_state))
6506                         return PTR_ERR(other_crtc_state);
6507
6508                 if (pipe_required_fdi_lanes(other_crtc_state) > 0) {
6509                         DRM_DEBUG_KMS("invalid shared fdi lane config on pipe %c: %i lanes\n",
6510                                       pipe_name(pipe), pipe_config->fdi_lanes);
6511                         return -EINVAL;
6512                 }
6513                 return 0;
6514         case PIPE_C:
6515                 if (pipe_config->fdi_lanes > 2) {
6516                         DRM_DEBUG_KMS("only 2 lanes on pipe %c: required %i lanes\n",
6517                                       pipe_name(pipe), pipe_config->fdi_lanes);
6518                         return -EINVAL;
6519                 }
6520
6521                 other_crtc = to_intel_crtc(intel_get_crtc_for_pipe(dev, PIPE_B));
6522                 other_crtc_state =
6523                         intel_atomic_get_crtc_state(state, other_crtc);
6524                 if (IS_ERR(other_crtc_state))
6525                         return PTR_ERR(other_crtc_state);
6526
6527                 if (pipe_required_fdi_lanes(other_crtc_state) > 2) {
6528                         DRM_DEBUG_KMS("fdi link B uses too many lanes to enable link C\n");
6529                         return -EINVAL;
6530                 }
6531                 return 0;
6532         default:
6533                 BUG();
6534         }
6535 }
6536
6537 #define RETRY 1
6538 static int ironlake_fdi_compute_config(struct intel_crtc *intel_crtc,
6539                                        struct intel_crtc_state *pipe_config)
6540 {
6541         struct drm_device *dev = intel_crtc->base.dev;
6542         const struct drm_display_mode *adjusted_mode = &pipe_config->base.adjusted_mode;
6543         int lane, link_bw, fdi_dotclock, ret;
6544         bool needs_recompute = false;
6545
6546 retry:
6547         /* FDI is a binary signal running at ~2.7GHz, encoding
6548          * each output octet as 10 bits. The actual frequency
6549          * is stored as a divider into a 100MHz clock, and the
6550          * mode pixel clock is stored in units of 1KHz.
6551          * Hence the bw of each lane in terms of the mode signal
6552          * is:
6553          */
6554         link_bw = intel_fdi_link_freq(to_i915(dev), pipe_config);
6555
6556         fdi_dotclock = adjusted_mode->crtc_clock;
6557
6558         lane = ironlake_get_lanes_required(fdi_dotclock, link_bw,
6559                                            pipe_config->pipe_bpp);
6560
6561         pipe_config->fdi_lanes = lane;
6562
6563         intel_link_compute_m_n(pipe_config->pipe_bpp, lane, fdi_dotclock,
6564                                link_bw, &pipe_config->fdi_m_n);
6565
6566         ret = ironlake_check_fdi_lanes(dev, intel_crtc->pipe, pipe_config);
6567         if (ret == -EINVAL && pipe_config->pipe_bpp > 6*3) {
6568                 pipe_config->pipe_bpp -= 2*3;
6569                 DRM_DEBUG_KMS("fdi link bw constraint, reducing pipe bpp to %i\n",
6570                               pipe_config->pipe_bpp);
6571                 needs_recompute = true;
6572                 pipe_config->bw_constrained = true;
6573
6574                 goto retry;
6575         }
6576
6577         if (needs_recompute)
6578                 return RETRY;
6579
6580         return ret;
6581 }
6582
6583 static bool pipe_config_supports_ips(struct drm_i915_private *dev_priv,
6584                                      struct intel_crtc_state *pipe_config)
6585 {
6586         if (pipe_config->pipe_bpp > 24)
6587                 return false;
6588
6589         /* HSW can handle pixel rate up to cdclk? */
6590         if (IS_HASWELL(dev_priv))
6591                 return true;
6592
6593         /*
6594          * We compare against max which means we must take
6595          * the increased cdclk requirement into account when
6596          * calculating the new cdclk.
6597          *
6598          * Should measure whether using a lower cdclk w/o IPS
6599          */
6600         return ilk_pipe_pixel_rate(pipe_config) <=
6601                 dev_priv->max_cdclk_freq * 95 / 100;
6602 }
6603
6604 static void hsw_compute_ips_config(struct intel_crtc *crtc,
6605                                    struct intel_crtc_state *pipe_config)
6606 {
6607         struct drm_device *dev = crtc->base.dev;
6608         struct drm_i915_private *dev_priv = dev->dev_private;
6609
6610         pipe_config->ips_enabled = i915.enable_ips &&
6611                 hsw_crtc_supports_ips(crtc) &&
6612                 pipe_config_supports_ips(dev_priv, pipe_config);
6613 }
6614
6615 static bool intel_crtc_supports_double_wide(const struct intel_crtc *crtc)
6616 {
6617         const struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
6618
6619         /* GDG double wide on either pipe, otherwise pipe A only */
6620         return INTEL_INFO(dev_priv)->gen < 4 &&
6621                 (crtc->pipe == PIPE_A || IS_I915G(dev_priv));
6622 }
6623
6624 static int intel_crtc_compute_config(struct intel_crtc *crtc,
6625                                      struct intel_crtc_state *pipe_config)
6626 {
6627         struct drm_device *dev = crtc->base.dev;
6628         struct drm_i915_private *dev_priv = dev->dev_private;
6629         const struct drm_display_mode *adjusted_mode = &pipe_config->base.adjusted_mode;
6630         int clock_limit = dev_priv->max_dotclk_freq;
6631
6632         if (INTEL_INFO(dev)->gen < 4) {
6633                 clock_limit = dev_priv->max_cdclk_freq * 9 / 10;
6634
6635                 /*
6636                  * Enable double wide mode when the dot clock
6637                  * is > 90% of the (display) core speed.
6638                  */
6639                 if (intel_crtc_supports_double_wide(crtc) &&
6640                     adjusted_mode->crtc_clock > clock_limit) {
6641                         clock_limit = dev_priv->max_dotclk_freq;
6642                         pipe_config->double_wide = true;
6643                 }
6644         }
6645
6646         if (adjusted_mode->crtc_clock > clock_limit) {
6647                 DRM_DEBUG_KMS("requested pixel clock (%d kHz) too high (max: %d kHz, double wide: %s)\n",
6648                               adjusted_mode->crtc_clock, clock_limit,
6649                               yesno(pipe_config->double_wide));
6650                 return -EINVAL;
6651         }
6652
6653         /*
6654          * Pipe horizontal size must be even in:
6655          * - DVO ganged mode
6656          * - LVDS dual channel mode
6657          * - Double wide pipe
6658          */
6659         if ((intel_pipe_will_have_type(pipe_config, INTEL_OUTPUT_LVDS) &&
6660              intel_is_dual_link_lvds(dev)) || pipe_config->double_wide)
6661                 pipe_config->pipe_src_w &= ~1;
6662
6663         /* Cantiga+ cannot handle modes with a hsync front porch of 0.
6664          * WaPruneModeWithIncorrectHsyncOffset:ctg,elk,ilk,snb,ivb,vlv,hsw.
6665          */
6666         if ((INTEL_INFO(dev)->gen > 4 || IS_G4X(dev)) &&
6667                 adjusted_mode->crtc_hsync_start == adjusted_mode->crtc_hdisplay)
6668                 return -EINVAL;
6669
6670         if (HAS_IPS(dev))
6671                 hsw_compute_ips_config(crtc, pipe_config);
6672
6673         if (pipe_config->has_pch_encoder)
6674                 return ironlake_fdi_compute_config(crtc, pipe_config);
6675
6676         return 0;
6677 }
6678
6679 static int skylake_get_display_clock_speed(struct drm_device *dev)
6680 {
6681         struct drm_i915_private *dev_priv = to_i915(dev);
6682         uint32_t cdctl;
6683
6684         skl_dpll0_update(dev_priv);
6685
6686         if (dev_priv->cdclk_pll.vco == 0)
6687                 return dev_priv->cdclk_pll.ref;
6688
6689         cdctl = I915_READ(CDCLK_CTL);
6690
6691         if (dev_priv->cdclk_pll.vco == 8640000) {
6692                 switch (cdctl & CDCLK_FREQ_SEL_MASK) {
6693                 case CDCLK_FREQ_450_432:
6694                         return 432000;
6695                 case CDCLK_FREQ_337_308:
6696                         return 308571;
6697                 case CDCLK_FREQ_540:
6698                         return 540000;
6699                 case CDCLK_FREQ_675_617:
6700                         return 617143;
6701                 default:
6702                         MISSING_CASE(cdctl & CDCLK_FREQ_SEL_MASK);
6703                 }
6704         } else {
6705                 switch (cdctl & CDCLK_FREQ_SEL_MASK) {
6706                 case CDCLK_FREQ_450_432:
6707                         return 450000;
6708                 case CDCLK_FREQ_337_308:
6709                         return 337500;
6710                 case CDCLK_FREQ_540:
6711                         return 540000;
6712                 case CDCLK_FREQ_675_617:
6713                         return 675000;
6714                 default:
6715                         MISSING_CASE(cdctl & CDCLK_FREQ_SEL_MASK);
6716                 }
6717         }
6718
6719         return dev_priv->cdclk_pll.ref;
6720 }
6721
6722 static void bxt_de_pll_update(struct drm_i915_private *dev_priv)
6723 {
6724         u32 val;
6725
6726         dev_priv->cdclk_pll.ref = 19200;
6727         dev_priv->cdclk_pll.vco = 0;
6728
6729         val = I915_READ(BXT_DE_PLL_ENABLE);
6730         if ((val & BXT_DE_PLL_PLL_ENABLE) == 0)
6731                 return;
6732
6733         if (WARN_ON((val & BXT_DE_PLL_LOCK) == 0))
6734                 return;
6735
6736         val = I915_READ(BXT_DE_PLL_CTL);
6737         dev_priv->cdclk_pll.vco = (val & BXT_DE_PLL_RATIO_MASK) *
6738                 dev_priv->cdclk_pll.ref;
6739 }
6740
6741 static int broxton_get_display_clock_speed(struct drm_device *dev)
6742 {
6743         struct drm_i915_private *dev_priv = to_i915(dev);
6744         u32 divider;
6745         int div, vco;
6746
6747         bxt_de_pll_update(dev_priv);
6748
6749         vco = dev_priv->cdclk_pll.vco;
6750         if (vco == 0)
6751                 return dev_priv->cdclk_pll.ref;
6752
6753         divider = I915_READ(CDCLK_CTL) & BXT_CDCLK_CD2X_DIV_SEL_MASK;
6754
6755         switch (divider) {
6756         case BXT_CDCLK_CD2X_DIV_SEL_1:
6757                 div = 2;
6758                 break;
6759         case BXT_CDCLK_CD2X_DIV_SEL_1_5:
6760                 div = 3;
6761                 break;
6762         case BXT_CDCLK_CD2X_DIV_SEL_2:
6763                 div = 4;
6764                 break;
6765         case BXT_CDCLK_CD2X_DIV_SEL_4:
6766                 div = 8;
6767                 break;
6768         default:
6769                 MISSING_CASE(divider);
6770                 return dev_priv->cdclk_pll.ref;
6771         }
6772
6773         return DIV_ROUND_CLOSEST(vco, div);
6774 }
6775
6776 static int broadwell_get_display_clock_speed(struct drm_device *dev)
6777 {
6778         struct drm_i915_private *dev_priv = dev->dev_private;
6779         uint32_t lcpll = I915_READ(LCPLL_CTL);
6780         uint32_t freq = lcpll & LCPLL_CLK_FREQ_MASK;
6781
6782         if (lcpll & LCPLL_CD_SOURCE_FCLK)
6783                 return 800000;
6784         else if (I915_READ(FUSE_STRAP) & HSW_CDCLK_LIMIT)
6785                 return 450000;
6786         else if (freq == LCPLL_CLK_FREQ_450)
6787                 return 450000;
6788         else if (freq == LCPLL_CLK_FREQ_54O_BDW)
6789                 return 540000;
6790         else if (freq == LCPLL_CLK_FREQ_337_5_BDW)
6791                 return 337500;
6792         else
6793                 return 675000;
6794 }
6795
6796 static int haswell_get_display_clock_speed(struct drm_device *dev)
6797 {
6798         struct drm_i915_private *dev_priv = dev->dev_private;
6799         uint32_t lcpll = I915_READ(LCPLL_CTL);
6800         uint32_t freq = lcpll & LCPLL_CLK_FREQ_MASK;
6801
6802         if (lcpll & LCPLL_CD_SOURCE_FCLK)
6803                 return 800000;
6804         else if (I915_READ(FUSE_STRAP) & HSW_CDCLK_LIMIT)
6805                 return 450000;
6806         else if (freq == LCPLL_CLK_FREQ_450)
6807                 return 450000;
6808         else if (IS_HSW_ULT(dev))
6809                 return 337500;
6810         else
6811                 return 540000;
6812 }
6813
6814 static int valleyview_get_display_clock_speed(struct drm_device *dev)
6815 {
6816         return vlv_get_cck_clock_hpll(to_i915(dev), "cdclk",
6817                                       CCK_DISPLAY_CLOCK_CONTROL);
6818 }
6819
6820 static int ilk_get_display_clock_speed(struct drm_device *dev)
6821 {
6822         return 450000;
6823 }
6824
6825 static int i945_get_display_clock_speed(struct drm_device *dev)
6826 {
6827         return 400000;
6828 }
6829
6830 static int i915_get_display_clock_speed(struct drm_device *dev)
6831 {
6832         return 333333;
6833 }
6834
6835 static int i9xx_misc_get_display_clock_speed(struct drm_device *dev)
6836 {
6837         return 200000;
6838 }
6839
6840 static int pnv_get_display_clock_speed(struct drm_device *dev)
6841 {
6842         u16 gcfgc = 0;
6843
6844         pci_read_config_word(dev->pdev, GCFGC, &gcfgc);
6845
6846         switch (gcfgc & GC_DISPLAY_CLOCK_MASK) {
6847         case GC_DISPLAY_CLOCK_267_MHZ_PNV:
6848                 return 266667;
6849         case GC_DISPLAY_CLOCK_333_MHZ_PNV:
6850                 return 333333;
6851         case GC_DISPLAY_CLOCK_444_MHZ_PNV:
6852                 return 444444;
6853         case GC_DISPLAY_CLOCK_200_MHZ_PNV:
6854                 return 200000;
6855         default:
6856                 DRM_ERROR("Unknown pnv display core clock 0x%04x\n", gcfgc);
6857         case GC_DISPLAY_CLOCK_133_MHZ_PNV:
6858                 return 133333;
6859         case GC_DISPLAY_CLOCK_167_MHZ_PNV:
6860                 return 166667;
6861         }
6862 }
6863
6864 static int i915gm_get_display_clock_speed(struct drm_device *dev)
6865 {
6866         u16 gcfgc = 0;
6867
6868         pci_read_config_word(dev->pdev, GCFGC, &gcfgc);
6869
6870         if (gcfgc & GC_LOW_FREQUENCY_ENABLE)
6871                 return 133333;
6872         else {
6873                 switch (gcfgc & GC_DISPLAY_CLOCK_MASK) {
6874                 case GC_DISPLAY_CLOCK_333_MHZ:
6875                         return 333333;
6876                 default:
6877                 case GC_DISPLAY_CLOCK_190_200_MHZ:
6878                         return 190000;
6879                 }
6880         }
6881 }
6882
6883 static int i865_get_display_clock_speed(struct drm_device *dev)
6884 {
6885         return 266667;
6886 }
6887
6888 static int i85x_get_display_clock_speed(struct drm_device *dev)
6889 {
6890         u16 hpllcc = 0;
6891
6892         /*
6893          * 852GM/852GMV only supports 133 MHz and the HPLLCC
6894          * encoding is different :(
6895          * FIXME is this the right way to detect 852GM/852GMV?
6896          */
6897         if (dev->pdev->revision == 0x1)
6898                 return 133333;
6899
6900         pci_bus_read_config_word(dev->pdev->bus,
6901                                  PCI_DEVFN(0, 3), HPLLCC, &hpllcc);
6902
6903         /* Assume that the hardware is in the high speed state.  This
6904          * should be the default.
6905          */
6906         switch (hpllcc & GC_CLOCK_CONTROL_MASK) {
6907         case GC_CLOCK_133_200:
6908         case GC_CLOCK_133_200_2:
6909         case GC_CLOCK_100_200:
6910                 return 200000;
6911         case GC_CLOCK_166_250:
6912                 return 250000;
6913         case GC_CLOCK_100_133:
6914                 return 133333;
6915         case GC_CLOCK_133_266:
6916         case GC_CLOCK_133_266_2:
6917         case GC_CLOCK_166_266:
6918                 return 266667;
6919         }
6920
6921         /* Shouldn't happen */
6922         return 0;
6923 }
6924
6925 static int i830_get_display_clock_speed(struct drm_device *dev)
6926 {
6927         return 133333;
6928 }
6929
6930 static unsigned int intel_hpll_vco(struct drm_device *dev)
6931 {
6932         struct drm_i915_private *dev_priv = dev->dev_private;
6933         static const unsigned int blb_vco[8] = {
6934                 [0] = 3200000,
6935                 [1] = 4000000,
6936                 [2] = 5333333,
6937                 [3] = 4800000,
6938                 [4] = 6400000,
6939         };
6940         static const unsigned int pnv_vco[8] = {
6941                 [0] = 3200000,
6942                 [1] = 4000000,
6943                 [2] = 5333333,
6944                 [3] = 4800000,
6945                 [4] = 2666667,
6946         };
6947         static const unsigned int cl_vco[8] = {
6948                 [0] = 3200000,
6949                 [1] = 4000000,
6950                 [2] = 5333333,
6951                 [3] = 6400000,
6952                 [4] = 3333333,
6953                 [5] = 3566667,
6954                 [6] = 4266667,
6955         };
6956         static const unsigned int elk_vco[8] = {
6957                 [0] = 3200000,
6958                 [1] = 4000000,
6959                 [2] = 5333333,
6960                 [3] = 4800000,
6961         };
6962         static const unsigned int ctg_vco[8] = {
6963                 [0] = 3200000,
6964                 [1] = 4000000,
6965                 [2] = 5333333,
6966                 [3] = 6400000,
6967                 [4] = 2666667,
6968                 [5] = 4266667,
6969         };
6970         const unsigned int *vco_table;
6971         unsigned int vco;
6972         uint8_t tmp = 0;
6973
6974         /* FIXME other chipsets? */
6975         if (IS_GM45(dev))
6976                 vco_table = ctg_vco;
6977         else if (IS_G4X(dev))
6978                 vco_table = elk_vco;
6979         else if (IS_CRESTLINE(dev))
6980                 vco_table = cl_vco;
6981         else if (IS_PINEVIEW(dev))
6982                 vco_table = pnv_vco;
6983         else if (IS_G33(dev))
6984                 vco_table = blb_vco;
6985         else
6986                 return 0;
6987
6988         tmp = I915_READ(IS_MOBILE(dev) ? HPLLVCO_MOBILE : HPLLVCO);
6989
6990         vco = vco_table[tmp & 0x7];
6991         if (vco == 0)
6992                 DRM_ERROR("Bad HPLL VCO (HPLLVCO=0x%02x)\n", tmp);
6993         else
6994                 DRM_DEBUG_KMS("HPLL VCO %u kHz\n", vco);
6995
6996         return vco;
6997 }
6998
6999 static int gm45_get_display_clock_speed(struct drm_device *dev)
7000 {
7001         unsigned int cdclk_sel, vco = intel_hpll_vco(dev);
7002         uint16_t tmp = 0;
7003
7004         pci_read_config_word(dev->pdev, GCFGC, &tmp);
7005
7006         cdclk_sel = (tmp >> 12) & 0x1;
7007
7008         switch (vco) {
7009         case 2666667:
7010         case 4000000:
7011         case 5333333:
7012                 return cdclk_sel ? 333333 : 222222;
7013         case 3200000:
7014                 return cdclk_sel ? 320000 : 228571;
7015         default:
7016                 DRM_ERROR("Unable to determine CDCLK. HPLL VCO=%u, CFGC=0x%04x\n", vco, tmp);
7017                 return 222222;
7018         }
7019 }
7020
7021 static int i965gm_get_display_clock_speed(struct drm_device *dev)
7022 {
7023         static const uint8_t div_3200[] = { 16, 10,  8 };
7024         static const uint8_t div_4000[] = { 20, 12, 10 };
7025         static const uint8_t div_5333[] = { 24, 16, 14 };
7026         const uint8_t *div_table;
7027         unsigned int cdclk_sel, vco = intel_hpll_vco(dev);
7028         uint16_t tmp = 0;
7029
7030         pci_read_config_word(dev->pdev, GCFGC, &tmp);
7031
7032         cdclk_sel = ((tmp >> 8) & 0x1f) - 1;
7033
7034         if (cdclk_sel >= ARRAY_SIZE(div_3200))
7035                 goto fail;
7036
7037         switch (vco) {
7038         case 3200000:
7039                 div_table = div_3200;
7040                 break;
7041         case 4000000:
7042                 div_table = div_4000;
7043                 break;
7044         case 5333333:
7045                 div_table = div_5333;
7046                 break;
7047         default:
7048                 goto fail;
7049         }
7050
7051         return DIV_ROUND_CLOSEST(vco, div_table[cdclk_sel]);
7052
7053 fail:
7054         DRM_ERROR("Unable to determine CDCLK. HPLL VCO=%u kHz, CFGC=0x%04x\n", vco, tmp);
7055         return 200000;
7056 }
7057
7058 static int g33_get_display_clock_speed(struct drm_device *dev)
7059 {
7060         static const uint8_t div_3200[] = { 12, 10,  8,  7, 5, 16 };
7061         static const uint8_t div_4000[] = { 14, 12, 10,  8, 6, 20 };
7062         static const uint8_t div_4800[] = { 20, 14, 12, 10, 8, 24 };
7063         static const uint8_t div_5333[] = { 20, 16, 12, 12, 8, 28 };
7064         const uint8_t *div_table;
7065         unsigned int cdclk_sel, vco = intel_hpll_vco(dev);
7066         uint16_t tmp = 0;
7067
7068         pci_read_config_word(dev->pdev, GCFGC, &tmp);
7069
7070         cdclk_sel = (tmp >> 4) & 0x7;
7071
7072         if (cdclk_sel >= ARRAY_SIZE(div_3200))
7073                 goto fail;
7074
7075         switch (vco) {
7076         case 3200000:
7077                 div_table = div_3200;
7078                 break;
7079         case 4000000:
7080                 div_table = div_4000;
7081                 break;
7082         case 4800000:
7083                 div_table = div_4800;
7084                 break;
7085         case 5333333:
7086                 div_table = div_5333;
7087                 break;
7088         default:
7089                 goto fail;
7090         }
7091
7092         return DIV_ROUND_CLOSEST(vco, div_table[cdclk_sel]);
7093
7094 fail:
7095         DRM_ERROR("Unable to determine CDCLK. HPLL VCO=%u kHz, CFGC=0x%08x\n", vco, tmp);
7096         return 190476;
7097 }
7098
7099 static void
7100 intel_reduce_m_n_ratio(uint32_t *num, uint32_t *den)
7101 {
7102         while (*num > DATA_LINK_M_N_MASK ||
7103                *den > DATA_LINK_M_N_MASK) {
7104                 *num >>= 1;
7105                 *den >>= 1;
7106         }
7107 }
7108
7109 static void compute_m_n(unsigned int m, unsigned int n,
7110                         uint32_t *ret_m, uint32_t *ret_n)
7111 {
7112         *ret_n = min_t(unsigned int, roundup_pow_of_two(n), DATA_LINK_N_MAX);
7113         *ret_m = div_u64((uint64_t) m * *ret_n, n);
7114         intel_reduce_m_n_ratio(ret_m, ret_n);
7115 }
7116
7117 void
7118 intel_link_compute_m_n(int bits_per_pixel, int nlanes,
7119                        int pixel_clock, int link_clock,
7120                        struct intel_link_m_n *m_n)
7121 {
7122         m_n->tu = 64;
7123
7124         compute_m_n(bits_per_pixel * pixel_clock,
7125                     link_clock * nlanes * 8,
7126                     &m_n->gmch_m, &m_n->gmch_n);
7127
7128         compute_m_n(pixel_clock, link_clock,
7129                     &m_n->link_m, &m_n->link_n);
7130 }
7131
7132 static inline bool intel_panel_use_ssc(struct drm_i915_private *dev_priv)
7133 {
7134         if (i915.panel_use_ssc >= 0)
7135                 return i915.panel_use_ssc != 0;
7136         return dev_priv->vbt.lvds_use_ssc
7137                 && !(dev_priv->quirks & QUIRK_LVDS_SSC_DISABLE);
7138 }
7139
7140 static uint32_t pnv_dpll_compute_fp(struct dpll *dpll)
7141 {
7142         return (1 << dpll->n) << 16 | dpll->m2;
7143 }
7144
7145 static uint32_t i9xx_dpll_compute_fp(struct dpll *dpll)
7146 {
7147         return dpll->n << 16 | dpll->m1 << 8 | dpll->m2;
7148 }
7149
7150 static void i9xx_update_pll_dividers(struct intel_crtc *crtc,
7151                                      struct intel_crtc_state *crtc_state,
7152                                      struct dpll *reduced_clock)
7153 {
7154         struct drm_device *dev = crtc->base.dev;
7155         u32 fp, fp2 = 0;
7156
7157         if (IS_PINEVIEW(dev)) {
7158                 fp = pnv_dpll_compute_fp(&crtc_state->dpll);
7159                 if (reduced_clock)
7160                         fp2 = pnv_dpll_compute_fp(reduced_clock);
7161         } else {
7162                 fp = i9xx_dpll_compute_fp(&crtc_state->dpll);
7163                 if (reduced_clock)
7164                         fp2 = i9xx_dpll_compute_fp(reduced_clock);
7165         }
7166
7167         crtc_state->dpll_hw_state.fp0 = fp;
7168
7169         crtc->lowfreq_avail = false;
7170         if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_LVDS) &&
7171             reduced_clock) {
7172                 crtc_state->dpll_hw_state.fp1 = fp2;
7173                 crtc->lowfreq_avail = true;
7174         } else {
7175                 crtc_state->dpll_hw_state.fp1 = fp;
7176         }
7177 }
7178
7179 static void vlv_pllb_recal_opamp(struct drm_i915_private *dev_priv, enum pipe
7180                 pipe)
7181 {
7182         u32 reg_val;
7183
7184         /*
7185          * PLLB opamp always calibrates to max value of 0x3f, force enable it
7186          * and set it to a reasonable value instead.
7187          */
7188         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW9(1));
7189         reg_val &= 0xffffff00;
7190         reg_val |= 0x00000030;
7191         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW9(1), reg_val);
7192
7193         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_REF_DW13);
7194         reg_val &= 0x8cffffff;
7195         reg_val = 0x8c000000;
7196         vlv_dpio_write(dev_priv, pipe, VLV_REF_DW13, reg_val);
7197
7198         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW9(1));
7199         reg_val &= 0xffffff00;
7200         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW9(1), reg_val);
7201
7202         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_REF_DW13);
7203         reg_val &= 0x00ffffff;
7204         reg_val |= 0xb0000000;
7205         vlv_dpio_write(dev_priv, pipe, VLV_REF_DW13, reg_val);
7206 }
7207
7208 static void intel_pch_transcoder_set_m_n(struct intel_crtc *crtc,
7209                                          struct intel_link_m_n *m_n)
7210 {
7211         struct drm_device *dev = crtc->base.dev;
7212         struct drm_i915_private *dev_priv = dev->dev_private;
7213         int pipe = crtc->pipe;
7214
7215         I915_WRITE(PCH_TRANS_DATA_M1(pipe), TU_SIZE(m_n->tu) | m_n->gmch_m);
7216         I915_WRITE(PCH_TRANS_DATA_N1(pipe), m_n->gmch_n);
7217         I915_WRITE(PCH_TRANS_LINK_M1(pipe), m_n->link_m);
7218         I915_WRITE(PCH_TRANS_LINK_N1(pipe), m_n->link_n);
7219 }
7220
7221 static void intel_cpu_transcoder_set_m_n(struct intel_crtc *crtc,
7222                                          struct intel_link_m_n *m_n,
7223                                          struct intel_link_m_n *m2_n2)
7224 {
7225         struct drm_device *dev = crtc->base.dev;
7226         struct drm_i915_private *dev_priv = dev->dev_private;
7227         int pipe = crtc->pipe;
7228         enum transcoder transcoder = crtc->config->cpu_transcoder;
7229
7230         if (INTEL_INFO(dev)->gen >= 5) {
7231                 I915_WRITE(PIPE_DATA_M1(transcoder), TU_SIZE(m_n->tu) | m_n->gmch_m);
7232                 I915_WRITE(PIPE_DATA_N1(transcoder), m_n->gmch_n);
7233                 I915_WRITE(PIPE_LINK_M1(transcoder), m_n->link_m);
7234                 I915_WRITE(PIPE_LINK_N1(transcoder), m_n->link_n);
7235                 /* M2_N2 registers to be set only for gen < 8 (M2_N2 available
7236                  * for gen < 8) and if DRRS is supported (to make sure the
7237                  * registers are not unnecessarily accessed).
7238                  */
7239                 if (m2_n2 && (IS_CHERRYVIEW(dev) || INTEL_INFO(dev)->gen < 8) &&
7240                         crtc->config->has_drrs) {
7241                         I915_WRITE(PIPE_DATA_M2(transcoder),
7242                                         TU_SIZE(m2_n2->tu) | m2_n2->gmch_m);
7243                         I915_WRITE(PIPE_DATA_N2(transcoder), m2_n2->gmch_n);
7244                         I915_WRITE(PIPE_LINK_M2(transcoder), m2_n2->link_m);
7245                         I915_WRITE(PIPE_LINK_N2(transcoder), m2_n2->link_n);
7246                 }
7247         } else {
7248                 I915_WRITE(PIPE_DATA_M_G4X(pipe), TU_SIZE(m_n->tu) | m_n->gmch_m);
7249                 I915_WRITE(PIPE_DATA_N_G4X(pipe), m_n->gmch_n);
7250                 I915_WRITE(PIPE_LINK_M_G4X(pipe), m_n->link_m);
7251                 I915_WRITE(PIPE_LINK_N_G4X(pipe), m_n->link_n);
7252         }
7253 }
7254
7255 void intel_dp_set_m_n(struct intel_crtc *crtc, enum link_m_n_set m_n)
7256 {
7257         struct intel_link_m_n *dp_m_n, *dp_m2_n2 = NULL;
7258
7259         if (m_n == M1_N1) {
7260                 dp_m_n = &crtc->config->dp_m_n;
7261                 dp_m2_n2 = &crtc->config->dp_m2_n2;
7262         } else if (m_n == M2_N2) {
7263
7264                 /*
7265                  * M2_N2 registers are not supported. Hence m2_n2 divider value
7266                  * needs to be programmed into M1_N1.
7267                  */
7268                 dp_m_n = &crtc->config->dp_m2_n2;
7269         } else {
7270                 DRM_ERROR("Unsupported divider value\n");
7271                 return;
7272         }
7273
7274         if (crtc->config->has_pch_encoder)
7275                 intel_pch_transcoder_set_m_n(crtc, &crtc->config->dp_m_n);
7276         else
7277                 intel_cpu_transcoder_set_m_n(crtc, dp_m_n, dp_m2_n2);
7278 }
7279
7280 static void vlv_compute_dpll(struct intel_crtc *crtc,
7281                              struct intel_crtc_state *pipe_config)
7282 {
7283         pipe_config->dpll_hw_state.dpll = DPLL_INTEGRATED_REF_CLK_VLV |
7284                 DPLL_REF_CLK_ENABLE_VLV | DPLL_VGA_MODE_DIS;
7285         if (crtc->pipe != PIPE_A)
7286                 pipe_config->dpll_hw_state.dpll |= DPLL_INTEGRATED_CRI_CLK_VLV;
7287
7288         /* DPLL not used with DSI, but still need the rest set up */
7289         if (!pipe_config->has_dsi_encoder)
7290                 pipe_config->dpll_hw_state.dpll |= DPLL_VCO_ENABLE |
7291                         DPLL_EXT_BUFFER_ENABLE_VLV;
7292
7293         pipe_config->dpll_hw_state.dpll_md =
7294                 (pipe_config->pixel_multiplier - 1) << DPLL_MD_UDI_MULTIPLIER_SHIFT;
7295 }
7296
7297 static void chv_compute_dpll(struct intel_crtc *crtc,
7298                              struct intel_crtc_state *pipe_config)
7299 {
7300         pipe_config->dpll_hw_state.dpll = DPLL_SSC_REF_CLK_CHV |
7301                 DPLL_REF_CLK_ENABLE_VLV | DPLL_VGA_MODE_DIS;
7302         if (crtc->pipe != PIPE_A)
7303                 pipe_config->dpll_hw_state.dpll |= DPLL_INTEGRATED_CRI_CLK_VLV;
7304
7305         /* DPLL not used with DSI, but still need the rest set up */
7306         if (!pipe_config->has_dsi_encoder)
7307                 pipe_config->dpll_hw_state.dpll |= DPLL_VCO_ENABLE;
7308
7309         pipe_config->dpll_hw_state.dpll_md =
7310                 (pipe_config->pixel_multiplier - 1) << DPLL_MD_UDI_MULTIPLIER_SHIFT;
7311 }
7312
7313 static void vlv_prepare_pll(struct intel_crtc *crtc,
7314                             const struct intel_crtc_state *pipe_config)
7315 {
7316         struct drm_device *dev = crtc->base.dev;
7317         struct drm_i915_private *dev_priv = dev->dev_private;
7318         enum pipe pipe = crtc->pipe;
7319         u32 mdiv;
7320         u32 bestn, bestm1, bestm2, bestp1, bestp2;
7321         u32 coreclk, reg_val;
7322
7323         /* Enable Refclk */
7324         I915_WRITE(DPLL(pipe),
7325                    pipe_config->dpll_hw_state.dpll &
7326                    ~(DPLL_VCO_ENABLE | DPLL_EXT_BUFFER_ENABLE_VLV));
7327
7328         /* No need to actually set up the DPLL with DSI */
7329         if ((pipe_config->dpll_hw_state.dpll & DPLL_VCO_ENABLE) == 0)
7330                 return;
7331
7332         mutex_lock(&dev_priv->sb_lock);
7333
7334         bestn = pipe_config->dpll.n;
7335         bestm1 = pipe_config->dpll.m1;
7336         bestm2 = pipe_config->dpll.m2;
7337         bestp1 = pipe_config->dpll.p1;
7338         bestp2 = pipe_config->dpll.p2;
7339
7340         /* See eDP HDMI DPIO driver vbios notes doc */
7341
7342         /* PLL B needs special handling */
7343         if (pipe == PIPE_B)
7344                 vlv_pllb_recal_opamp(dev_priv, pipe);
7345
7346         /* Set up Tx target for periodic Rcomp update */
7347         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW9_BCAST, 0x0100000f);
7348
7349         /* Disable target IRef on PLL */
7350         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW8(pipe));
7351         reg_val &= 0x00ffffff;
7352         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW8(pipe), reg_val);
7353
7354         /* Disable fast lock */
7355         vlv_dpio_write(dev_priv, pipe, VLV_CMN_DW0, 0x610);
7356
7357         /* Set idtafcrecal before PLL is enabled */
7358         mdiv = ((bestm1 << DPIO_M1DIV_SHIFT) | (bestm2 & DPIO_M2DIV_MASK));
7359         mdiv |= ((bestp1 << DPIO_P1_SHIFT) | (bestp2 << DPIO_P2_SHIFT));
7360         mdiv |= ((bestn << DPIO_N_SHIFT));
7361         mdiv |= (1 << DPIO_K_SHIFT);
7362
7363         /*
7364          * Post divider depends on pixel clock rate, DAC vs digital (and LVDS,
7365          * but we don't support that).
7366          * Note: don't use the DAC post divider as it seems unstable.
7367          */
7368         mdiv |= (DPIO_POST_DIV_HDMIDP << DPIO_POST_DIV_SHIFT);
7369         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW3(pipe), mdiv);
7370
7371         mdiv |= DPIO_ENABLE_CALIBRATION;
7372         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW3(pipe), mdiv);
7373
7374         /* Set HBR and RBR LPF coefficients */
7375         if (pipe_config->port_clock == 162000 ||
7376             intel_pipe_has_type(crtc, INTEL_OUTPUT_ANALOG) ||
7377             intel_pipe_has_type(crtc, INTEL_OUTPUT_HDMI))
7378                 vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW10(pipe),
7379                                  0x009f0003);
7380         else
7381                 vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW10(pipe),
7382                                  0x00d0000f);
7383
7384         if (pipe_config->has_dp_encoder) {
7385                 /* Use SSC source */
7386                 if (pipe == PIPE_A)
7387                         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW5(pipe),
7388                                          0x0df40000);
7389                 else
7390                         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW5(pipe),
7391                                          0x0df70000);
7392         } else { /* HDMI or VGA */
7393                 /* Use bend source */
7394                 if (pipe == PIPE_A)
7395                         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW5(pipe),
7396                                          0x0df70000);
7397                 else
7398                         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW5(pipe),
7399                                          0x0df40000);
7400         }
7401
7402         coreclk = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW7(pipe));
7403         coreclk = (coreclk & 0x0000ff00) | 0x01c00000;
7404         if (intel_pipe_has_type(crtc, INTEL_OUTPUT_DISPLAYPORT) ||
7405             intel_pipe_has_type(crtc, INTEL_OUTPUT_EDP))
7406                 coreclk |= 0x01000000;
7407         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW7(pipe), coreclk);
7408
7409         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW11(pipe), 0x87871000);
7410         mutex_unlock(&dev_priv->sb_lock);
7411 }
7412
7413 static void chv_prepare_pll(struct intel_crtc *crtc,
7414                             const struct intel_crtc_state *pipe_config)
7415 {
7416         struct drm_device *dev = crtc->base.dev;
7417         struct drm_i915_private *dev_priv = dev->dev_private;
7418         enum pipe pipe = crtc->pipe;
7419         enum dpio_channel port = vlv_pipe_to_channel(pipe);
7420         u32 loopfilter, tribuf_calcntr;
7421         u32 bestn, bestm1, bestm2, bestp1, bestp2, bestm2_frac;
7422         u32 dpio_val;
7423         int vco;
7424
7425         /* Enable Refclk and SSC */
7426         I915_WRITE(DPLL(pipe),
7427                    pipe_config->dpll_hw_state.dpll & ~DPLL_VCO_ENABLE);
7428
7429         /* No need to actually set up the DPLL with DSI */
7430         if ((pipe_config->dpll_hw_state.dpll & DPLL_VCO_ENABLE) == 0)
7431                 return;
7432
7433         bestn = pipe_config->dpll.n;
7434         bestm2_frac = pipe_config->dpll.m2 & 0x3fffff;
7435         bestm1 = pipe_config->dpll.m1;
7436         bestm2 = pipe_config->dpll.m2 >> 22;
7437         bestp1 = pipe_config->dpll.p1;
7438         bestp2 = pipe_config->dpll.p2;
7439         vco = pipe_config->dpll.vco;
7440         dpio_val = 0;
7441         loopfilter = 0;
7442
7443         mutex_lock(&dev_priv->sb_lock);
7444
7445         /* p1 and p2 divider */
7446         vlv_dpio_write(dev_priv, pipe, CHV_CMN_DW13(port),
7447                         5 << DPIO_CHV_S1_DIV_SHIFT |
7448                         bestp1 << DPIO_CHV_P1_DIV_SHIFT |
7449                         bestp2 << DPIO_CHV_P2_DIV_SHIFT |
7450                         1 << DPIO_CHV_K_DIV_SHIFT);
7451
7452         /* Feedback post-divider - m2 */
7453         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW0(port), bestm2);
7454
7455         /* Feedback refclk divider - n and m1 */
7456         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW1(port),
7457                         DPIO_CHV_M1_DIV_BY_2 |
7458                         1 << DPIO_CHV_N_DIV_SHIFT);
7459
7460         /* M2 fraction division */
7461         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW2(port), bestm2_frac);
7462
7463         /* M2 fraction division enable */
7464         dpio_val = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW3(port));
7465         dpio_val &= ~(DPIO_CHV_FEEDFWD_GAIN_MASK | DPIO_CHV_FRAC_DIV_EN);
7466         dpio_val |= (2 << DPIO_CHV_FEEDFWD_GAIN_SHIFT);
7467         if (bestm2_frac)
7468                 dpio_val |= DPIO_CHV_FRAC_DIV_EN;
7469         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW3(port), dpio_val);
7470
7471         /* Program digital lock detect threshold */
7472         dpio_val = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW9(port));
7473         dpio_val &= ~(DPIO_CHV_INT_LOCK_THRESHOLD_MASK |
7474                                         DPIO_CHV_INT_LOCK_THRESHOLD_SEL_COARSE);
7475         dpio_val |= (0x5 << DPIO_CHV_INT_LOCK_THRESHOLD_SHIFT);
7476         if (!bestm2_frac)
7477                 dpio_val |= DPIO_CHV_INT_LOCK_THRESHOLD_SEL_COARSE;
7478         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW9(port), dpio_val);
7479
7480         /* Loop filter */
7481         if (vco == 5400000) {
7482                 loopfilter |= (0x3 << DPIO_CHV_PROP_COEFF_SHIFT);
7483                 loopfilter |= (0x8 << DPIO_CHV_INT_COEFF_SHIFT);
7484                 loopfilter |= (0x1 << DPIO_CHV_GAIN_CTRL_SHIFT);
7485                 tribuf_calcntr = 0x9;
7486         } else if (vco <= 6200000) {
7487                 loopfilter |= (0x5 << DPIO_CHV_PROP_COEFF_SHIFT);
7488                 loopfilter |= (0xB << DPIO_CHV_INT_COEFF_SHIFT);
7489                 loopfilter |= (0x3 << DPIO_CHV_GAIN_CTRL_SHIFT);
7490                 tribuf_calcntr = 0x9;
7491         } else if (vco <= 6480000) {
7492                 loopfilter |= (0x4 << DPIO_CHV_PROP_COEFF_SHIFT);
7493                 loopfilter |= (0x9 << DPIO_CHV_INT_COEFF_SHIFT);
7494                 loopfilter |= (0x3 << DPIO_CHV_GAIN_CTRL_SHIFT);
7495                 tribuf_calcntr = 0x8;
7496         } else {
7497                 /* Not supported. Apply the same limits as in the max case */
7498                 loopfilter |= (0x4 << DPIO_CHV_PROP_COEFF_SHIFT);
7499                 loopfilter |= (0x9 << DPIO_CHV_INT_COEFF_SHIFT);
7500                 loopfilter |= (0x3 << DPIO_CHV_GAIN_CTRL_SHIFT);
7501                 tribuf_calcntr = 0;
7502         }
7503         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW6(port), loopfilter);
7504
7505         dpio_val = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW8(port));
7506         dpio_val &= ~DPIO_CHV_TDC_TARGET_CNT_MASK;
7507         dpio_val |= (tribuf_calcntr << DPIO_CHV_TDC_TARGET_CNT_SHIFT);
7508         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW8(port), dpio_val);
7509
7510         /* AFC Recal */
7511         vlv_dpio_write(dev_priv, pipe, CHV_CMN_DW14(port),
7512                         vlv_dpio_read(dev_priv, pipe, CHV_CMN_DW14(port)) |
7513                         DPIO_AFC_RECAL);
7514
7515         mutex_unlock(&dev_priv->sb_lock);
7516 }
7517
7518 /**
7519  * vlv_force_pll_on - forcibly enable just the PLL
7520  * @dev_priv: i915 private structure
7521  * @pipe: pipe PLL to enable
7522  * @dpll: PLL configuration
7523  *
7524  * Enable the PLL for @pipe using the supplied @dpll config. To be used
7525  * in cases where we need the PLL enabled even when @pipe is not going to
7526  * be enabled.
7527  */
7528 int vlv_force_pll_on(struct drm_device *dev, enum pipe pipe,
7529                      const struct dpll *dpll)
7530 {
7531         struct intel_crtc *crtc =
7532                 to_intel_crtc(intel_get_crtc_for_pipe(dev, pipe));
7533         struct intel_crtc_state *pipe_config;
7534
7535         pipe_config = kzalloc(sizeof(*pipe_config), GFP_KERNEL);
7536         if (!pipe_config)
7537                 return -ENOMEM;
7538
7539         pipe_config->base.crtc = &crtc->base;
7540         pipe_config->pixel_multiplier = 1;
7541         pipe_config->dpll = *dpll;
7542
7543         if (IS_CHERRYVIEW(dev)) {
7544                 chv_compute_dpll(crtc, pipe_config);
7545                 chv_prepare_pll(crtc, pipe_config);
7546                 chv_enable_pll(crtc, pipe_config);
7547         } else {
7548                 vlv_compute_dpll(crtc, pipe_config);
7549                 vlv_prepare_pll(crtc, pipe_config);
7550                 vlv_enable_pll(crtc, pipe_config);
7551         }
7552
7553         kfree(pipe_config);
7554
7555         return 0;
7556 }
7557
7558 /**
7559  * vlv_force_pll_off - forcibly disable just the PLL
7560  * @dev_priv: i915 private structure
7561  * @pipe: pipe PLL to disable
7562  *
7563  * Disable the PLL for @pipe. To be used in cases where we need
7564  * the PLL enabled even when @pipe is not going to be enabled.
7565  */
7566 void vlv_force_pll_off(struct drm_device *dev, enum pipe pipe)
7567 {
7568         if (IS_CHERRYVIEW(dev))
7569                 chv_disable_pll(to_i915(dev), pipe);
7570         else
7571                 vlv_disable_pll(to_i915(dev), pipe);
7572 }
7573
7574 static void i9xx_compute_dpll(struct intel_crtc *crtc,
7575                               struct intel_crtc_state *crtc_state,
7576                               struct dpll *reduced_clock)
7577 {
7578         struct drm_device *dev = crtc->base.dev;
7579         struct drm_i915_private *dev_priv = dev->dev_private;
7580         u32 dpll;
7581         bool is_sdvo;
7582         struct dpll *clock = &crtc_state->dpll;
7583
7584         i9xx_update_pll_dividers(crtc, crtc_state, reduced_clock);
7585
7586         is_sdvo = intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_SDVO) ||
7587                 intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_HDMI);
7588
7589         dpll = DPLL_VGA_MODE_DIS;
7590
7591         if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_LVDS))
7592                 dpll |= DPLLB_MODE_LVDS;
7593         else
7594                 dpll |= DPLLB_MODE_DAC_SERIAL;
7595
7596         if (IS_I945G(dev) || IS_I945GM(dev) || IS_G33(dev)) {
7597                 dpll |= (crtc_state->pixel_multiplier - 1)
7598                         << SDVO_MULTIPLIER_SHIFT_HIRES;
7599         }
7600
7601         if (is_sdvo)
7602                 dpll |= DPLL_SDVO_HIGH_SPEED;
7603
7604         if (crtc_state->has_dp_encoder)
7605                 dpll |= DPLL_SDVO_HIGH_SPEED;
7606
7607         /* compute bitmask from p1 value */
7608         if (IS_PINEVIEW(dev))
7609                 dpll |= (1 << (clock->p1 - 1)) << DPLL_FPA01_P1_POST_DIV_SHIFT_PINEVIEW;
7610         else {
7611                 dpll |= (1 << (clock->p1 - 1)) << DPLL_FPA01_P1_POST_DIV_SHIFT;
7612                 if (IS_G4X(dev) && reduced_clock)
7613                         dpll |= (1 << (reduced_clock->p1 - 1)) << DPLL_FPA1_P1_POST_DIV_SHIFT;
7614         }
7615         switch (clock->p2) {
7616         case 5:
7617                 dpll |= DPLL_DAC_SERIAL_P2_CLOCK_DIV_5;
7618                 break;
7619         case 7:
7620                 dpll |= DPLLB_LVDS_P2_CLOCK_DIV_7;
7621                 break;
7622         case 10:
7623                 dpll |= DPLL_DAC_SERIAL_P2_CLOCK_DIV_10;
7624                 break;
7625         case 14:
7626                 dpll |= DPLLB_LVDS_P2_CLOCK_DIV_14;
7627                 break;
7628         }
7629         if (INTEL_INFO(dev)->gen >= 4)
7630                 dpll |= (6 << PLL_LOAD_PULSE_PHASE_SHIFT);
7631
7632         if (crtc_state->sdvo_tv_clock)
7633                 dpll |= PLL_REF_INPUT_TVCLKINBC;
7634         else if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_LVDS) &&
7635                  intel_panel_use_ssc(dev_priv))
7636                 dpll |= PLLB_REF_INPUT_SPREADSPECTRUMIN;
7637         else
7638                 dpll |= PLL_REF_INPUT_DREFCLK;
7639
7640         dpll |= DPLL_VCO_ENABLE;
7641         crtc_state->dpll_hw_state.dpll = dpll;
7642
7643         if (INTEL_INFO(dev)->gen >= 4) {
7644                 u32 dpll_md = (crtc_state->pixel_multiplier - 1)
7645                         << DPLL_MD_UDI_MULTIPLIER_SHIFT;
7646                 crtc_state->dpll_hw_state.dpll_md = dpll_md;
7647         }
7648 }
7649
7650 static void i8xx_compute_dpll(struct intel_crtc *crtc,
7651                               struct intel_crtc_state *crtc_state,
7652                               struct dpll *reduced_clock)
7653 {
7654         struct drm_device *dev = crtc->base.dev;
7655         struct drm_i915_private *dev_priv = dev->dev_private;
7656         u32 dpll;
7657         struct dpll *clock = &crtc_state->dpll;
7658
7659         i9xx_update_pll_dividers(crtc, crtc_state, reduced_clock);
7660
7661         dpll = DPLL_VGA_MODE_DIS;
7662
7663         if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_LVDS)) {
7664                 dpll |= (1 << (clock->p1 - 1)) << DPLL_FPA01_P1_POST_DIV_SHIFT;
7665         } else {
7666                 if (clock->p1 == 2)
7667                         dpll |= PLL_P1_DIVIDE_BY_TWO;
7668                 else
7669                         dpll |= (clock->p1 - 2) << DPLL_FPA01_P1_POST_DIV_SHIFT;
7670                 if (clock->p2 == 4)
7671                         dpll |= PLL_P2_DIVIDE_BY_4;
7672         }
7673
7674         if (!IS_I830(dev) && intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_DVO))
7675                 dpll |= DPLL_DVO_2X_MODE;
7676
7677         if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_LVDS) &&
7678             intel_panel_use_ssc(dev_priv))
7679                 dpll |= PLLB_REF_INPUT_SPREADSPECTRUMIN;
7680         else
7681                 dpll |= PLL_REF_INPUT_DREFCLK;
7682
7683         dpll |= DPLL_VCO_ENABLE;
7684         crtc_state->dpll_hw_state.dpll = dpll;
7685 }
7686
7687 static void intel_set_pipe_timings(struct intel_crtc *intel_crtc)
7688 {
7689         struct drm_device *dev = intel_crtc->base.dev;
7690         struct drm_i915_private *dev_priv = dev->dev_private;
7691         enum pipe pipe = intel_crtc->pipe;
7692         enum transcoder cpu_transcoder = intel_crtc->config->cpu_transcoder;
7693         const struct drm_display_mode *adjusted_mode = &intel_crtc->config->base.adjusted_mode;
7694         uint32_t crtc_vtotal, crtc_vblank_end;
7695         int vsyncshift = 0;
7696
7697         /* We need to be careful not to changed the adjusted mode, for otherwise
7698          * the hw state checker will get angry at the mismatch. */
7699         crtc_vtotal = adjusted_mode->crtc_vtotal;
7700         crtc_vblank_end = adjusted_mode->crtc_vblank_end;
7701
7702         if (adjusted_mode->flags & DRM_MODE_FLAG_INTERLACE) {
7703                 /* the chip adds 2 halflines automatically */
7704                 crtc_vtotal -= 1;
7705                 crtc_vblank_end -= 1;
7706
7707                 if (intel_pipe_has_type(intel_crtc, INTEL_OUTPUT_SDVO))
7708                         vsyncshift = (adjusted_mode->crtc_htotal - 1) / 2;
7709                 else
7710                         vsyncshift = adjusted_mode->crtc_hsync_start -
7711                                 adjusted_mode->crtc_htotal / 2;
7712                 if (vsyncshift < 0)
7713                         vsyncshift += adjusted_mode->crtc_htotal;
7714         }
7715
7716         if (INTEL_INFO(dev)->gen > 3)
7717                 I915_WRITE(VSYNCSHIFT(cpu_transcoder), vsyncshift);
7718
7719         I915_WRITE(HTOTAL(cpu_transcoder),
7720                    (adjusted_mode->crtc_hdisplay - 1) |
7721                    ((adjusted_mode->crtc_htotal - 1) << 16));
7722         I915_WRITE(HBLANK(cpu_transcoder),
7723                    (adjusted_mode->crtc_hblank_start - 1) |
7724                    ((adjusted_mode->crtc_hblank_end - 1) << 16));
7725         I915_WRITE(HSYNC(cpu_transcoder),
7726                    (adjusted_mode->crtc_hsync_start - 1) |
7727                    ((adjusted_mode->crtc_hsync_end - 1) << 16));
7728
7729         I915_WRITE(VTOTAL(cpu_transcoder),
7730                    (adjusted_mode->crtc_vdisplay - 1) |
7731                    ((crtc_vtotal - 1) << 16));
7732         I915_WRITE(VBLANK(cpu_transcoder),
7733                    (adjusted_mode->crtc_vblank_start - 1) |
7734                    ((crtc_vblank_end - 1) << 16));
7735         I915_WRITE(VSYNC(cpu_transcoder),
7736                    (adjusted_mode->crtc_vsync_start - 1) |
7737                    ((adjusted_mode->crtc_vsync_end - 1) << 16));
7738
7739         /* Workaround: when the EDP input selection is B, the VTOTAL_B must be
7740          * programmed with the VTOTAL_EDP value. Same for VTOTAL_C. This is
7741          * documented on the DDI_FUNC_CTL register description, EDP Input Select
7742          * bits. */
7743         if (IS_HASWELL(dev) && cpu_transcoder == TRANSCODER_EDP &&
7744             (pipe == PIPE_B || pipe == PIPE_C))
7745                 I915_WRITE(VTOTAL(pipe), I915_READ(VTOTAL(cpu_transcoder)));
7746
7747 }
7748
7749 static void intel_set_pipe_src_size(struct intel_crtc *intel_crtc)
7750 {
7751         struct drm_device *dev = intel_crtc->base.dev;
7752         struct drm_i915_private *dev_priv = dev->dev_private;
7753         enum pipe pipe = intel_crtc->pipe;
7754
7755         /* pipesrc controls the size that is scaled from, which should
7756          * always be the user's requested size.
7757          */
7758         I915_WRITE(PIPESRC(pipe),
7759                    ((intel_crtc->config->pipe_src_w - 1) << 16) |
7760                    (intel_crtc->config->pipe_src_h - 1));
7761 }
7762
7763 static void intel_get_pipe_timings(struct intel_crtc *crtc,
7764                                    struct intel_crtc_state *pipe_config)
7765 {
7766         struct drm_device *dev = crtc->base.dev;
7767         struct drm_i915_private *dev_priv = dev->dev_private;
7768         enum transcoder cpu_transcoder = pipe_config->cpu_transcoder;
7769         uint32_t tmp;
7770
7771         tmp = I915_READ(HTOTAL(cpu_transcoder));
7772         pipe_config->base.adjusted_mode.crtc_hdisplay = (tmp & 0xffff) + 1;
7773         pipe_config->base.adjusted_mode.crtc_htotal = ((tmp >> 16) & 0xffff) + 1;
7774         tmp = I915_READ(HBLANK(cpu_transcoder));
7775         pipe_config->base.adjusted_mode.crtc_hblank_start = (tmp & 0xffff) + 1;
7776         pipe_config->base.adjusted_mode.crtc_hblank_end = ((tmp >> 16) & 0xffff) + 1;
7777         tmp = I915_READ(HSYNC(cpu_transcoder));
7778         pipe_config->base.adjusted_mode.crtc_hsync_start = (tmp & 0xffff) + 1;
7779         pipe_config->base.adjusted_mode.crtc_hsync_end = ((tmp >> 16) & 0xffff) + 1;
7780
7781         tmp = I915_READ(VTOTAL(cpu_transcoder));
7782         pipe_config->base.adjusted_mode.crtc_vdisplay = (tmp & 0xffff) + 1;
7783         pipe_config->base.adjusted_mode.crtc_vtotal = ((tmp >> 16) & 0xffff) + 1;
7784         tmp = I915_READ(VBLANK(cpu_transcoder));
7785         pipe_config->base.adjusted_mode.crtc_vblank_start = (tmp & 0xffff) + 1;
7786         pipe_config->base.adjusted_mode.crtc_vblank_end = ((tmp >> 16) & 0xffff) + 1;
7787         tmp = I915_READ(VSYNC(cpu_transcoder));
7788         pipe_config->base.adjusted_mode.crtc_vsync_start = (tmp & 0xffff) + 1;
7789         pipe_config->base.adjusted_mode.crtc_vsync_end = ((tmp >> 16) & 0xffff) + 1;
7790
7791         if (I915_READ(PIPECONF(cpu_transcoder)) & PIPECONF_INTERLACE_MASK) {
7792                 pipe_config->base.adjusted_mode.flags |= DRM_MODE_FLAG_INTERLACE;
7793                 pipe_config->base.adjusted_mode.crtc_vtotal += 1;
7794                 pipe_config->base.adjusted_mode.crtc_vblank_end += 1;
7795         }
7796 }
7797
7798 static void intel_get_pipe_src_size(struct intel_crtc *crtc,
7799                                     struct intel_crtc_state *pipe_config)
7800 {
7801         struct drm_device *dev = crtc->base.dev;
7802         struct drm_i915_private *dev_priv = dev->dev_private;
7803         u32 tmp;
7804
7805         tmp = I915_READ(PIPESRC(crtc->pipe));
7806         pipe_config->pipe_src_h = (tmp & 0xffff) + 1;
7807         pipe_config->pipe_src_w = ((tmp >> 16) & 0xffff) + 1;
7808
7809         pipe_config->base.mode.vdisplay = pipe_config->pipe_src_h;
7810         pipe_config->base.mode.hdisplay = pipe_config->pipe_src_w;
7811 }
7812
7813 void intel_mode_from_pipe_config(struct drm_display_mode *mode,
7814                                  struct intel_crtc_state *pipe_config)
7815 {
7816         mode->hdisplay = pipe_config->base.adjusted_mode.crtc_hdisplay;
7817         mode->htotal = pipe_config->base.adjusted_mode.crtc_htotal;
7818         mode->hsync_start = pipe_config->base.adjusted_mode.crtc_hsync_start;
7819         mode->hsync_end = pipe_config->base.adjusted_mode.crtc_hsync_end;
7820
7821         mode->vdisplay = pipe_config->base.adjusted_mode.crtc_vdisplay;
7822         mode->vtotal = pipe_config->base.adjusted_mode.crtc_vtotal;
7823         mode->vsync_start = pipe_config->base.adjusted_mode.crtc_vsync_start;
7824         mode->vsync_end = pipe_config->base.adjusted_mode.crtc_vsync_end;
7825
7826         mode->flags = pipe_config->base.adjusted_mode.flags;
7827         mode->type = DRM_MODE_TYPE_DRIVER;
7828
7829         mode->clock = pipe_config->base.adjusted_mode.crtc_clock;
7830         mode->flags |= pipe_config->base.adjusted_mode.flags;
7831
7832         mode->hsync = drm_mode_hsync(mode);
7833         mode->vrefresh = drm_mode_vrefresh(mode);
7834         drm_mode_set_name(mode);
7835 }
7836
7837 static void i9xx_set_pipeconf(struct intel_crtc *intel_crtc)
7838 {
7839         struct drm_device *dev = intel_crtc->base.dev;
7840         struct drm_i915_private *dev_priv = dev->dev_private;
7841         uint32_t pipeconf;
7842
7843         pipeconf = 0;
7844
7845         if ((intel_crtc->pipe == PIPE_A && dev_priv->quirks & QUIRK_PIPEA_FORCE) ||
7846             (intel_crtc->pipe == PIPE_B && dev_priv->quirks & QUIRK_PIPEB_FORCE))
7847                 pipeconf |= I915_READ(PIPECONF(intel_crtc->pipe)) & PIPECONF_ENABLE;
7848
7849         if (intel_crtc->config->double_wide)
7850                 pipeconf |= PIPECONF_DOUBLE_WIDE;
7851
7852         /* only g4x and later have fancy bpc/dither controls */
7853         if (IS_G4X(dev) || IS_VALLEYVIEW(dev) || IS_CHERRYVIEW(dev)) {
7854                 /* Bspec claims that we can't use dithering for 30bpp pipes. */
7855                 if (intel_crtc->config->dither && intel_crtc->config->pipe_bpp != 30)
7856                         pipeconf |= PIPECONF_DITHER_EN |
7857                                     PIPECONF_DITHER_TYPE_SP;
7858
7859                 switch (intel_crtc->config->pipe_bpp) {
7860                 case 18:
7861                         pipeconf |= PIPECONF_6BPC;
7862                         break;
7863                 case 24:
7864                         pipeconf |= PIPECONF_8BPC;
7865                         break;
7866                 case 30:
7867                         pipeconf |= PIPECONF_10BPC;
7868                         break;
7869                 default:
7870                         /* Case prevented by intel_choose_pipe_bpp_dither. */
7871                         BUG();
7872                 }
7873         }
7874
7875         if (HAS_PIPE_CXSR(dev)) {
7876                 if (intel_crtc->lowfreq_avail) {
7877                         DRM_DEBUG_KMS("enabling CxSR downclocking\n");
7878                         pipeconf |= PIPECONF_CXSR_DOWNCLOCK;
7879                 } else {
7880                         DRM_DEBUG_KMS("disabling CxSR downclocking\n");
7881                 }
7882         }
7883
7884         if (intel_crtc->config->base.adjusted_mode.flags & DRM_MODE_FLAG_INTERLACE) {
7885                 if (INTEL_INFO(dev)->gen < 4 ||
7886                     intel_pipe_has_type(intel_crtc, INTEL_OUTPUT_SDVO))
7887                         pipeconf |= PIPECONF_INTERLACE_W_FIELD_INDICATION;
7888                 else
7889                         pipeconf |= PIPECONF_INTERLACE_W_SYNC_SHIFT;
7890         } else
7891                 pipeconf |= PIPECONF_PROGRESSIVE;
7892
7893         if ((IS_VALLEYVIEW(dev) || IS_CHERRYVIEW(dev)) &&
7894              intel_crtc->config->limited_color_range)
7895                 pipeconf |= PIPECONF_COLOR_RANGE_SELECT;
7896
7897         I915_WRITE(PIPECONF(intel_crtc->pipe), pipeconf);
7898         POSTING_READ(PIPECONF(intel_crtc->pipe));
7899 }
7900
7901 static int i8xx_crtc_compute_clock(struct intel_crtc *crtc,
7902                                    struct intel_crtc_state *crtc_state)
7903 {
7904         struct drm_device *dev = crtc->base.dev;
7905         struct drm_i915_private *dev_priv = dev->dev_private;
7906         const struct intel_limit *limit;
7907         int refclk = 48000;
7908
7909         memset(&crtc_state->dpll_hw_state, 0,
7910                sizeof(crtc_state->dpll_hw_state));
7911
7912         if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_LVDS)) {
7913                 if (intel_panel_use_ssc(dev_priv)) {
7914                         refclk = dev_priv->vbt.lvds_ssc_freq;
7915                         DRM_DEBUG_KMS("using SSC reference clock of %d kHz\n", refclk);
7916                 }
7917
7918                 limit = &intel_limits_i8xx_lvds;
7919         } else if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_DVO)) {
7920                 limit = &intel_limits_i8xx_dvo;
7921         } else {
7922                 limit = &intel_limits_i8xx_dac;
7923         }
7924
7925         if (!crtc_state->clock_set &&
7926             !i9xx_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
7927                                  refclk, NULL, &crtc_state->dpll)) {
7928                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
7929                 return -EINVAL;
7930         }
7931
7932         i8xx_compute_dpll(crtc, crtc_state, NULL);
7933
7934         return 0;
7935 }
7936
7937 static int g4x_crtc_compute_clock(struct intel_crtc *crtc,
7938                                   struct intel_crtc_state *crtc_state)
7939 {
7940         struct drm_device *dev = crtc->base.dev;
7941         struct drm_i915_private *dev_priv = dev->dev_private;
7942         const struct intel_limit *limit;
7943         int refclk = 96000;
7944
7945         memset(&crtc_state->dpll_hw_state, 0,
7946                sizeof(crtc_state->dpll_hw_state));
7947
7948         if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_LVDS)) {
7949                 if (intel_panel_use_ssc(dev_priv)) {
7950                         refclk = dev_priv->vbt.lvds_ssc_freq;
7951                         DRM_DEBUG_KMS("using SSC reference clock of %d kHz\n", refclk);
7952                 }
7953
7954                 if (intel_is_dual_link_lvds(dev))
7955                         limit = &intel_limits_g4x_dual_channel_lvds;
7956                 else
7957                         limit = &intel_limits_g4x_single_channel_lvds;
7958         } else if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_HDMI) ||
7959                    intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_ANALOG)) {
7960                 limit = &intel_limits_g4x_hdmi;
7961         } else if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_SDVO)) {
7962                 limit = &intel_limits_g4x_sdvo;
7963         } else {
7964                 /* The option is for other outputs */
7965                 limit = &intel_limits_i9xx_sdvo;
7966         }
7967
7968         if (!crtc_state->clock_set &&
7969             !g4x_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
7970                                 refclk, NULL, &crtc_state->dpll)) {
7971                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
7972                 return -EINVAL;
7973         }
7974
7975         i9xx_compute_dpll(crtc, crtc_state, NULL);
7976
7977         return 0;
7978 }
7979
7980 static int pnv_crtc_compute_clock(struct intel_crtc *crtc,
7981                                   struct intel_crtc_state *crtc_state)
7982 {
7983         struct drm_device *dev = crtc->base.dev;
7984         struct drm_i915_private *dev_priv = dev->dev_private;
7985         const struct intel_limit *limit;
7986         int refclk = 96000;
7987
7988         memset(&crtc_state->dpll_hw_state, 0,
7989                sizeof(crtc_state->dpll_hw_state));
7990
7991         if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_LVDS)) {
7992                 if (intel_panel_use_ssc(dev_priv)) {
7993                         refclk = dev_priv->vbt.lvds_ssc_freq;
7994                         DRM_DEBUG_KMS("using SSC reference clock of %d kHz\n", refclk);
7995                 }
7996
7997                 limit = &intel_limits_pineview_lvds;
7998         } else {
7999                 limit = &intel_limits_pineview_sdvo;
8000         }
8001
8002         if (!crtc_state->clock_set &&
8003             !pnv_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
8004                                 refclk, NULL, &crtc_state->dpll)) {
8005                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
8006                 return -EINVAL;
8007         }
8008
8009         i9xx_compute_dpll(crtc, crtc_state, NULL);
8010
8011         return 0;
8012 }
8013
8014 static int i9xx_crtc_compute_clock(struct intel_crtc *crtc,
8015                                    struct intel_crtc_state *crtc_state)
8016 {
8017         struct drm_device *dev = crtc->base.dev;
8018         struct drm_i915_private *dev_priv = dev->dev_private;
8019         const struct intel_limit *limit;
8020         int refclk = 96000;
8021
8022         memset(&crtc_state->dpll_hw_state, 0,
8023                sizeof(crtc_state->dpll_hw_state));
8024
8025         if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_LVDS)) {
8026                 if (intel_panel_use_ssc(dev_priv)) {
8027                         refclk = dev_priv->vbt.lvds_ssc_freq;
8028                         DRM_DEBUG_KMS("using SSC reference clock of %d kHz\n", refclk);
8029                 }
8030
8031                 limit = &intel_limits_i9xx_lvds;
8032         } else {
8033                 limit = &intel_limits_i9xx_sdvo;
8034         }
8035
8036         if (!crtc_state->clock_set &&
8037             !i9xx_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
8038                                  refclk, NULL, &crtc_state->dpll)) {
8039                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
8040                 return -EINVAL;
8041         }
8042
8043         i9xx_compute_dpll(crtc, crtc_state, NULL);
8044
8045         return 0;
8046 }
8047
8048 static int chv_crtc_compute_clock(struct intel_crtc *crtc,
8049                                   struct intel_crtc_state *crtc_state)
8050 {
8051         int refclk = 100000;
8052         const struct intel_limit *limit = &intel_limits_chv;
8053
8054         memset(&crtc_state->dpll_hw_state, 0,
8055                sizeof(crtc_state->dpll_hw_state));
8056
8057         if (!crtc_state->clock_set &&
8058             !chv_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
8059                                 refclk, NULL, &crtc_state->dpll)) {
8060                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
8061                 return -EINVAL;
8062         }
8063
8064         chv_compute_dpll(crtc, crtc_state);
8065
8066         return 0;
8067 }
8068
8069 static int vlv_crtc_compute_clock(struct intel_crtc *crtc,
8070                                   struct intel_crtc_state *crtc_state)
8071 {
8072         int refclk = 100000;
8073         const struct intel_limit *limit = &intel_limits_vlv;
8074
8075         memset(&crtc_state->dpll_hw_state, 0,
8076                sizeof(crtc_state->dpll_hw_state));
8077
8078         if (!crtc_state->clock_set &&
8079             !vlv_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
8080                                 refclk, NULL, &crtc_state->dpll)) {
8081                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
8082                 return -EINVAL;
8083         }
8084
8085         vlv_compute_dpll(crtc, crtc_state);
8086
8087         return 0;
8088 }
8089
8090 static void i9xx_get_pfit_config(struct intel_crtc *crtc,
8091                                  struct intel_crtc_state *pipe_config)
8092 {
8093         struct drm_device *dev = crtc->base.dev;
8094         struct drm_i915_private *dev_priv = dev->dev_private;
8095         uint32_t tmp;
8096
8097         if (INTEL_INFO(dev)->gen <= 3 && (IS_I830(dev) || !IS_MOBILE(dev)))
8098                 return;
8099
8100         tmp = I915_READ(PFIT_CONTROL);
8101         if (!(tmp & PFIT_ENABLE))
8102                 return;
8103
8104         /* Check whether the pfit is attached to our pipe. */
8105         if (INTEL_INFO(dev)->gen < 4) {
8106                 if (crtc->pipe != PIPE_B)
8107                         return;
8108         } else {
8109                 if ((tmp & PFIT_PIPE_MASK) != (crtc->pipe << PFIT_PIPE_SHIFT))
8110                         return;
8111         }
8112
8113         pipe_config->gmch_pfit.control = tmp;
8114         pipe_config->gmch_pfit.pgm_ratios = I915_READ(PFIT_PGM_RATIOS);
8115 }
8116
8117 static void vlv_crtc_clock_get(struct intel_crtc *crtc,
8118                                struct intel_crtc_state *pipe_config)
8119 {
8120         struct drm_device *dev = crtc->base.dev;
8121         struct drm_i915_private *dev_priv = dev->dev_private;
8122         int pipe = pipe_config->cpu_transcoder;
8123         struct dpll clock;
8124         u32 mdiv;
8125         int refclk = 100000;
8126
8127         /* In case of DSI, DPLL will not be used */
8128         if ((pipe_config->dpll_hw_state.dpll & DPLL_VCO_ENABLE) == 0)
8129                 return;
8130
8131         mutex_lock(&dev_priv->sb_lock);
8132         mdiv = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW3(pipe));
8133         mutex_unlock(&dev_priv->sb_lock);
8134
8135         clock.m1 = (mdiv >> DPIO_M1DIV_SHIFT) & 7;
8136         clock.m2 = mdiv & DPIO_M2DIV_MASK;
8137         clock.n = (mdiv >> DPIO_N_SHIFT) & 0xf;
8138         clock.p1 = (mdiv >> DPIO_P1_SHIFT) & 7;
8139         clock.p2 = (mdiv >> DPIO_P2_SHIFT) & 0x1f;
8140
8141         pipe_config->port_clock = vlv_calc_dpll_params(refclk, &clock);
8142 }
8143
8144 static void
8145 i9xx_get_initial_plane_config(struct intel_crtc *crtc,
8146                               struct intel_initial_plane_config *plane_config)
8147 {
8148         struct drm_device *dev = crtc->base.dev;
8149         struct drm_i915_private *dev_priv = dev->dev_private;
8150         u32 val, base, offset;
8151         int pipe = crtc->pipe, plane = crtc->plane;
8152         int fourcc, pixel_format;
8153         unsigned int aligned_height;
8154         struct drm_framebuffer *fb;
8155         struct intel_framebuffer *intel_fb;
8156
8157         val = I915_READ(DSPCNTR(plane));
8158         if (!(val & DISPLAY_PLANE_ENABLE))
8159                 return;
8160
8161         intel_fb = kzalloc(sizeof(*intel_fb), GFP_KERNEL);
8162         if (!intel_fb) {
8163                 DRM_DEBUG_KMS("failed to alloc fb\n");
8164                 return;
8165         }
8166
8167         fb = &intel_fb->base;
8168
8169         if (INTEL_INFO(dev)->gen >= 4) {
8170                 if (val & DISPPLANE_TILED) {
8171                         plane_config->tiling = I915_TILING_X;
8172                         fb->modifier[0] = I915_FORMAT_MOD_X_TILED;
8173                 }
8174         }
8175
8176         pixel_format = val & DISPPLANE_PIXFORMAT_MASK;
8177         fourcc = i9xx_format_to_fourcc(pixel_format);
8178         fb->pixel_format = fourcc;
8179         fb->bits_per_pixel = drm_format_plane_cpp(fourcc, 0) * 8;
8180
8181         if (INTEL_INFO(dev)->gen >= 4) {
8182                 if (plane_config->tiling)
8183                         offset = I915_READ(DSPTILEOFF(plane));
8184                 else
8185                         offset = I915_READ(DSPLINOFF(plane));
8186                 base = I915_READ(DSPSURF(plane)) & 0xfffff000;
8187         } else {
8188                 base = I915_READ(DSPADDR(plane));
8189         }
8190         plane_config->base = base;
8191
8192         val = I915_READ(PIPESRC(pipe));
8193         fb->width = ((val >> 16) & 0xfff) + 1;
8194         fb->height = ((val >> 0) & 0xfff) + 1;
8195
8196         val = I915_READ(DSPSTRIDE(pipe));
8197         fb->pitches[0] = val & 0xffffffc0;
8198
8199         aligned_height = intel_fb_align_height(dev, fb->height,
8200                                                fb->pixel_format,
8201                                                fb->modifier[0]);
8202
8203         plane_config->size = fb->pitches[0] * aligned_height;
8204
8205         DRM_DEBUG_KMS("pipe/plane %c/%d with fb: size=%dx%d@%d, offset=%x, pitch %d, size 0x%x\n",
8206                       pipe_name(pipe), plane, fb->width, fb->height,
8207                       fb->bits_per_pixel, base, fb->pitches[0],
8208                       plane_config->size);
8209
8210         plane_config->fb = intel_fb;
8211 }
8212
8213 static void chv_crtc_clock_get(struct intel_crtc *crtc,
8214                                struct intel_crtc_state *pipe_config)
8215 {
8216         struct drm_device *dev = crtc->base.dev;
8217         struct drm_i915_private *dev_priv = dev->dev_private;
8218         int pipe = pipe_config->cpu_transcoder;
8219         enum dpio_channel port = vlv_pipe_to_channel(pipe);
8220         struct dpll clock;
8221         u32 cmn_dw13, pll_dw0, pll_dw1, pll_dw2, pll_dw3;
8222         int refclk = 100000;
8223
8224         /* In case of DSI, DPLL will not be used */
8225         if ((pipe_config->dpll_hw_state.dpll & DPLL_VCO_ENABLE) == 0)
8226                 return;
8227
8228         mutex_lock(&dev_priv->sb_lock);
8229         cmn_dw13 = vlv_dpio_read(dev_priv, pipe, CHV_CMN_DW13(port));
8230         pll_dw0 = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW0(port));
8231         pll_dw1 = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW1(port));
8232         pll_dw2 = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW2(port));
8233         pll_dw3 = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW3(port));
8234         mutex_unlock(&dev_priv->sb_lock);
8235
8236         clock.m1 = (pll_dw1 & 0x7) == DPIO_CHV_M1_DIV_BY_2 ? 2 : 0;
8237         clock.m2 = (pll_dw0 & 0xff) << 22;
8238         if (pll_dw3 & DPIO_CHV_FRAC_DIV_EN)
8239                 clock.m2 |= pll_dw2 & 0x3fffff;
8240         clock.n = (pll_dw1 >> DPIO_CHV_N_DIV_SHIFT) & 0xf;
8241         clock.p1 = (cmn_dw13 >> DPIO_CHV_P1_DIV_SHIFT) & 0x7;
8242         clock.p2 = (cmn_dw13 >> DPIO_CHV_P2_DIV_SHIFT) & 0x1f;
8243
8244         pipe_config->port_clock = chv_calc_dpll_params(refclk, &clock);
8245 }
8246
8247 static bool i9xx_get_pipe_config(struct intel_crtc *crtc,
8248                                  struct intel_crtc_state *pipe_config)
8249 {
8250         struct drm_device *dev = crtc->base.dev;
8251         struct drm_i915_private *dev_priv = dev->dev_private;
8252         enum intel_display_power_domain power_domain;
8253         uint32_t tmp;
8254         bool ret;
8255
8256         power_domain = POWER_DOMAIN_PIPE(crtc->pipe);
8257         if (!intel_display_power_get_if_enabled(dev_priv, power_domain))
8258                 return false;
8259
8260         pipe_config->cpu_transcoder = (enum transcoder) crtc->pipe;
8261         pipe_config->shared_dpll = NULL;
8262
8263         ret = false;
8264
8265         tmp = I915_READ(PIPECONF(crtc->pipe));
8266         if (!(tmp & PIPECONF_ENABLE))
8267                 goto out;
8268
8269         if (IS_G4X(dev) || IS_VALLEYVIEW(dev) || IS_CHERRYVIEW(dev)) {
8270                 switch (tmp & PIPECONF_BPC_MASK) {
8271                 case PIPECONF_6BPC:
8272                         pipe_config->pipe_bpp = 18;
8273                         break;
8274                 case PIPECONF_8BPC:
8275                         pipe_config->pipe_bpp = 24;
8276                         break;
8277                 case PIPECONF_10BPC:
8278                         pipe_config->pipe_bpp = 30;
8279                         break;
8280                 default:
8281                         break;
8282                 }
8283         }
8284
8285         if ((IS_VALLEYVIEW(dev) || IS_CHERRYVIEW(dev)) &&
8286             (tmp & PIPECONF_COLOR_RANGE_SELECT))
8287                 pipe_config->limited_color_range = true;
8288
8289         if (INTEL_INFO(dev)->gen < 4)
8290                 pipe_config->double_wide = tmp & PIPECONF_DOUBLE_WIDE;
8291
8292         intel_get_pipe_timings(crtc, pipe_config);
8293         intel_get_pipe_src_size(crtc, pipe_config);
8294
8295         i9xx_get_pfit_config(crtc, pipe_config);
8296
8297         if (INTEL_INFO(dev)->gen >= 4) {
8298                 /* No way to read it out on pipes B and C */
8299                 if (IS_CHERRYVIEW(dev) && crtc->pipe != PIPE_A)
8300                         tmp = dev_priv->chv_dpll_md[crtc->pipe];
8301                 else
8302                         tmp = I915_READ(DPLL_MD(crtc->pipe));
8303                 pipe_config->pixel_multiplier =
8304                         ((tmp & DPLL_MD_UDI_MULTIPLIER_MASK)
8305                          >> DPLL_MD_UDI_MULTIPLIER_SHIFT) + 1;
8306                 pipe_config->dpll_hw_state.dpll_md = tmp;
8307         } else if (IS_I945G(dev) || IS_I945GM(dev) || IS_G33(dev)) {
8308                 tmp = I915_READ(DPLL(crtc->pipe));
8309                 pipe_config->pixel_multiplier =
8310                         ((tmp & SDVO_MULTIPLIER_MASK)
8311                          >> SDVO_MULTIPLIER_SHIFT_HIRES) + 1;
8312         } else {
8313                 /* Note that on i915G/GM the pixel multiplier is in the sdvo
8314                  * port and will be fixed up in the encoder->get_config
8315                  * function. */
8316                 pipe_config->pixel_multiplier = 1;
8317         }
8318         pipe_config->dpll_hw_state.dpll = I915_READ(DPLL(crtc->pipe));
8319         if (!IS_VALLEYVIEW(dev) && !IS_CHERRYVIEW(dev)) {
8320                 /*
8321                  * DPLL_DVO_2X_MODE must be enabled for both DPLLs
8322                  * on 830. Filter it out here so that we don't
8323                  * report errors due to that.
8324                  */
8325                 if (IS_I830(dev))
8326                         pipe_config->dpll_hw_state.dpll &= ~DPLL_DVO_2X_MODE;
8327
8328                 pipe_config->dpll_hw_state.fp0 = I915_READ(FP0(crtc->pipe));
8329                 pipe_config->dpll_hw_state.fp1 = I915_READ(FP1(crtc->pipe));
8330         } else {
8331                 /* Mask out read-only status bits. */
8332                 pipe_config->dpll_hw_state.dpll &= ~(DPLL_LOCK_VLV |
8333                                                      DPLL_PORTC_READY_MASK |
8334                                                      DPLL_PORTB_READY_MASK);
8335         }
8336
8337         if (IS_CHERRYVIEW(dev))
8338                 chv_crtc_clock_get(crtc, pipe_config);
8339         else if (IS_VALLEYVIEW(dev))
8340                 vlv_crtc_clock_get(crtc, pipe_config);
8341         else
8342                 i9xx_crtc_clock_get(crtc, pipe_config);
8343
8344         /*
8345          * Normally the dotclock is filled in by the encoder .get_config()
8346          * but in case the pipe is enabled w/o any ports we need a sane
8347          * default.
8348          */
8349         pipe_config->base.adjusted_mode.crtc_clock =
8350                 pipe_config->port_clock / pipe_config->pixel_multiplier;
8351
8352         ret = true;
8353
8354 out:
8355         intel_display_power_put(dev_priv, power_domain);
8356
8357         return ret;
8358 }
8359
8360 static void ironlake_init_pch_refclk(struct drm_device *dev)
8361 {
8362         struct drm_i915_private *dev_priv = dev->dev_private;
8363         struct intel_encoder *encoder;
8364         u32 val, final;
8365         bool has_lvds = false;
8366         bool has_cpu_edp = false;
8367         bool has_panel = false;
8368         bool has_ck505 = false;
8369         bool can_ssc = false;
8370
8371         /* We need to take the global config into account */
8372         for_each_intel_encoder(dev, encoder) {
8373                 switch (encoder->type) {
8374                 case INTEL_OUTPUT_LVDS:
8375                         has_panel = true;
8376                         has_lvds = true;
8377                         break;
8378                 case INTEL_OUTPUT_EDP:
8379                         has_panel = true;
8380                         if (enc_to_dig_port(&encoder->base)->port == PORT_A)
8381                                 has_cpu_edp = true;
8382                         break;
8383                 default:
8384                         break;
8385                 }
8386         }
8387
8388         if (HAS_PCH_IBX(dev)) {
8389                 has_ck505 = dev_priv->vbt.display_clock_mode;
8390                 can_ssc = has_ck505;
8391         } else {
8392                 has_ck505 = false;
8393                 can_ssc = true;
8394         }
8395
8396         DRM_DEBUG_KMS("has_panel %d has_lvds %d has_ck505 %d\n",
8397                       has_panel, has_lvds, has_ck505);
8398
8399         /* Ironlake: try to setup display ref clock before DPLL
8400          * enabling. This is only under driver's control after
8401          * PCH B stepping, previous chipset stepping should be
8402          * ignoring this setting.
8403          */
8404         val = I915_READ(PCH_DREF_CONTROL);
8405
8406         /* As we must carefully and slowly disable/enable each source in turn,
8407          * compute the final state we want first and check if we need to
8408          * make any changes at all.
8409          */
8410         final = val;
8411         final &= ~DREF_NONSPREAD_SOURCE_MASK;
8412         if (has_ck505)
8413                 final |= DREF_NONSPREAD_CK505_ENABLE;
8414         else
8415                 final |= DREF_NONSPREAD_SOURCE_ENABLE;
8416
8417         final &= ~DREF_SSC_SOURCE_MASK;
8418         final &= ~DREF_CPU_SOURCE_OUTPUT_MASK;
8419         final &= ~DREF_SSC1_ENABLE;
8420
8421         if (has_panel) {
8422                 final |= DREF_SSC_SOURCE_ENABLE;
8423
8424                 if (intel_panel_use_ssc(dev_priv) && can_ssc)
8425                         final |= DREF_SSC1_ENABLE;
8426
8427                 if (has_cpu_edp) {
8428                         if (intel_panel_use_ssc(dev_priv) && can_ssc)
8429                                 final |= DREF_CPU_SOURCE_OUTPUT_DOWNSPREAD;
8430                         else
8431                                 final |= DREF_CPU_SOURCE_OUTPUT_NONSPREAD;
8432                 } else
8433                         final |= DREF_CPU_SOURCE_OUTPUT_DISABLE;
8434         } else {
8435                 final |= DREF_SSC_SOURCE_DISABLE;
8436                 final |= DREF_CPU_SOURCE_OUTPUT_DISABLE;
8437         }
8438
8439         if (final == val)
8440                 return;
8441
8442         /* Always enable nonspread source */
8443         val &= ~DREF_NONSPREAD_SOURCE_MASK;
8444
8445         if (has_ck505)
8446                 val |= DREF_NONSPREAD_CK505_ENABLE;
8447         else
8448                 val |= DREF_NONSPREAD_SOURCE_ENABLE;
8449
8450         if (has_panel) {
8451                 val &= ~DREF_SSC_SOURCE_MASK;
8452                 val |= DREF_SSC_SOURCE_ENABLE;
8453
8454                 /* SSC must be turned on before enabling the CPU output  */
8455                 if (intel_panel_use_ssc(dev_priv) && can_ssc) {
8456                         DRM_DEBUG_KMS("Using SSC on panel\n");
8457                         val |= DREF_SSC1_ENABLE;
8458                 } else
8459                         val &= ~DREF_SSC1_ENABLE;
8460
8461                 /* Get SSC going before enabling the outputs */
8462                 I915_WRITE(PCH_DREF_CONTROL, val);
8463                 POSTING_READ(PCH_DREF_CONTROL);
8464                 udelay(200);
8465
8466                 val &= ~DREF_CPU_SOURCE_OUTPUT_MASK;
8467
8468                 /* Enable CPU source on CPU attached eDP */
8469                 if (has_cpu_edp) {
8470                         if (intel_panel_use_ssc(dev_priv) && can_ssc) {
8471                                 DRM_DEBUG_KMS("Using SSC on eDP\n");
8472                                 val |= DREF_CPU_SOURCE_OUTPUT_DOWNSPREAD;
8473                         } else
8474                                 val |= DREF_CPU_SOURCE_OUTPUT_NONSPREAD;
8475                 } else
8476                         val |= DREF_CPU_SOURCE_OUTPUT_DISABLE;
8477
8478                 I915_WRITE(PCH_DREF_CONTROL, val);
8479                 POSTING_READ(PCH_DREF_CONTROL);
8480                 udelay(200);
8481         } else {
8482                 DRM_DEBUG_KMS("Disabling SSC entirely\n");
8483
8484                 val &= ~DREF_CPU_SOURCE_OUTPUT_MASK;
8485
8486                 /* Turn off CPU output */
8487                 val |= DREF_CPU_SOURCE_OUTPUT_DISABLE;
8488
8489                 I915_WRITE(PCH_DREF_CONTROL, val);
8490                 POSTING_READ(PCH_DREF_CONTROL);
8491                 udelay(200);
8492
8493                 /* Turn off the SSC source */
8494                 val &= ~DREF_SSC_SOURCE_MASK;
8495                 val |= DREF_SSC_SOURCE_DISABLE;
8496
8497                 /* Turn off SSC1 */
8498                 val &= ~DREF_SSC1_ENABLE;
8499
8500                 I915_WRITE(PCH_DREF_CONTROL, val);
8501                 POSTING_READ(PCH_DREF_CONTROL);
8502                 udelay(200);
8503         }
8504
8505         BUG_ON(val != final);
8506 }
8507
8508 static void lpt_reset_fdi_mphy(struct drm_i915_private *dev_priv)
8509 {
8510         uint32_t tmp;
8511
8512         tmp = I915_READ(SOUTH_CHICKEN2);
8513         tmp |= FDI_MPHY_IOSFSB_RESET_CTL;
8514         I915_WRITE(SOUTH_CHICKEN2, tmp);
8515
8516         if (wait_for_atomic_us(I915_READ(SOUTH_CHICKEN2) &
8517                                FDI_MPHY_IOSFSB_RESET_STATUS, 100))
8518                 DRM_ERROR("FDI mPHY reset assert timeout\n");
8519
8520         tmp = I915_READ(SOUTH_CHICKEN2);
8521         tmp &= ~FDI_MPHY_IOSFSB_RESET_CTL;
8522         I915_WRITE(SOUTH_CHICKEN2, tmp);
8523
8524         if (wait_for_atomic_us((I915_READ(SOUTH_CHICKEN2) &
8525                                 FDI_MPHY_IOSFSB_RESET_STATUS) == 0, 100))
8526                 DRM_ERROR("FDI mPHY reset de-assert timeout\n");
8527 }
8528
8529 /* WaMPhyProgramming:hsw */
8530 static void lpt_program_fdi_mphy(struct drm_i915_private *dev_priv)
8531 {
8532         uint32_t tmp;
8533
8534         tmp = intel_sbi_read(dev_priv, 0x8008, SBI_MPHY);
8535         tmp &= ~(0xFF << 24);
8536         tmp |= (0x12 << 24);
8537         intel_sbi_write(dev_priv, 0x8008, tmp, SBI_MPHY);
8538
8539         tmp = intel_sbi_read(dev_priv, 0x2008, SBI_MPHY);
8540         tmp |= (1 << 11);
8541         intel_sbi_write(dev_priv, 0x2008, tmp, SBI_MPHY);
8542
8543         tmp = intel_sbi_read(dev_priv, 0x2108, SBI_MPHY);
8544         tmp |= (1 << 11);
8545         intel_sbi_write(dev_priv, 0x2108, tmp, SBI_MPHY);
8546
8547         tmp = intel_sbi_read(dev_priv, 0x206C, SBI_MPHY);
8548         tmp |= (1 << 24) | (1 << 21) | (1 << 18);
8549         intel_sbi_write(dev_priv, 0x206C, tmp, SBI_MPHY);
8550
8551         tmp = intel_sbi_read(dev_priv, 0x216C, SBI_MPHY);
8552         tmp |= (1 << 24) | (1 << 21) | (1 << 18);
8553         intel_sbi_write(dev_priv, 0x216C, tmp, SBI_MPHY);
8554
8555         tmp = intel_sbi_read(dev_priv, 0x2080, SBI_MPHY);
8556         tmp &= ~(7 << 13);
8557         tmp |= (5 << 13);
8558         intel_sbi_write(dev_priv, 0x2080, tmp, SBI_MPHY);
8559
8560         tmp = intel_sbi_read(dev_priv, 0x2180, SBI_MPHY);
8561         tmp &= ~(7 << 13);
8562         tmp |= (5 << 13);
8563         intel_sbi_write(dev_priv, 0x2180, tmp, SBI_MPHY);
8564
8565         tmp = intel_sbi_read(dev_priv, 0x208C, SBI_MPHY);
8566         tmp &= ~0xFF;
8567         tmp |= 0x1C;
8568         intel_sbi_write(dev_priv, 0x208C, tmp, SBI_MPHY);
8569
8570         tmp = intel_sbi_read(dev_priv, 0x218C, SBI_MPHY);
8571         tmp &= ~0xFF;
8572         tmp |= 0x1C;
8573         intel_sbi_write(dev_priv, 0x218C, tmp, SBI_MPHY);
8574
8575         tmp = intel_sbi_read(dev_priv, 0x2098, SBI_MPHY);
8576         tmp &= ~(0xFF << 16);
8577         tmp |= (0x1C << 16);
8578         intel_sbi_write(dev_priv, 0x2098, tmp, SBI_MPHY);
8579
8580         tmp = intel_sbi_read(dev_priv, 0x2198, SBI_MPHY);
8581         tmp &= ~(0xFF << 16);
8582         tmp |= (0x1C << 16);
8583         intel_sbi_write(dev_priv, 0x2198, tmp, SBI_MPHY);
8584
8585         tmp = intel_sbi_read(dev_priv, 0x20C4, SBI_MPHY);
8586         tmp |= (1 << 27);
8587         intel_sbi_write(dev_priv, 0x20C4, tmp, SBI_MPHY);
8588
8589         tmp = intel_sbi_read(dev_priv, 0x21C4, SBI_MPHY);
8590         tmp |= (1 << 27);
8591         intel_sbi_write(dev_priv, 0x21C4, tmp, SBI_MPHY);
8592
8593         tmp = intel_sbi_read(dev_priv, 0x20EC, SBI_MPHY);
8594         tmp &= ~(0xF << 28);
8595         tmp |= (4 << 28);
8596         intel_sbi_write(dev_priv, 0x20EC, tmp, SBI_MPHY);
8597
8598         tmp = intel_sbi_read(dev_priv, 0x21EC, SBI_MPHY);
8599         tmp &= ~(0xF << 28);
8600         tmp |= (4 << 28);
8601         intel_sbi_write(dev_priv, 0x21EC, tmp, SBI_MPHY);
8602 }
8603
8604 /* Implements 3 different sequences from BSpec chapter "Display iCLK
8605  * Programming" based on the parameters passed:
8606  * - Sequence to enable CLKOUT_DP
8607  * - Sequence to enable CLKOUT_DP without spread
8608  * - Sequence to enable CLKOUT_DP for FDI usage and configure PCH FDI I/O
8609  */
8610 static void lpt_enable_clkout_dp(struct drm_device *dev, bool with_spread,
8611                                  bool with_fdi)
8612 {
8613         struct drm_i915_private *dev_priv = dev->dev_private;
8614         uint32_t reg, tmp;
8615
8616         if (WARN(with_fdi && !with_spread, "FDI requires downspread\n"))
8617                 with_spread = true;
8618         if (WARN(HAS_PCH_LPT_LP(dev) && with_fdi, "LP PCH doesn't have FDI\n"))
8619                 with_fdi = false;
8620
8621         mutex_lock(&dev_priv->sb_lock);
8622
8623         tmp = intel_sbi_read(dev_priv, SBI_SSCCTL, SBI_ICLK);
8624         tmp &= ~SBI_SSCCTL_DISABLE;
8625         tmp |= SBI_SSCCTL_PATHALT;
8626         intel_sbi_write(dev_priv, SBI_SSCCTL, tmp, SBI_ICLK);
8627
8628         udelay(24);
8629
8630         if (with_spread) {
8631                 tmp = intel_sbi_read(dev_priv, SBI_SSCCTL, SBI_ICLK);
8632                 tmp &= ~SBI_SSCCTL_PATHALT;
8633                 intel_sbi_write(dev_priv, SBI_SSCCTL, tmp, SBI_ICLK);
8634
8635                 if (with_fdi) {
8636                         lpt_reset_fdi_mphy(dev_priv);
8637                         lpt_program_fdi_mphy(dev_priv);
8638                 }
8639         }
8640
8641         reg = HAS_PCH_LPT_LP(dev) ? SBI_GEN0 : SBI_DBUFF0;
8642         tmp = intel_sbi_read(dev_priv, reg, SBI_ICLK);
8643         tmp |= SBI_GEN0_CFG_BUFFENABLE_DISABLE;
8644         intel_sbi_write(dev_priv, reg, tmp, SBI_ICLK);
8645
8646         mutex_unlock(&dev_priv->sb_lock);
8647 }
8648
8649 /* Sequence to disable CLKOUT_DP */
8650 static void lpt_disable_clkout_dp(struct drm_device *dev)
8651 {
8652         struct drm_i915_private *dev_priv = dev->dev_private;
8653         uint32_t reg, tmp;
8654
8655         mutex_lock(&dev_priv->sb_lock);
8656
8657         reg = HAS_PCH_LPT_LP(dev) ? SBI_GEN0 : SBI_DBUFF0;
8658         tmp = intel_sbi_read(dev_priv, reg, SBI_ICLK);
8659         tmp &= ~SBI_GEN0_CFG_BUFFENABLE_DISABLE;
8660         intel_sbi_write(dev_priv, reg, tmp, SBI_ICLK);
8661
8662         tmp = intel_sbi_read(dev_priv, SBI_SSCCTL, SBI_ICLK);
8663         if (!(tmp & SBI_SSCCTL_DISABLE)) {
8664                 if (!(tmp & SBI_SSCCTL_PATHALT)) {
8665                         tmp |= SBI_SSCCTL_PATHALT;
8666                         intel_sbi_write(dev_priv, SBI_SSCCTL, tmp, SBI_ICLK);
8667                         udelay(32);
8668                 }
8669                 tmp |= SBI_SSCCTL_DISABLE;
8670                 intel_sbi_write(dev_priv, SBI_SSCCTL, tmp, SBI_ICLK);
8671         }
8672
8673         mutex_unlock(&dev_priv->sb_lock);
8674 }
8675
8676 #define BEND_IDX(steps) ((50 + (steps)) / 5)
8677
8678 static const uint16_t sscdivintphase[] = {
8679         [BEND_IDX( 50)] = 0x3B23,
8680         [BEND_IDX( 45)] = 0x3B23,
8681         [BEND_IDX( 40)] = 0x3C23,
8682         [BEND_IDX( 35)] = 0x3C23,
8683         [BEND_IDX( 30)] = 0x3D23,
8684         [BEND_IDX( 25)] = 0x3D23,
8685         [BEND_IDX( 20)] = 0x3E23,
8686         [BEND_IDX( 15)] = 0x3E23,
8687         [BEND_IDX( 10)] = 0x3F23,
8688         [BEND_IDX(  5)] = 0x3F23,
8689         [BEND_IDX(  0)] = 0x0025,
8690         [BEND_IDX( -5)] = 0x0025,
8691         [BEND_IDX(-10)] = 0x0125,
8692         [BEND_IDX(-15)] = 0x0125,
8693         [BEND_IDX(-20)] = 0x0225,
8694         [BEND_IDX(-25)] = 0x0225,
8695         [BEND_IDX(-30)] = 0x0325,
8696         [BEND_IDX(-35)] = 0x0325,
8697         [BEND_IDX(-40)] = 0x0425,
8698         [BEND_IDX(-45)] = 0x0425,
8699         [BEND_IDX(-50)] = 0x0525,
8700 };
8701
8702 /*
8703  * Bend CLKOUT_DP
8704  * steps -50 to 50 inclusive, in steps of 5
8705  * < 0 slow down the clock, > 0 speed up the clock, 0 == no bend (135MHz)
8706  * change in clock period = -(steps / 10) * 5.787 ps
8707  */
8708 static void lpt_bend_clkout_dp(struct drm_i915_private *dev_priv, int steps)
8709 {
8710         uint32_t tmp;
8711         int idx = BEND_IDX(steps);
8712
8713         if (WARN_ON(steps % 5 != 0))
8714                 return;
8715
8716         if (WARN_ON(idx >= ARRAY_SIZE(sscdivintphase)))
8717                 return;
8718
8719         mutex_lock(&dev_priv->sb_lock);
8720
8721         if (steps % 10 != 0)
8722                 tmp = 0xAAAAAAAB;
8723         else
8724                 tmp = 0x00000000;
8725         intel_sbi_write(dev_priv, SBI_SSCDITHPHASE, tmp, SBI_ICLK);
8726
8727         tmp = intel_sbi_read(dev_priv, SBI_SSCDIVINTPHASE, SBI_ICLK);
8728         tmp &= 0xffff0000;
8729         tmp |= sscdivintphase[idx];
8730         intel_sbi_write(dev_priv, SBI_SSCDIVINTPHASE, tmp, SBI_ICLK);
8731
8732         mutex_unlock(&dev_priv->sb_lock);
8733 }
8734
8735 #undef BEND_IDX
8736
8737 static void lpt_init_pch_refclk(struct drm_device *dev)
8738 {
8739         struct intel_encoder *encoder;
8740         bool has_vga = false;
8741
8742         for_each_intel_encoder(dev, encoder) {
8743                 switch (encoder->type) {
8744                 case INTEL_OUTPUT_ANALOG:
8745                         has_vga = true;
8746                         break;
8747                 default:
8748                         break;
8749                 }
8750         }
8751
8752         if (has_vga) {
8753                 lpt_bend_clkout_dp(to_i915(dev), 0);
8754                 lpt_enable_clkout_dp(dev, true, true);
8755         } else {
8756                 lpt_disable_clkout_dp(dev);
8757         }
8758 }
8759
8760 /*
8761  * Initialize reference clocks when the driver loads
8762  */
8763 void intel_init_pch_refclk(struct drm_device *dev)
8764 {
8765         if (HAS_PCH_IBX(dev) || HAS_PCH_CPT(dev))
8766                 ironlake_init_pch_refclk(dev);
8767         else if (HAS_PCH_LPT(dev))
8768                 lpt_init_pch_refclk(dev);
8769 }
8770
8771 static void ironlake_set_pipeconf(struct drm_crtc *crtc)
8772 {
8773         struct drm_i915_private *dev_priv = crtc->dev->dev_private;
8774         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
8775         int pipe = intel_crtc->pipe;
8776         uint32_t val;
8777
8778         val = 0;
8779
8780         switch (intel_crtc->config->pipe_bpp) {
8781         case 18:
8782                 val |= PIPECONF_6BPC;
8783                 break;
8784         case 24:
8785                 val |= PIPECONF_8BPC;
8786                 break;
8787         case 30:
8788                 val |= PIPECONF_10BPC;
8789                 break;
8790         case 36:
8791                 val |= PIPECONF_12BPC;
8792                 break;
8793         default:
8794                 /* Case prevented by intel_choose_pipe_bpp_dither. */
8795                 BUG();
8796         }
8797
8798         if (intel_crtc->config->dither)
8799                 val |= (PIPECONF_DITHER_EN | PIPECONF_DITHER_TYPE_SP);
8800
8801         if (intel_crtc->config->base.adjusted_mode.flags & DRM_MODE_FLAG_INTERLACE)
8802                 val |= PIPECONF_INTERLACED_ILK;
8803         else
8804                 val |= PIPECONF_PROGRESSIVE;
8805
8806         if (intel_crtc->config->limited_color_range)
8807                 val |= PIPECONF_COLOR_RANGE_SELECT;
8808
8809         I915_WRITE(PIPECONF(pipe), val);
8810         POSTING_READ(PIPECONF(pipe));
8811 }
8812
8813 static void haswell_set_pipeconf(struct drm_crtc *crtc)
8814 {
8815         struct drm_i915_private *dev_priv = crtc->dev->dev_private;
8816         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
8817         enum transcoder cpu_transcoder = intel_crtc->config->cpu_transcoder;
8818         u32 val = 0;
8819
8820         if (IS_HASWELL(dev_priv) && intel_crtc->config->dither)
8821                 val |= (PIPECONF_DITHER_EN | PIPECONF_DITHER_TYPE_SP);
8822
8823         if (intel_crtc->config->base.adjusted_mode.flags & DRM_MODE_FLAG_INTERLACE)
8824                 val |= PIPECONF_INTERLACED_ILK;
8825         else
8826                 val |= PIPECONF_PROGRESSIVE;
8827
8828         I915_WRITE(PIPECONF(cpu_transcoder), val);
8829         POSTING_READ(PIPECONF(cpu_transcoder));
8830 }
8831
8832 static void haswell_set_pipemisc(struct drm_crtc *crtc)
8833 {
8834         struct drm_i915_private *dev_priv = crtc->dev->dev_private;
8835         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
8836
8837         if (IS_BROADWELL(dev_priv) || INTEL_INFO(dev_priv)->gen >= 9) {
8838                 u32 val = 0;
8839
8840                 switch (intel_crtc->config->pipe_bpp) {
8841                 case 18:
8842                         val |= PIPEMISC_DITHER_6_BPC;
8843                         break;
8844                 case 24:
8845                         val |= PIPEMISC_DITHER_8_BPC;
8846                         break;
8847                 case 30:
8848                         val |= PIPEMISC_DITHER_10_BPC;
8849                         break;
8850                 case 36:
8851                         val |= PIPEMISC_DITHER_12_BPC;
8852                         break;
8853                 default:
8854                         /* Case prevented by pipe_config_set_bpp. */
8855                         BUG();
8856                 }
8857
8858                 if (intel_crtc->config->dither)
8859                         val |= PIPEMISC_DITHER_ENABLE | PIPEMISC_DITHER_TYPE_SP;
8860
8861                 I915_WRITE(PIPEMISC(intel_crtc->pipe), val);
8862         }
8863 }
8864
8865 int ironlake_get_lanes_required(int target_clock, int link_bw, int bpp)
8866 {
8867         /*
8868          * Account for spread spectrum to avoid
8869          * oversubscribing the link. Max center spread
8870          * is 2.5%; use 5% for safety's sake.
8871          */
8872         u32 bps = target_clock * bpp * 21 / 20;
8873         return DIV_ROUND_UP(bps, link_bw * 8);
8874 }
8875
8876 static bool ironlake_needs_fb_cb_tune(struct dpll *dpll, int factor)
8877 {
8878         return i9xx_dpll_compute_m(dpll) < factor * dpll->n;
8879 }
8880
8881 static void ironlake_compute_dpll(struct intel_crtc *intel_crtc,
8882                                   struct intel_crtc_state *crtc_state,
8883                                   struct dpll *reduced_clock)
8884 {
8885         struct drm_crtc *crtc = &intel_crtc->base;
8886         struct drm_device *dev = crtc->dev;
8887         struct drm_i915_private *dev_priv = dev->dev_private;
8888         struct drm_atomic_state *state = crtc_state->base.state;
8889         struct drm_connector *connector;
8890         struct drm_connector_state *connector_state;
8891         struct intel_encoder *encoder;
8892         u32 dpll, fp, fp2;
8893         int factor, i;
8894         bool is_lvds = false, is_sdvo = false;
8895
8896         for_each_connector_in_state(state, connector, connector_state, i) {
8897                 if (connector_state->crtc != crtc_state->base.crtc)
8898                         continue;
8899
8900                 encoder = to_intel_encoder(connector_state->best_encoder);
8901
8902                 switch (encoder->type) {
8903                 case INTEL_OUTPUT_LVDS:
8904                         is_lvds = true;
8905                         break;
8906                 case INTEL_OUTPUT_SDVO:
8907                 case INTEL_OUTPUT_HDMI:
8908                         is_sdvo = true;
8909                         break;
8910                 default:
8911                         break;
8912                 }
8913         }
8914
8915         /* Enable autotuning of the PLL clock (if permissible) */
8916         factor = 21;
8917         if (is_lvds) {
8918                 if ((intel_panel_use_ssc(dev_priv) &&
8919                      dev_priv->vbt.lvds_ssc_freq == 100000) ||
8920                     (HAS_PCH_IBX(dev) && intel_is_dual_link_lvds(dev)))
8921                         factor = 25;
8922         } else if (crtc_state->sdvo_tv_clock)
8923                 factor = 20;
8924
8925         fp = i9xx_dpll_compute_fp(&crtc_state->dpll);
8926
8927         if (ironlake_needs_fb_cb_tune(&crtc_state->dpll, factor))
8928                 fp |= FP_CB_TUNE;
8929
8930         if (reduced_clock) {
8931                 fp2 = i9xx_dpll_compute_fp(reduced_clock);
8932
8933                 if (reduced_clock->m < factor * reduced_clock->n)
8934                         fp2 |= FP_CB_TUNE;
8935         } else {
8936                 fp2 = fp;
8937         }
8938
8939         dpll = 0;
8940
8941         if (is_lvds)
8942                 dpll |= DPLLB_MODE_LVDS;
8943         else
8944                 dpll |= DPLLB_MODE_DAC_SERIAL;
8945
8946         dpll |= (crtc_state->pixel_multiplier - 1)
8947                 << PLL_REF_SDVO_HDMI_MULTIPLIER_SHIFT;
8948
8949         if (is_sdvo)
8950                 dpll |= DPLL_SDVO_HIGH_SPEED;
8951         if (crtc_state->has_dp_encoder)
8952                 dpll |= DPLL_SDVO_HIGH_SPEED;
8953
8954         /* compute bitmask from p1 value */
8955         dpll |= (1 << (crtc_state->dpll.p1 - 1)) << DPLL_FPA01_P1_POST_DIV_SHIFT;
8956         /* also FPA1 */
8957         dpll |= (1 << (crtc_state->dpll.p1 - 1)) << DPLL_FPA1_P1_POST_DIV_SHIFT;
8958
8959         switch (crtc_state->dpll.p2) {
8960         case 5:
8961                 dpll |= DPLL_DAC_SERIAL_P2_CLOCK_DIV_5;
8962                 break;
8963         case 7:
8964                 dpll |= DPLLB_LVDS_P2_CLOCK_DIV_7;
8965                 break;
8966         case 10:
8967                 dpll |= DPLL_DAC_SERIAL_P2_CLOCK_DIV_10;
8968                 break;
8969         case 14:
8970                 dpll |= DPLLB_LVDS_P2_CLOCK_DIV_14;
8971                 break;
8972         }
8973
8974         if (is_lvds && intel_panel_use_ssc(dev_priv))
8975                 dpll |= PLLB_REF_INPUT_SPREADSPECTRUMIN;
8976         else
8977                 dpll |= PLL_REF_INPUT_DREFCLK;
8978
8979         dpll |= DPLL_VCO_ENABLE;
8980
8981         crtc_state->dpll_hw_state.dpll = dpll;
8982         crtc_state->dpll_hw_state.fp0 = fp;
8983         crtc_state->dpll_hw_state.fp1 = fp2;
8984 }
8985
8986 static int ironlake_crtc_compute_clock(struct intel_crtc *crtc,
8987                                        struct intel_crtc_state *crtc_state)
8988 {
8989         struct drm_device *dev = crtc->base.dev;
8990         struct drm_i915_private *dev_priv = dev->dev_private;
8991         struct dpll reduced_clock;
8992         bool has_reduced_clock = false;
8993         struct intel_shared_dpll *pll;
8994         const struct intel_limit *limit;
8995         int refclk = 120000;
8996
8997         memset(&crtc_state->dpll_hw_state, 0,
8998                sizeof(crtc_state->dpll_hw_state));
8999
9000         crtc->lowfreq_avail = false;
9001
9002         /* CPU eDP is the only output that doesn't need a PCH PLL of its own. */
9003         if (!crtc_state->has_pch_encoder)
9004                 return 0;
9005
9006         if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_LVDS)) {
9007                 if (intel_panel_use_ssc(dev_priv)) {
9008                         DRM_DEBUG_KMS("using SSC reference clock of %d kHz\n",
9009                                       dev_priv->vbt.lvds_ssc_freq);
9010                         refclk = dev_priv->vbt.lvds_ssc_freq;
9011                 }
9012
9013                 if (intel_is_dual_link_lvds(dev)) {
9014                         if (refclk == 100000)
9015                                 limit = &intel_limits_ironlake_dual_lvds_100m;
9016                         else
9017                                 limit = &intel_limits_ironlake_dual_lvds;
9018                 } else {
9019                         if (refclk == 100000)
9020                                 limit = &intel_limits_ironlake_single_lvds_100m;
9021                         else
9022                                 limit = &intel_limits_ironlake_single_lvds;
9023                 }
9024         } else {
9025                 limit = &intel_limits_ironlake_dac;
9026         }
9027
9028         if (!crtc_state->clock_set &&
9029             !g4x_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
9030                                 refclk, NULL, &crtc_state->dpll)) {
9031                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
9032                 return -EINVAL;
9033         }
9034
9035         ironlake_compute_dpll(crtc, crtc_state,
9036                               has_reduced_clock ? &reduced_clock : NULL);
9037
9038         pll = intel_get_shared_dpll(crtc, crtc_state, NULL);
9039         if (pll == NULL) {
9040                 DRM_DEBUG_DRIVER("failed to find PLL for pipe %c\n",
9041                                  pipe_name(crtc->pipe));
9042                 return -EINVAL;
9043         }
9044
9045         if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_LVDS) &&
9046             has_reduced_clock)
9047                 crtc->lowfreq_avail = true;
9048
9049         return 0;
9050 }
9051
9052 static void intel_pch_transcoder_get_m_n(struct intel_crtc *crtc,
9053                                          struct intel_link_m_n *m_n)
9054 {
9055         struct drm_device *dev = crtc->base.dev;
9056         struct drm_i915_private *dev_priv = dev->dev_private;
9057         enum pipe pipe = crtc->pipe;
9058
9059         m_n->link_m = I915_READ(PCH_TRANS_LINK_M1(pipe));
9060         m_n->link_n = I915_READ(PCH_TRANS_LINK_N1(pipe));
9061         m_n->gmch_m = I915_READ(PCH_TRANS_DATA_M1(pipe))
9062                 & ~TU_SIZE_MASK;
9063         m_n->gmch_n = I915_READ(PCH_TRANS_DATA_N1(pipe));
9064         m_n->tu = ((I915_READ(PCH_TRANS_DATA_M1(pipe))
9065                     & TU_SIZE_MASK) >> TU_SIZE_SHIFT) + 1;
9066 }
9067
9068 static void intel_cpu_transcoder_get_m_n(struct intel_crtc *crtc,
9069                                          enum transcoder transcoder,
9070                                          struct intel_link_m_n *m_n,
9071                                          struct intel_link_m_n *m2_n2)
9072 {
9073         struct drm_device *dev = crtc->base.dev;
9074         struct drm_i915_private *dev_priv = dev->dev_private;
9075         enum pipe pipe = crtc->pipe;
9076
9077         if (INTEL_INFO(dev)->gen >= 5) {
9078                 m_n->link_m = I915_READ(PIPE_LINK_M1(transcoder));
9079                 m_n->link_n = I915_READ(PIPE_LINK_N1(transcoder));
9080                 m_n->gmch_m = I915_READ(PIPE_DATA_M1(transcoder))
9081                         & ~TU_SIZE_MASK;
9082                 m_n->gmch_n = I915_READ(PIPE_DATA_N1(transcoder));
9083                 m_n->tu = ((I915_READ(PIPE_DATA_M1(transcoder))
9084                             & TU_SIZE_MASK) >> TU_SIZE_SHIFT) + 1;
9085                 /* Read M2_N2 registers only for gen < 8 (M2_N2 available for
9086                  * gen < 8) and if DRRS is supported (to make sure the
9087                  * registers are not unnecessarily read).
9088                  */
9089                 if (m2_n2 && INTEL_INFO(dev)->gen < 8 &&
9090                         crtc->config->has_drrs) {
9091                         m2_n2->link_m = I915_READ(PIPE_LINK_M2(transcoder));
9092                         m2_n2->link_n = I915_READ(PIPE_LINK_N2(transcoder));
9093                         m2_n2->gmch_m = I915_READ(PIPE_DATA_M2(transcoder))
9094                                         & ~TU_SIZE_MASK;
9095                         m2_n2->gmch_n = I915_READ(PIPE_DATA_N2(transcoder));
9096                         m2_n2->tu = ((I915_READ(PIPE_DATA_M2(transcoder))
9097                                         & TU_SIZE_MASK) >> TU_SIZE_SHIFT) + 1;
9098                 }
9099         } else {
9100                 m_n->link_m = I915_READ(PIPE_LINK_M_G4X(pipe));
9101                 m_n->link_n = I915_READ(PIPE_LINK_N_G4X(pipe));
9102                 m_n->gmch_m = I915_READ(PIPE_DATA_M_G4X(pipe))
9103                         & ~TU_SIZE_MASK;
9104                 m_n->gmch_n = I915_READ(PIPE_DATA_N_G4X(pipe));
9105                 m_n->tu = ((I915_READ(PIPE_DATA_M_G4X(pipe))
9106                             & TU_SIZE_MASK) >> TU_SIZE_SHIFT) + 1;
9107         }
9108 }
9109
9110 void intel_dp_get_m_n(struct intel_crtc *crtc,
9111                       struct intel_crtc_state *pipe_config)
9112 {
9113         if (pipe_config->has_pch_encoder)
9114                 intel_pch_transcoder_get_m_n(crtc, &pipe_config->dp_m_n);
9115         else
9116                 intel_cpu_transcoder_get_m_n(crtc, pipe_config->cpu_transcoder,
9117                                              &pipe_config->dp_m_n,
9118                                              &pipe_config->dp_m2_n2);
9119 }
9120
9121 static void ironlake_get_fdi_m_n_config(struct intel_crtc *crtc,
9122                                         struct intel_crtc_state *pipe_config)
9123 {
9124         intel_cpu_transcoder_get_m_n(crtc, pipe_config->cpu_transcoder,
9125                                      &pipe_config->fdi_m_n, NULL);
9126 }
9127
9128 static void skylake_get_pfit_config(struct intel_crtc *crtc,
9129                                     struct intel_crtc_state *pipe_config)
9130 {
9131         struct drm_device *dev = crtc->base.dev;
9132         struct drm_i915_private *dev_priv = dev->dev_private;
9133         struct intel_crtc_scaler_state *scaler_state = &pipe_config->scaler_state;
9134         uint32_t ps_ctrl = 0;
9135         int id = -1;
9136         int i;
9137
9138         /* find scaler attached to this pipe */
9139         for (i = 0; i < crtc->num_scalers; i++) {
9140                 ps_ctrl = I915_READ(SKL_PS_CTRL(crtc->pipe, i));
9141                 if (ps_ctrl & PS_SCALER_EN && !(ps_ctrl & PS_PLANE_SEL_MASK)) {
9142                         id = i;
9143                         pipe_config->pch_pfit.enabled = true;
9144                         pipe_config->pch_pfit.pos = I915_READ(SKL_PS_WIN_POS(crtc->pipe, i));
9145                         pipe_config->pch_pfit.size = I915_READ(SKL_PS_WIN_SZ(crtc->pipe, i));
9146                         break;
9147                 }
9148         }
9149
9150         scaler_state->scaler_id = id;
9151         if (id >= 0) {
9152                 scaler_state->scaler_users |= (1 << SKL_CRTC_INDEX);
9153         } else {
9154                 scaler_state->scaler_users &= ~(1 << SKL_CRTC_INDEX);
9155         }
9156 }
9157
9158 static void
9159 skylake_get_initial_plane_config(struct intel_crtc *crtc,
9160                                  struct intel_initial_plane_config *plane_config)
9161 {
9162         struct drm_device *dev = crtc->base.dev;
9163         struct drm_i915_private *dev_priv = dev->dev_private;
9164         u32 val, base, offset, stride_mult, tiling;
9165         int pipe = crtc->pipe;
9166         int fourcc, pixel_format;
9167         unsigned int aligned_height;
9168         struct drm_framebuffer *fb;
9169         struct intel_framebuffer *intel_fb;
9170
9171         intel_fb = kzalloc(sizeof(*intel_fb), GFP_KERNEL);
9172         if (!intel_fb) {
9173                 DRM_DEBUG_KMS("failed to alloc fb\n");
9174                 return;
9175         }
9176
9177         fb = &intel_fb->base;
9178
9179         val = I915_READ(PLANE_CTL(pipe, 0));
9180         if (!(val & PLANE_CTL_ENABLE))
9181                 goto error;
9182
9183         pixel_format = val & PLANE_CTL_FORMAT_MASK;
9184         fourcc = skl_format_to_fourcc(pixel_format,
9185                                       val & PLANE_CTL_ORDER_RGBX,
9186                                       val & PLANE_CTL_ALPHA_MASK);
9187         fb->pixel_format = fourcc;
9188         fb->bits_per_pixel = drm_format_plane_cpp(fourcc, 0) * 8;
9189
9190         tiling = val & PLANE_CTL_TILED_MASK;
9191         switch (tiling) {
9192         case PLANE_CTL_TILED_LINEAR:
9193                 fb->modifier[0] = DRM_FORMAT_MOD_NONE;
9194                 break;
9195         case PLANE_CTL_TILED_X:
9196                 plane_config->tiling = I915_TILING_X;
9197                 fb->modifier[0] = I915_FORMAT_MOD_X_TILED;
9198                 break;
9199         case PLANE_CTL_TILED_Y:
9200                 fb->modifier[0] = I915_FORMAT_MOD_Y_TILED;
9201                 break;
9202         case PLANE_CTL_TILED_YF:
9203                 fb->modifier[0] = I915_FORMAT_MOD_Yf_TILED;
9204                 break;
9205         default:
9206                 MISSING_CASE(tiling);
9207                 goto error;
9208         }
9209
9210         base = I915_READ(PLANE_SURF(pipe, 0)) & 0xfffff000;
9211         plane_config->base = base;
9212
9213         offset = I915_READ(PLANE_OFFSET(pipe, 0));
9214
9215         val = I915_READ(PLANE_SIZE(pipe, 0));
9216         fb->height = ((val >> 16) & 0xfff) + 1;
9217         fb->width = ((val >> 0) & 0x1fff) + 1;
9218
9219         val = I915_READ(PLANE_STRIDE(pipe, 0));
9220         stride_mult = intel_fb_stride_alignment(dev_priv, fb->modifier[0],
9221                                                 fb->pixel_format);
9222         fb->pitches[0] = (val & 0x3ff) * stride_mult;
9223
9224         aligned_height = intel_fb_align_height(dev, fb->height,
9225                                                fb->pixel_format,
9226                                                fb->modifier[0]);
9227
9228         plane_config->size = fb->pitches[0] * aligned_height;
9229
9230         DRM_DEBUG_KMS("pipe %c with fb: size=%dx%d@%d, offset=%x, pitch %d, size 0x%x\n",
9231                       pipe_name(pipe), fb->width, fb->height,
9232                       fb->bits_per_pixel, base, fb->pitches[0],
9233                       plane_config->size);
9234
9235         plane_config->fb = intel_fb;
9236         return;
9237
9238 error:
9239         kfree(fb);
9240 }
9241
9242 static void ironlake_get_pfit_config(struct intel_crtc *crtc,
9243                                      struct intel_crtc_state *pipe_config)
9244 {
9245         struct drm_device *dev = crtc->base.dev;
9246         struct drm_i915_private *dev_priv = dev->dev_private;
9247         uint32_t tmp;
9248
9249         tmp = I915_READ(PF_CTL(crtc->pipe));
9250
9251         if (tmp & PF_ENABLE) {
9252                 pipe_config->pch_pfit.enabled = true;
9253                 pipe_config->pch_pfit.pos = I915_READ(PF_WIN_POS(crtc->pipe));
9254                 pipe_config->pch_pfit.size = I915_READ(PF_WIN_SZ(crtc->pipe));
9255
9256                 /* We currently do not free assignements of panel fitters on
9257                  * ivb/hsw (since we don't use the higher upscaling modes which
9258                  * differentiates them) so just WARN about this case for now. */
9259                 if (IS_GEN7(dev)) {
9260                         WARN_ON((tmp & PF_PIPE_SEL_MASK_IVB) !=
9261                                 PF_PIPE_SEL_IVB(crtc->pipe));
9262                 }
9263         }
9264 }
9265
9266 static void
9267 ironlake_get_initial_plane_config(struct intel_crtc *crtc,
9268                                   struct intel_initial_plane_config *plane_config)
9269 {
9270         struct drm_device *dev = crtc->base.dev;
9271         struct drm_i915_private *dev_priv = dev->dev_private;
9272         u32 val, base, offset;
9273         int pipe = crtc->pipe;
9274         int fourcc, pixel_format;
9275         unsigned int aligned_height;
9276         struct drm_framebuffer *fb;
9277         struct intel_framebuffer *intel_fb;
9278
9279         val = I915_READ(DSPCNTR(pipe));
9280         if (!(val & DISPLAY_PLANE_ENABLE))
9281                 return;
9282
9283         intel_fb = kzalloc(sizeof(*intel_fb), GFP_KERNEL);
9284         if (!intel_fb) {
9285                 DRM_DEBUG_KMS("failed to alloc fb\n");
9286                 return;
9287         }
9288
9289         fb = &intel_fb->base;
9290
9291         if (INTEL_INFO(dev)->gen >= 4) {
9292                 if (val & DISPPLANE_TILED) {
9293                         plane_config->tiling = I915_TILING_X;
9294                         fb->modifier[0] = I915_FORMAT_MOD_X_TILED;
9295                 }
9296         }
9297
9298         pixel_format = val & DISPPLANE_PIXFORMAT_MASK;
9299         fourcc = i9xx_format_to_fourcc(pixel_format);
9300         fb->pixel_format = fourcc;
9301         fb->bits_per_pixel = drm_format_plane_cpp(fourcc, 0) * 8;
9302
9303         base = I915_READ(DSPSURF(pipe)) & 0xfffff000;
9304         if (IS_HASWELL(dev) || IS_BROADWELL(dev)) {
9305                 offset = I915_READ(DSPOFFSET(pipe));
9306         } else {
9307                 if (plane_config->tiling)
9308                         offset = I915_READ(DSPTILEOFF(pipe));
9309                 else
9310                         offset = I915_READ(DSPLINOFF(pipe));
9311         }
9312         plane_config->base = base;
9313
9314         val = I915_READ(PIPESRC(pipe));
9315         fb->width = ((val >> 16) & 0xfff) + 1;
9316         fb->height = ((val >> 0) & 0xfff) + 1;
9317
9318         val = I915_READ(DSPSTRIDE(pipe));
9319         fb->pitches[0] = val & 0xffffffc0;
9320
9321         aligned_height = intel_fb_align_height(dev, fb->height,
9322                                                fb->pixel_format,
9323                                                fb->modifier[0]);
9324
9325         plane_config->size = fb->pitches[0] * aligned_height;
9326
9327         DRM_DEBUG_KMS("pipe %c with fb: size=%dx%d@%d, offset=%x, pitch %d, size 0x%x\n",
9328                       pipe_name(pipe), fb->width, fb->height,
9329                       fb->bits_per_pixel, base, fb->pitches[0],
9330                       plane_config->size);
9331
9332         plane_config->fb = intel_fb;
9333 }
9334
9335 static bool ironlake_get_pipe_config(struct intel_crtc *crtc,
9336                                      struct intel_crtc_state *pipe_config)
9337 {
9338         struct drm_device *dev = crtc->base.dev;
9339         struct drm_i915_private *dev_priv = dev->dev_private;
9340         enum intel_display_power_domain power_domain;
9341         uint32_t tmp;
9342         bool ret;
9343
9344         power_domain = POWER_DOMAIN_PIPE(crtc->pipe);
9345         if (!intel_display_power_get_if_enabled(dev_priv, power_domain))
9346                 return false;
9347
9348         pipe_config->cpu_transcoder = (enum transcoder) crtc->pipe;
9349         pipe_config->shared_dpll = NULL;
9350
9351         ret = false;
9352         tmp = I915_READ(PIPECONF(crtc->pipe));
9353         if (!(tmp & PIPECONF_ENABLE))
9354                 goto out;
9355
9356         switch (tmp & PIPECONF_BPC_MASK) {
9357         case PIPECONF_6BPC:
9358                 pipe_config->pipe_bpp = 18;
9359                 break;
9360         case PIPECONF_8BPC:
9361                 pipe_config->pipe_bpp = 24;
9362                 break;
9363         case PIPECONF_10BPC:
9364                 pipe_config->pipe_bpp = 30;
9365                 break;
9366         case PIPECONF_12BPC:
9367                 pipe_config->pipe_bpp = 36;
9368                 break;
9369         default:
9370                 break;
9371         }
9372
9373         if (tmp & PIPECONF_COLOR_RANGE_SELECT)
9374                 pipe_config->limited_color_range = true;
9375
9376         if (I915_READ(PCH_TRANSCONF(crtc->pipe)) & TRANS_ENABLE) {
9377                 struct intel_shared_dpll *pll;
9378                 enum intel_dpll_id pll_id;
9379
9380                 pipe_config->has_pch_encoder = true;
9381
9382                 tmp = I915_READ(FDI_RX_CTL(crtc->pipe));
9383                 pipe_config->fdi_lanes = ((FDI_DP_PORT_WIDTH_MASK & tmp) >>
9384                                           FDI_DP_PORT_WIDTH_SHIFT) + 1;
9385
9386                 ironlake_get_fdi_m_n_config(crtc, pipe_config);
9387
9388                 if (HAS_PCH_IBX(dev_priv)) {
9389                         /*
9390                          * The pipe->pch transcoder and pch transcoder->pll
9391                          * mapping is fixed.
9392                          */
9393                         pll_id = (enum intel_dpll_id) crtc->pipe;
9394                 } else {
9395                         tmp = I915_READ(PCH_DPLL_SEL);
9396                         if (tmp & TRANS_DPLLB_SEL(crtc->pipe))
9397                                 pll_id = DPLL_ID_PCH_PLL_B;
9398                         else
9399                                 pll_id= DPLL_ID_PCH_PLL_A;
9400                 }
9401
9402                 pipe_config->shared_dpll =
9403                         intel_get_shared_dpll_by_id(dev_priv, pll_id);
9404                 pll = pipe_config->shared_dpll;
9405
9406                 WARN_ON(!pll->funcs.get_hw_state(dev_priv, pll,
9407                                                  &pipe_config->dpll_hw_state));
9408
9409                 tmp = pipe_config->dpll_hw_state.dpll;
9410                 pipe_config->pixel_multiplier =
9411                         ((tmp & PLL_REF_SDVO_HDMI_MULTIPLIER_MASK)
9412                          >> PLL_REF_SDVO_HDMI_MULTIPLIER_SHIFT) + 1;
9413
9414                 ironlake_pch_clock_get(crtc, pipe_config);
9415         } else {
9416                 pipe_config->pixel_multiplier = 1;
9417         }
9418
9419         intel_get_pipe_timings(crtc, pipe_config);
9420         intel_get_pipe_src_size(crtc, pipe_config);
9421
9422         ironlake_get_pfit_config(crtc, pipe_config);
9423
9424         ret = true;
9425
9426 out:
9427         intel_display_power_put(dev_priv, power_domain);
9428
9429         return ret;
9430 }
9431
9432 static void assert_can_disable_lcpll(struct drm_i915_private *dev_priv)
9433 {
9434         struct drm_device *dev = dev_priv->dev;
9435         struct intel_crtc *crtc;
9436
9437         for_each_intel_crtc(dev, crtc)
9438                 I915_STATE_WARN(crtc->active, "CRTC for pipe %c enabled\n",
9439                      pipe_name(crtc->pipe));
9440
9441         I915_STATE_WARN(I915_READ(HSW_PWR_WELL_DRIVER), "Power well on\n");
9442         I915_STATE_WARN(I915_READ(SPLL_CTL) & SPLL_PLL_ENABLE, "SPLL enabled\n");
9443         I915_STATE_WARN(I915_READ(WRPLL_CTL(0)) & WRPLL_PLL_ENABLE, "WRPLL1 enabled\n");
9444         I915_STATE_WARN(I915_READ(WRPLL_CTL(1)) & WRPLL_PLL_ENABLE, "WRPLL2 enabled\n");
9445         I915_STATE_WARN(I915_READ(PCH_PP_STATUS) & PP_ON, "Panel power on\n");
9446         I915_STATE_WARN(I915_READ(BLC_PWM_CPU_CTL2) & BLM_PWM_ENABLE,
9447              "CPU PWM1 enabled\n");
9448         if (IS_HASWELL(dev))
9449                 I915_STATE_WARN(I915_READ(HSW_BLC_PWM2_CTL) & BLM_PWM_ENABLE,
9450                      "CPU PWM2 enabled\n");
9451         I915_STATE_WARN(I915_READ(BLC_PWM_PCH_CTL1) & BLM_PCH_PWM_ENABLE,
9452              "PCH PWM1 enabled\n");
9453         I915_STATE_WARN(I915_READ(UTIL_PIN_CTL) & UTIL_PIN_ENABLE,
9454              "Utility pin enabled\n");
9455         I915_STATE_WARN(I915_READ(PCH_GTC_CTL) & PCH_GTC_ENABLE, "PCH GTC enabled\n");
9456
9457         /*
9458          * In theory we can still leave IRQs enabled, as long as only the HPD
9459          * interrupts remain enabled. We used to check for that, but since it's
9460          * gen-specific and since we only disable LCPLL after we fully disable
9461          * the interrupts, the check below should be enough.
9462          */
9463         I915_STATE_WARN(intel_irqs_enabled(dev_priv), "IRQs enabled\n");
9464 }
9465
9466 static uint32_t hsw_read_dcomp(struct drm_i915_private *dev_priv)
9467 {
9468         struct drm_device *dev = dev_priv->dev;
9469
9470         if (IS_HASWELL(dev))
9471                 return I915_READ(D_COMP_HSW);
9472         else
9473                 return I915_READ(D_COMP_BDW);
9474 }
9475
9476 static void hsw_write_dcomp(struct drm_i915_private *dev_priv, uint32_t val)
9477 {
9478         struct drm_device *dev = dev_priv->dev;
9479
9480         if (IS_HASWELL(dev)) {
9481                 mutex_lock(&dev_priv->rps.hw_lock);
9482                 if (sandybridge_pcode_write(dev_priv, GEN6_PCODE_WRITE_D_COMP,
9483                                             val))
9484                         DRM_ERROR("Failed to write to D_COMP\n");
9485                 mutex_unlock(&dev_priv->rps.hw_lock);
9486         } else {
9487                 I915_WRITE(D_COMP_BDW, val);
9488                 POSTING_READ(D_COMP_BDW);
9489         }
9490 }
9491
9492 /*
9493  * This function implements pieces of two sequences from BSpec:
9494  * - Sequence for display software to disable LCPLL
9495  * - Sequence for display software to allow package C8+
9496  * The steps implemented here are just the steps that actually touch the LCPLL
9497  * register. Callers should take care of disabling all the display engine
9498  * functions, doing the mode unset, fixing interrupts, etc.
9499  */
9500 static void hsw_disable_lcpll(struct drm_i915_private *dev_priv,
9501                               bool switch_to_fclk, bool allow_power_down)
9502 {
9503         uint32_t val;
9504
9505         assert_can_disable_lcpll(dev_priv);
9506
9507         val = I915_READ(LCPLL_CTL);
9508
9509         if (switch_to_fclk) {
9510                 val |= LCPLL_CD_SOURCE_FCLK;
9511                 I915_WRITE(LCPLL_CTL, val);
9512
9513                 if (wait_for_atomic_us(I915_READ(LCPLL_CTL) &
9514                                        LCPLL_CD_SOURCE_FCLK_DONE, 1))
9515                         DRM_ERROR("Switching to FCLK failed\n");
9516
9517                 val = I915_READ(LCPLL_CTL);
9518         }
9519
9520         val |= LCPLL_PLL_DISABLE;
9521         I915_WRITE(LCPLL_CTL, val);
9522         POSTING_READ(LCPLL_CTL);
9523
9524         if (wait_for((I915_READ(LCPLL_CTL) & LCPLL_PLL_LOCK) == 0, 1))
9525                 DRM_ERROR("LCPLL still locked\n");
9526
9527         val = hsw_read_dcomp(dev_priv);
9528         val |= D_COMP_COMP_DISABLE;
9529         hsw_write_dcomp(dev_priv, val);
9530         ndelay(100);
9531
9532         if (wait_for((hsw_read_dcomp(dev_priv) & D_COMP_RCOMP_IN_PROGRESS) == 0,
9533                      1))
9534                 DRM_ERROR("D_COMP RCOMP still in progress\n");
9535
9536         if (allow_power_down) {
9537                 val = I915_READ(LCPLL_CTL);
9538                 val |= LCPLL_POWER_DOWN_ALLOW;
9539                 I915_WRITE(LCPLL_CTL, val);
9540                 POSTING_READ(LCPLL_CTL);
9541         }
9542 }
9543
9544 /*
9545  * Fully restores LCPLL, disallowing power down and switching back to LCPLL
9546  * source.
9547  */
9548 static void hsw_restore_lcpll(struct drm_i915_private *dev_priv)
9549 {
9550         uint32_t val;
9551
9552         val = I915_READ(LCPLL_CTL);
9553
9554         if ((val & (LCPLL_PLL_LOCK | LCPLL_PLL_DISABLE | LCPLL_CD_SOURCE_FCLK |
9555                     LCPLL_POWER_DOWN_ALLOW)) == LCPLL_PLL_LOCK)
9556                 return;
9557
9558         /*
9559          * Make sure we're not on PC8 state before disabling PC8, otherwise
9560          * we'll hang the machine. To prevent PC8 state, just enable force_wake.
9561          */
9562         intel_uncore_forcewake_get(dev_priv, FORCEWAKE_ALL);
9563
9564         if (val & LCPLL_POWER_DOWN_ALLOW) {
9565                 val &= ~LCPLL_POWER_DOWN_ALLOW;
9566                 I915_WRITE(LCPLL_CTL, val);
9567                 POSTING_READ(LCPLL_CTL);
9568         }
9569
9570         val = hsw_read_dcomp(dev_priv);
9571         val |= D_COMP_COMP_FORCE;
9572         val &= ~D_COMP_COMP_DISABLE;
9573         hsw_write_dcomp(dev_priv, val);
9574
9575         val = I915_READ(LCPLL_CTL);
9576         val &= ~LCPLL_PLL_DISABLE;
9577         I915_WRITE(LCPLL_CTL, val);
9578
9579         if (wait_for(I915_READ(LCPLL_CTL) & LCPLL_PLL_LOCK, 5))
9580                 DRM_ERROR("LCPLL not locked yet\n");
9581
9582         if (val & LCPLL_CD_SOURCE_FCLK) {
9583                 val = I915_READ(LCPLL_CTL);
9584                 val &= ~LCPLL_CD_SOURCE_FCLK;
9585                 I915_WRITE(LCPLL_CTL, val);
9586
9587                 if (wait_for_atomic_us((I915_READ(LCPLL_CTL) &
9588                                         LCPLL_CD_SOURCE_FCLK_DONE) == 0, 1))
9589                         DRM_ERROR("Switching back to LCPLL failed\n");
9590         }
9591
9592         intel_uncore_forcewake_put(dev_priv, FORCEWAKE_ALL);
9593         intel_update_cdclk(dev_priv->dev);
9594 }
9595
9596 /*
9597  * Package states C8 and deeper are really deep PC states that can only be
9598  * reached when all the devices on the system allow it, so even if the graphics
9599  * device allows PC8+, it doesn't mean the system will actually get to these
9600  * states. Our driver only allows PC8+ when going into runtime PM.
9601  *
9602  * The requirements for PC8+ are that all the outputs are disabled, the power
9603  * well is disabled and most interrupts are disabled, and these are also
9604  * requirements for runtime PM. When these conditions are met, we manually do
9605  * the other conditions: disable the interrupts, clocks and switch LCPLL refclk
9606  * to Fclk. If we're in PC8+ and we get an non-hotplug interrupt, we can hard
9607  * hang the machine.
9608  *
9609  * When we really reach PC8 or deeper states (not just when we allow it) we lose
9610  * the state of some registers, so when we come back from PC8+ we need to
9611  * restore this state. We don't get into PC8+ if we're not in RC6, so we don't
9612  * need to take care of the registers kept by RC6. Notice that this happens even
9613  * if we don't put the device in PCI D3 state (which is what currently happens
9614  * because of the runtime PM support).
9615  *
9616  * For more, read "Display Sequences for Package C8" on the hardware
9617  * documentation.
9618  */
9619 void hsw_enable_pc8(struct drm_i915_private *dev_priv)
9620 {
9621         struct drm_device *dev = dev_priv->dev;
9622         uint32_t val;
9623
9624         DRM_DEBUG_KMS("Enabling package C8+\n");
9625
9626         if (HAS_PCH_LPT_LP(dev)) {
9627                 val = I915_READ(SOUTH_DSPCLK_GATE_D);
9628                 val &= ~PCH_LP_PARTITION_LEVEL_DISABLE;
9629                 I915_WRITE(SOUTH_DSPCLK_GATE_D, val);
9630         }
9631
9632         lpt_disable_clkout_dp(dev);
9633         hsw_disable_lcpll(dev_priv, true, true);
9634 }
9635
9636 void hsw_disable_pc8(struct drm_i915_private *dev_priv)
9637 {
9638         struct drm_device *dev = dev_priv->dev;
9639         uint32_t val;
9640
9641         DRM_DEBUG_KMS("Disabling package C8+\n");
9642
9643         hsw_restore_lcpll(dev_priv);
9644         lpt_init_pch_refclk(dev);
9645
9646         if (HAS_PCH_LPT_LP(dev)) {
9647                 val = I915_READ(SOUTH_DSPCLK_GATE_D);
9648                 val |= PCH_LP_PARTITION_LEVEL_DISABLE;
9649                 I915_WRITE(SOUTH_DSPCLK_GATE_D, val);
9650         }
9651 }
9652
9653 static void broxton_modeset_commit_cdclk(struct drm_atomic_state *old_state)
9654 {
9655         struct drm_device *dev = old_state->dev;
9656         struct intel_atomic_state *old_intel_state =
9657                 to_intel_atomic_state(old_state);
9658         unsigned int req_cdclk = old_intel_state->dev_cdclk;
9659
9660         broxton_set_cdclk(to_i915(dev), req_cdclk);
9661 }
9662
9663 /* compute the max rate for new configuration */
9664 static int ilk_max_pixel_rate(struct drm_atomic_state *state)
9665 {
9666         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
9667         struct drm_i915_private *dev_priv = state->dev->dev_private;
9668         struct drm_crtc *crtc;
9669         struct drm_crtc_state *cstate;
9670         struct intel_crtc_state *crtc_state;
9671         unsigned max_pixel_rate = 0, i;
9672         enum pipe pipe;
9673
9674         memcpy(intel_state->min_pixclk, dev_priv->min_pixclk,
9675                sizeof(intel_state->min_pixclk));
9676
9677         for_each_crtc_in_state(state, crtc, cstate, i) {
9678                 int pixel_rate;
9679
9680                 crtc_state = to_intel_crtc_state(cstate);
9681                 if (!crtc_state->base.enable) {
9682                         intel_state->min_pixclk[i] = 0;
9683                         continue;
9684                 }
9685
9686                 pixel_rate = ilk_pipe_pixel_rate(crtc_state);
9687
9688                 /* pixel rate mustn't exceed 95% of cdclk with IPS on BDW */
9689                 if (IS_BROADWELL(dev_priv) && crtc_state->ips_enabled)
9690                         pixel_rate = DIV_ROUND_UP(pixel_rate * 100, 95);
9691
9692                 intel_state->min_pixclk[i] = pixel_rate;
9693         }
9694
9695         for_each_pipe(dev_priv, pipe)
9696                 max_pixel_rate = max(intel_state->min_pixclk[pipe], max_pixel_rate);
9697
9698         return max_pixel_rate;
9699 }
9700
9701 static void broadwell_set_cdclk(struct drm_device *dev, int cdclk)
9702 {
9703         struct drm_i915_private *dev_priv = dev->dev_private;
9704         uint32_t val, data;
9705         int ret;
9706
9707         if (WARN((I915_READ(LCPLL_CTL) &
9708                   (LCPLL_PLL_DISABLE | LCPLL_PLL_LOCK |
9709                    LCPLL_CD_CLOCK_DISABLE | LCPLL_ROOT_CD_CLOCK_DISABLE |
9710                    LCPLL_CD2X_CLOCK_DISABLE | LCPLL_POWER_DOWN_ALLOW |
9711                    LCPLL_CD_SOURCE_FCLK)) != LCPLL_PLL_LOCK,
9712                  "trying to change cdclk frequency with cdclk not enabled\n"))
9713                 return;
9714
9715         mutex_lock(&dev_priv->rps.hw_lock);
9716         ret = sandybridge_pcode_write(dev_priv,
9717                                       BDW_PCODE_DISPLAY_FREQ_CHANGE_REQ, 0x0);
9718         mutex_unlock(&dev_priv->rps.hw_lock);
9719         if (ret) {
9720                 DRM_ERROR("failed to inform pcode about cdclk change\n");
9721                 return;
9722         }
9723
9724         val = I915_READ(LCPLL_CTL);
9725         val |= LCPLL_CD_SOURCE_FCLK;
9726         I915_WRITE(LCPLL_CTL, val);
9727
9728         if (wait_for_us(I915_READ(LCPLL_CTL) &
9729                         LCPLL_CD_SOURCE_FCLK_DONE, 1))
9730                 DRM_ERROR("Switching to FCLK failed\n");
9731
9732         val = I915_READ(LCPLL_CTL);
9733         val &= ~LCPLL_CLK_FREQ_MASK;
9734
9735         switch (cdclk) {
9736         case 450000:
9737                 val |= LCPLL_CLK_FREQ_450;
9738                 data = 0;
9739                 break;
9740         case 540000:
9741                 val |= LCPLL_CLK_FREQ_54O_BDW;
9742                 data = 1;
9743                 break;
9744         case 337500:
9745                 val |= LCPLL_CLK_FREQ_337_5_BDW;
9746                 data = 2;
9747                 break;
9748         case 675000:
9749                 val |= LCPLL_CLK_FREQ_675_BDW;
9750                 data = 3;
9751                 break;
9752         default:
9753                 WARN(1, "invalid cdclk frequency\n");
9754                 return;
9755         }
9756
9757         I915_WRITE(LCPLL_CTL, val);
9758
9759         val = I915_READ(LCPLL_CTL);
9760         val &= ~LCPLL_CD_SOURCE_FCLK;
9761         I915_WRITE(LCPLL_CTL, val);
9762
9763         if (wait_for_us((I915_READ(LCPLL_CTL) &
9764                         LCPLL_CD_SOURCE_FCLK_DONE) == 0, 1))
9765                 DRM_ERROR("Switching back to LCPLL failed\n");
9766
9767         mutex_lock(&dev_priv->rps.hw_lock);
9768         sandybridge_pcode_write(dev_priv, HSW_PCODE_DE_WRITE_FREQ_REQ, data);
9769         mutex_unlock(&dev_priv->rps.hw_lock);
9770
9771         I915_WRITE(CDCLK_FREQ, DIV_ROUND_CLOSEST(cdclk, 1000) - 1);
9772
9773         intel_update_cdclk(dev);
9774
9775         WARN(cdclk != dev_priv->cdclk_freq,
9776              "cdclk requested %d kHz but got %d kHz\n",
9777              cdclk, dev_priv->cdclk_freq);
9778 }
9779
9780 static int broadwell_calc_cdclk(int max_pixclk)
9781 {
9782         if (max_pixclk > 540000)
9783                 return 675000;
9784         else if (max_pixclk > 450000)
9785                 return 540000;
9786         else if (max_pixclk > 337500)
9787                 return 450000;
9788         else
9789                 return 337500;
9790 }
9791
9792 static int broadwell_modeset_calc_cdclk(struct drm_atomic_state *state)
9793 {
9794         struct drm_i915_private *dev_priv = to_i915(state->dev);
9795         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
9796         int max_pixclk = ilk_max_pixel_rate(state);
9797         int cdclk;
9798
9799         /*
9800          * FIXME should also account for plane ratio
9801          * once 64bpp pixel formats are supported.
9802          */
9803         cdclk = broadwell_calc_cdclk(max_pixclk);
9804
9805         if (cdclk > dev_priv->max_cdclk_freq) {
9806                 DRM_DEBUG_KMS("requested cdclk (%d kHz) exceeds max (%d kHz)\n",
9807                               cdclk, dev_priv->max_cdclk_freq);
9808                 return -EINVAL;
9809         }
9810
9811         intel_state->cdclk = intel_state->dev_cdclk = cdclk;
9812         if (!intel_state->active_crtcs)
9813                 intel_state->dev_cdclk = broadwell_calc_cdclk(0);
9814
9815         return 0;
9816 }
9817
9818 static void broadwell_modeset_commit_cdclk(struct drm_atomic_state *old_state)
9819 {
9820         struct drm_device *dev = old_state->dev;
9821         struct intel_atomic_state *old_intel_state =
9822                 to_intel_atomic_state(old_state);
9823         unsigned req_cdclk = old_intel_state->dev_cdclk;
9824
9825         broadwell_set_cdclk(dev, req_cdclk);
9826 }
9827
9828 static int skl_modeset_calc_cdclk(struct drm_atomic_state *state)
9829 {
9830         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
9831         struct drm_i915_private *dev_priv = to_i915(state->dev);
9832         const int max_pixclk = ilk_max_pixel_rate(state);
9833         int vco = intel_state->cdclk_pll_vco;
9834         int cdclk;
9835
9836         /*
9837          * FIXME should also account for plane ratio
9838          * once 64bpp pixel formats are supported.
9839          */
9840         cdclk = skl_calc_cdclk(max_pixclk, vco);
9841
9842         /*
9843          * FIXME move the cdclk caclulation to
9844          * compute_config() so we can fail gracegully.
9845          */
9846         if (cdclk > dev_priv->max_cdclk_freq) {
9847                 DRM_ERROR("requested cdclk (%d kHz) exceeds max (%d kHz)\n",
9848                           cdclk, dev_priv->max_cdclk_freq);
9849                 cdclk = dev_priv->max_cdclk_freq;
9850         }
9851
9852         intel_state->cdclk = intel_state->dev_cdclk = cdclk;
9853         if (!intel_state->active_crtcs)
9854                 intel_state->dev_cdclk = skl_calc_cdclk(0, vco);
9855
9856         return 0;
9857 }
9858
9859 static void skl_modeset_commit_cdclk(struct drm_atomic_state *old_state)
9860 {
9861         struct drm_i915_private *dev_priv = to_i915(old_state->dev);
9862         struct intel_atomic_state *intel_state = to_intel_atomic_state(old_state);
9863         unsigned int req_cdclk = intel_state->dev_cdclk;
9864         unsigned int req_vco = intel_state->cdclk_pll_vco;
9865
9866         skl_set_cdclk(dev_priv, req_cdclk, req_vco);
9867 }
9868
9869 static int haswell_crtc_compute_clock(struct intel_crtc *crtc,
9870                                       struct intel_crtc_state *crtc_state)
9871 {
9872         struct intel_encoder *intel_encoder =
9873                 intel_ddi_get_crtc_new_encoder(crtc_state);
9874
9875         if (intel_encoder->type != INTEL_OUTPUT_DSI) {
9876                 if (!intel_ddi_pll_select(crtc, crtc_state))
9877                         return -EINVAL;
9878         }
9879
9880         crtc->lowfreq_avail = false;
9881
9882         return 0;
9883 }
9884
9885 static void bxt_get_ddi_pll(struct drm_i915_private *dev_priv,
9886                                 enum port port,
9887                                 struct intel_crtc_state *pipe_config)
9888 {
9889         enum intel_dpll_id id;
9890
9891         switch (port) {
9892         case PORT_A:
9893                 pipe_config->ddi_pll_sel = SKL_DPLL0;
9894                 id = DPLL_ID_SKL_DPLL0;
9895                 break;
9896         case PORT_B:
9897                 pipe_config->ddi_pll_sel = SKL_DPLL1;
9898                 id = DPLL_ID_SKL_DPLL1;
9899                 break;
9900         case PORT_C:
9901                 pipe_config->ddi_pll_sel = SKL_DPLL2;
9902                 id = DPLL_ID_SKL_DPLL2;
9903                 break;
9904         default:
9905                 DRM_ERROR("Incorrect port type\n");
9906                 return;
9907         }
9908
9909         pipe_config->shared_dpll = intel_get_shared_dpll_by_id(dev_priv, id);
9910 }
9911
9912 static void skylake_get_ddi_pll(struct drm_i915_private *dev_priv,
9913                                 enum port port,
9914                                 struct intel_crtc_state *pipe_config)
9915 {
9916         enum intel_dpll_id id;
9917         u32 temp;
9918
9919         temp = I915_READ(DPLL_CTRL2) & DPLL_CTRL2_DDI_CLK_SEL_MASK(port);
9920         pipe_config->ddi_pll_sel = temp >> (port * 3 + 1);
9921
9922         switch (pipe_config->ddi_pll_sel) {
9923         case SKL_DPLL0:
9924                 id = DPLL_ID_SKL_DPLL0;
9925                 break;
9926         case SKL_DPLL1:
9927                 id = DPLL_ID_SKL_DPLL1;
9928                 break;
9929         case SKL_DPLL2:
9930                 id = DPLL_ID_SKL_DPLL2;
9931                 break;
9932         case SKL_DPLL3:
9933                 id = DPLL_ID_SKL_DPLL3;
9934                 break;
9935         default:
9936                 MISSING_CASE(pipe_config->ddi_pll_sel);
9937                 return;
9938         }
9939
9940         pipe_config->shared_dpll = intel_get_shared_dpll_by_id(dev_priv, id);
9941 }
9942
9943 static void haswell_get_ddi_pll(struct drm_i915_private *dev_priv,
9944                                 enum port port,
9945                                 struct intel_crtc_state *pipe_config)
9946 {
9947         enum intel_dpll_id id;
9948
9949         pipe_config->ddi_pll_sel = I915_READ(PORT_CLK_SEL(port));
9950
9951         switch (pipe_config->ddi_pll_sel) {
9952         case PORT_CLK_SEL_WRPLL1:
9953                 id = DPLL_ID_WRPLL1;
9954                 break;
9955         case PORT_CLK_SEL_WRPLL2:
9956                 id = DPLL_ID_WRPLL2;
9957                 break;
9958         case PORT_CLK_SEL_SPLL:
9959                 id = DPLL_ID_SPLL;
9960                 break;
9961         case PORT_CLK_SEL_LCPLL_810:
9962                 id = DPLL_ID_LCPLL_810;
9963                 break;
9964         case PORT_CLK_SEL_LCPLL_1350:
9965                 id = DPLL_ID_LCPLL_1350;
9966                 break;
9967         case PORT_CLK_SEL_LCPLL_2700:
9968                 id = DPLL_ID_LCPLL_2700;
9969                 break;
9970         default:
9971                 MISSING_CASE(pipe_config->ddi_pll_sel);
9972                 /* fall through */
9973         case PORT_CLK_SEL_NONE:
9974                 return;
9975         }
9976
9977         pipe_config->shared_dpll = intel_get_shared_dpll_by_id(dev_priv, id);
9978 }
9979
9980 static bool hsw_get_transcoder_state(struct intel_crtc *crtc,
9981                                      struct intel_crtc_state *pipe_config,
9982                                      unsigned long *power_domain_mask)
9983 {
9984         struct drm_device *dev = crtc->base.dev;
9985         struct drm_i915_private *dev_priv = dev->dev_private;
9986         enum intel_display_power_domain power_domain;
9987         u32 tmp;
9988
9989         /*
9990          * The pipe->transcoder mapping is fixed with the exception of the eDP
9991          * transcoder handled below.
9992          */
9993         pipe_config->cpu_transcoder = (enum transcoder) crtc->pipe;
9994
9995         /*
9996          * XXX: Do intel_display_power_get_if_enabled before reading this (for
9997          * consistency and less surprising code; it's in always on power).
9998          */
9999         tmp = I915_READ(TRANS_DDI_FUNC_CTL(TRANSCODER_EDP));
10000         if (tmp & TRANS_DDI_FUNC_ENABLE) {
10001                 enum pipe trans_edp_pipe;
10002                 switch (tmp & TRANS_DDI_EDP_INPUT_MASK) {
10003                 default:
10004                         WARN(1, "unknown pipe linked to edp transcoder\n");
10005                 case TRANS_DDI_EDP_INPUT_A_ONOFF:
10006                 case TRANS_DDI_EDP_INPUT_A_ON:
10007                         trans_edp_pipe = PIPE_A;
10008                         break;
10009                 case TRANS_DDI_EDP_INPUT_B_ONOFF:
10010                         trans_edp_pipe = PIPE_B;
10011                         break;
10012                 case TRANS_DDI_EDP_INPUT_C_ONOFF:
10013                         trans_edp_pipe = PIPE_C;
10014                         break;
10015                 }
10016
10017                 if (trans_edp_pipe == crtc->pipe)
10018                         pipe_config->cpu_transcoder = TRANSCODER_EDP;
10019         }
10020
10021         power_domain = POWER_DOMAIN_TRANSCODER(pipe_config->cpu_transcoder);
10022         if (!intel_display_power_get_if_enabled(dev_priv, power_domain))
10023                 return false;
10024         *power_domain_mask |= BIT(power_domain);
10025
10026         tmp = I915_READ(PIPECONF(pipe_config->cpu_transcoder));
10027
10028         return tmp & PIPECONF_ENABLE;
10029 }
10030
10031 static bool bxt_get_dsi_transcoder_state(struct intel_crtc *crtc,
10032                                          struct intel_crtc_state *pipe_config,
10033                                          unsigned long *power_domain_mask)
10034 {
10035         struct drm_device *dev = crtc->base.dev;
10036         struct drm_i915_private *dev_priv = dev->dev_private;
10037         enum intel_display_power_domain power_domain;
10038         enum port port;
10039         enum transcoder cpu_transcoder;
10040         u32 tmp;
10041
10042         pipe_config->has_dsi_encoder = false;
10043
10044         for_each_port_masked(port, BIT(PORT_A) | BIT(PORT_C)) {
10045                 if (port == PORT_A)
10046                         cpu_transcoder = TRANSCODER_DSI_A;
10047                 else
10048                         cpu_transcoder = TRANSCODER_DSI_C;
10049
10050                 power_domain = POWER_DOMAIN_TRANSCODER(cpu_transcoder);
10051                 if (!intel_display_power_get_if_enabled(dev_priv, power_domain))
10052                         continue;
10053                 *power_domain_mask |= BIT(power_domain);
10054
10055                 /*
10056                  * The PLL needs to be enabled with a valid divider
10057                  * configuration, otherwise accessing DSI registers will hang
10058                  * the machine. See BSpec North Display Engine
10059                  * registers/MIPI[BXT]. We can break out here early, since we
10060                  * need the same DSI PLL to be enabled for both DSI ports.
10061                  */
10062                 if (!intel_dsi_pll_is_enabled(dev_priv))
10063                         break;
10064
10065                 /* XXX: this works for video mode only */
10066                 tmp = I915_READ(BXT_MIPI_PORT_CTRL(port));
10067                 if (!(tmp & DPI_ENABLE))
10068                         continue;
10069
10070                 tmp = I915_READ(MIPI_CTRL(port));
10071                 if ((tmp & BXT_PIPE_SELECT_MASK) != BXT_PIPE_SELECT(crtc->pipe))
10072                         continue;
10073
10074                 pipe_config->cpu_transcoder = cpu_transcoder;
10075                 pipe_config->has_dsi_encoder = true;
10076                 break;
10077         }
10078
10079         return pipe_config->has_dsi_encoder;
10080 }
10081
10082 static void haswell_get_ddi_port_state(struct intel_crtc *crtc,
10083                                        struct intel_crtc_state *pipe_config)
10084 {
10085         struct drm_device *dev = crtc->base.dev;
10086         struct drm_i915_private *dev_priv = dev->dev_private;
10087         struct intel_shared_dpll *pll;
10088         enum port port;
10089         uint32_t tmp;
10090
10091         tmp = I915_READ(TRANS_DDI_FUNC_CTL(pipe_config->cpu_transcoder));
10092
10093         port = (tmp & TRANS_DDI_PORT_MASK) >> TRANS_DDI_PORT_SHIFT;
10094
10095         if (IS_SKYLAKE(dev) || IS_KABYLAKE(dev))
10096                 skylake_get_ddi_pll(dev_priv, port, pipe_config);
10097         else if (IS_BROXTON(dev))
10098                 bxt_get_ddi_pll(dev_priv, port, pipe_config);
10099         else
10100                 haswell_get_ddi_pll(dev_priv, port, pipe_config);
10101
10102         pll = pipe_config->shared_dpll;
10103         if (pll) {
10104                 WARN_ON(!pll->funcs.get_hw_state(dev_priv, pll,
10105                                                  &pipe_config->dpll_hw_state));
10106         }
10107
10108         /*
10109          * Haswell has only FDI/PCH transcoder A. It is which is connected to
10110          * DDI E. So just check whether this pipe is wired to DDI E and whether
10111          * the PCH transcoder is on.
10112          */
10113         if (INTEL_INFO(dev)->gen < 9 &&
10114             (port == PORT_E) && I915_READ(LPT_TRANSCONF) & TRANS_ENABLE) {
10115                 pipe_config->has_pch_encoder = true;
10116
10117                 tmp = I915_READ(FDI_RX_CTL(PIPE_A));
10118                 pipe_config->fdi_lanes = ((FDI_DP_PORT_WIDTH_MASK & tmp) >>
10119                                           FDI_DP_PORT_WIDTH_SHIFT) + 1;
10120
10121                 ironlake_get_fdi_m_n_config(crtc, pipe_config);
10122         }
10123 }
10124
10125 static bool haswell_get_pipe_config(struct intel_crtc *crtc,
10126                                     struct intel_crtc_state *pipe_config)
10127 {
10128         struct drm_device *dev = crtc->base.dev;
10129         struct drm_i915_private *dev_priv = dev->dev_private;
10130         enum intel_display_power_domain power_domain;
10131         unsigned long power_domain_mask;
10132         bool active;
10133
10134         power_domain = POWER_DOMAIN_PIPE(crtc->pipe);
10135         if (!intel_display_power_get_if_enabled(dev_priv, power_domain))
10136                 return false;
10137         power_domain_mask = BIT(power_domain);
10138
10139         pipe_config->shared_dpll = NULL;
10140
10141         active = hsw_get_transcoder_state(crtc, pipe_config, &power_domain_mask);
10142
10143         if (IS_BROXTON(dev_priv)) {
10144                 bxt_get_dsi_transcoder_state(crtc, pipe_config,
10145                                              &power_domain_mask);
10146                 WARN_ON(active && pipe_config->has_dsi_encoder);
10147                 if (pipe_config->has_dsi_encoder)
10148                         active = true;
10149         }
10150
10151         if (!active)
10152                 goto out;
10153
10154         if (!pipe_config->has_dsi_encoder) {
10155                 haswell_get_ddi_port_state(crtc, pipe_config);
10156                 intel_get_pipe_timings(crtc, pipe_config);
10157         }
10158
10159         intel_get_pipe_src_size(crtc, pipe_config);
10160
10161         pipe_config->gamma_mode =
10162                 I915_READ(GAMMA_MODE(crtc->pipe)) & GAMMA_MODE_MODE_MASK;
10163
10164         if (INTEL_INFO(dev)->gen >= 9) {
10165                 skl_init_scalers(dev, crtc, pipe_config);
10166         }
10167
10168         if (INTEL_INFO(dev)->gen >= 9) {
10169                 pipe_config->scaler_state.scaler_id = -1;
10170                 pipe_config->scaler_state.scaler_users &= ~(1 << SKL_CRTC_INDEX);
10171         }
10172
10173         power_domain = POWER_DOMAIN_PIPE_PANEL_FITTER(crtc->pipe);
10174         if (intel_display_power_get_if_enabled(dev_priv, power_domain)) {
10175                 power_domain_mask |= BIT(power_domain);
10176                 if (INTEL_INFO(dev)->gen >= 9)
10177                         skylake_get_pfit_config(crtc, pipe_config);
10178                 else
10179                         ironlake_get_pfit_config(crtc, pipe_config);
10180         }
10181
10182         if (IS_HASWELL(dev))
10183                 pipe_config->ips_enabled = hsw_crtc_supports_ips(crtc) &&
10184                         (I915_READ(IPS_CTL) & IPS_ENABLE);
10185
10186         if (pipe_config->cpu_transcoder != TRANSCODER_EDP &&
10187             !transcoder_is_dsi(pipe_config->cpu_transcoder)) {
10188                 pipe_config->pixel_multiplier =
10189                         I915_READ(PIPE_MULT(pipe_config->cpu_transcoder)) + 1;
10190         } else {
10191                 pipe_config->pixel_multiplier = 1;
10192         }
10193
10194 out:
10195         for_each_power_domain(power_domain, power_domain_mask)
10196                 intel_display_power_put(dev_priv, power_domain);
10197
10198         return active;
10199 }
10200
10201 static void i845_update_cursor(struct drm_crtc *crtc, u32 base,
10202                                const struct intel_plane_state *plane_state)
10203 {
10204         struct drm_device *dev = crtc->dev;
10205         struct drm_i915_private *dev_priv = dev->dev_private;
10206         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
10207         uint32_t cntl = 0, size = 0;
10208
10209         if (plane_state && plane_state->visible) {
10210                 unsigned int width = plane_state->base.crtc_w;
10211                 unsigned int height = plane_state->base.crtc_h;
10212                 unsigned int stride = roundup_pow_of_two(width) * 4;
10213
10214                 switch (stride) {
10215                 default:
10216                         WARN_ONCE(1, "Invalid cursor width/stride, width=%u, stride=%u\n",
10217                                   width, stride);
10218                         stride = 256;
10219                         /* fallthrough */
10220                 case 256:
10221                 case 512:
10222                 case 1024:
10223                 case 2048:
10224                         break;
10225                 }
10226
10227                 cntl |= CURSOR_ENABLE |
10228                         CURSOR_GAMMA_ENABLE |
10229                         CURSOR_FORMAT_ARGB |
10230                         CURSOR_STRIDE(stride);
10231
10232                 size = (height << 12) | width;
10233         }
10234
10235         if (intel_crtc->cursor_cntl != 0 &&
10236             (intel_crtc->cursor_base != base ||
10237              intel_crtc->cursor_size != size ||
10238              intel_crtc->cursor_cntl != cntl)) {
10239                 /* On these chipsets we can only modify the base/size/stride
10240                  * whilst the cursor is disabled.
10241                  */
10242                 I915_WRITE(CURCNTR(PIPE_A), 0);
10243                 POSTING_READ(CURCNTR(PIPE_A));
10244                 intel_crtc->cursor_cntl = 0;
10245         }
10246
10247         if (intel_crtc->cursor_base != base) {
10248                 I915_WRITE(CURBASE(PIPE_A), base);
10249                 intel_crtc->cursor_base = base;
10250         }
10251
10252         if (intel_crtc->cursor_size != size) {
10253                 I915_WRITE(CURSIZE, size);
10254                 intel_crtc->cursor_size = size;
10255         }
10256
10257         if (intel_crtc->cursor_cntl != cntl) {
10258                 I915_WRITE(CURCNTR(PIPE_A), cntl);
10259                 POSTING_READ(CURCNTR(PIPE_A));
10260                 intel_crtc->cursor_cntl = cntl;
10261         }
10262 }
10263
10264 static void i9xx_update_cursor(struct drm_crtc *crtc, u32 base,
10265                                const struct intel_plane_state *plane_state)
10266 {
10267         struct drm_device *dev = crtc->dev;
10268         struct drm_i915_private *dev_priv = dev->dev_private;
10269         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
10270         int pipe = intel_crtc->pipe;
10271         uint32_t cntl = 0;
10272
10273         if (plane_state && plane_state->visible) {
10274                 cntl = MCURSOR_GAMMA_ENABLE;
10275                 switch (plane_state->base.crtc_w) {
10276                         case 64:
10277                                 cntl |= CURSOR_MODE_64_ARGB_AX;
10278                                 break;
10279                         case 128:
10280                                 cntl |= CURSOR_MODE_128_ARGB_AX;
10281                                 break;
10282                         case 256:
10283                                 cntl |= CURSOR_MODE_256_ARGB_AX;
10284                                 break;
10285                         default:
10286                                 MISSING_CASE(plane_state->base.crtc_w);
10287                                 return;
10288                 }
10289                 cntl |= pipe << 28; /* Connect to correct pipe */
10290
10291                 if (HAS_DDI(dev))
10292                         cntl |= CURSOR_PIPE_CSC_ENABLE;
10293
10294                 if (plane_state->base.rotation == BIT(DRM_ROTATE_180))
10295                         cntl |= CURSOR_ROTATE_180;
10296         }
10297
10298         if (intel_crtc->cursor_cntl != cntl) {
10299                 I915_WRITE(CURCNTR(pipe), cntl);
10300                 POSTING_READ(CURCNTR(pipe));
10301                 intel_crtc->cursor_cntl = cntl;
10302         }
10303
10304         /* and commit changes on next vblank */
10305         I915_WRITE(CURBASE(pipe), base);
10306         POSTING_READ(CURBASE(pipe));
10307
10308         intel_crtc->cursor_base = base;
10309 }
10310
10311 /* If no-part of the cursor is visible on the framebuffer, then the GPU may hang... */
10312 static void intel_crtc_update_cursor(struct drm_crtc *crtc,
10313                                      const struct intel_plane_state *plane_state)
10314 {
10315         struct drm_device *dev = crtc->dev;
10316         struct drm_i915_private *dev_priv = dev->dev_private;
10317         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
10318         int pipe = intel_crtc->pipe;
10319         u32 base = intel_crtc->cursor_addr;
10320         u32 pos = 0;
10321
10322         if (plane_state) {
10323                 int x = plane_state->base.crtc_x;
10324                 int y = plane_state->base.crtc_y;
10325
10326                 if (x < 0) {
10327                         pos |= CURSOR_POS_SIGN << CURSOR_X_SHIFT;
10328                         x = -x;
10329                 }
10330                 pos |= x << CURSOR_X_SHIFT;
10331
10332                 if (y < 0) {
10333                         pos |= CURSOR_POS_SIGN << CURSOR_Y_SHIFT;
10334                         y = -y;
10335                 }
10336                 pos |= y << CURSOR_Y_SHIFT;
10337
10338                 /* ILK+ do this automagically */
10339                 if (HAS_GMCH_DISPLAY(dev) &&
10340                     plane_state->base.rotation == BIT(DRM_ROTATE_180)) {
10341                         base += (plane_state->base.crtc_h *
10342                                  plane_state->base.crtc_w - 1) * 4;
10343                 }
10344         }
10345
10346         I915_WRITE(CURPOS(pipe), pos);
10347
10348         if (IS_845G(dev) || IS_I865G(dev))
10349                 i845_update_cursor(crtc, base, plane_state);
10350         else
10351                 i9xx_update_cursor(crtc, base, plane_state);
10352 }
10353
10354 static bool cursor_size_ok(struct drm_device *dev,
10355                            uint32_t width, uint32_t height)
10356 {
10357         if (width == 0 || height == 0)
10358                 return false;
10359
10360         /*
10361          * 845g/865g are special in that they are only limited by
10362          * the width of their cursors, the height is arbitrary up to
10363          * the precision of the register. Everything else requires
10364          * square cursors, limited to a few power-of-two sizes.
10365          */
10366         if (IS_845G(dev) || IS_I865G(dev)) {
10367                 if ((width & 63) != 0)
10368                         return false;
10369
10370                 if (width > (IS_845G(dev) ? 64 : 512))
10371                         return false;
10372
10373                 if (height > 1023)
10374                         return false;
10375         } else {
10376                 switch (width | height) {
10377                 case 256:
10378                 case 128:
10379                         if (IS_GEN2(dev))
10380                                 return false;
10381                 case 64:
10382                         break;
10383                 default:
10384                         return false;
10385                 }
10386         }
10387
10388         return true;
10389 }
10390
10391 /* VESA 640x480x72Hz mode to set on the pipe */
10392 static struct drm_display_mode load_detect_mode = {
10393         DRM_MODE("640x480", DRM_MODE_TYPE_DEFAULT, 31500, 640, 664,
10394                  704, 832, 0, 480, 489, 491, 520, 0, DRM_MODE_FLAG_NHSYNC | DRM_MODE_FLAG_NVSYNC),
10395 };
10396
10397 struct drm_framebuffer *
10398 __intel_framebuffer_create(struct drm_device *dev,
10399                            struct drm_mode_fb_cmd2 *mode_cmd,
10400                            struct drm_i915_gem_object *obj)
10401 {
10402         struct intel_framebuffer *intel_fb;
10403         int ret;
10404
10405         intel_fb = kzalloc(sizeof(*intel_fb), GFP_KERNEL);
10406         if (!intel_fb)
10407                 return ERR_PTR(-ENOMEM);
10408
10409         ret = intel_framebuffer_init(dev, intel_fb, mode_cmd, obj);
10410         if (ret)
10411                 goto err;
10412
10413         return &intel_fb->base;
10414
10415 err:
10416         kfree(intel_fb);
10417         return ERR_PTR(ret);
10418 }
10419
10420 static struct drm_framebuffer *
10421 intel_framebuffer_create(struct drm_device *dev,
10422                          struct drm_mode_fb_cmd2 *mode_cmd,
10423                          struct drm_i915_gem_object *obj)
10424 {
10425         struct drm_framebuffer *fb;
10426         int ret;
10427
10428         ret = i915_mutex_lock_interruptible(dev);
10429         if (ret)
10430                 return ERR_PTR(ret);
10431         fb = __intel_framebuffer_create(dev, mode_cmd, obj);
10432         mutex_unlock(&dev->struct_mutex);
10433
10434         return fb;
10435 }
10436
10437 static u32
10438 intel_framebuffer_pitch_for_width(int width, int bpp)
10439 {
10440         u32 pitch = DIV_ROUND_UP(width * bpp, 8);
10441         return ALIGN(pitch, 64);
10442 }
10443
10444 static u32
10445 intel_framebuffer_size_for_mode(struct drm_display_mode *mode, int bpp)
10446 {
10447         u32 pitch = intel_framebuffer_pitch_for_width(mode->hdisplay, bpp);
10448         return PAGE_ALIGN(pitch * mode->vdisplay);
10449 }
10450
10451 static struct drm_framebuffer *
10452 intel_framebuffer_create_for_mode(struct drm_device *dev,
10453                                   struct drm_display_mode *mode,
10454                                   int depth, int bpp)
10455 {
10456         struct drm_framebuffer *fb;
10457         struct drm_i915_gem_object *obj;
10458         struct drm_mode_fb_cmd2 mode_cmd = { 0 };
10459
10460         obj = i915_gem_object_create(dev,
10461                                     intel_framebuffer_size_for_mode(mode, bpp));
10462         if (IS_ERR(obj))
10463                 return ERR_CAST(obj);
10464
10465         mode_cmd.width = mode->hdisplay;
10466         mode_cmd.height = mode->vdisplay;
10467         mode_cmd.pitches[0] = intel_framebuffer_pitch_for_width(mode_cmd.width,
10468                                                                 bpp);
10469         mode_cmd.pixel_format = drm_mode_legacy_fb_format(bpp, depth);
10470
10471         fb = intel_framebuffer_create(dev, &mode_cmd, obj);
10472         if (IS_ERR(fb))
10473                 drm_gem_object_unreference_unlocked(&obj->base);
10474
10475         return fb;
10476 }
10477
10478 static struct drm_framebuffer *
10479 mode_fits_in_fbdev(struct drm_device *dev,
10480                    struct drm_display_mode *mode)
10481 {
10482 #ifdef CONFIG_DRM_FBDEV_EMULATION
10483         struct drm_i915_private *dev_priv = dev->dev_private;
10484         struct drm_i915_gem_object *obj;
10485         struct drm_framebuffer *fb;
10486
10487         if (!dev_priv->fbdev)
10488                 return NULL;
10489
10490         if (!dev_priv->fbdev->fb)
10491                 return NULL;
10492
10493         obj = dev_priv->fbdev->fb->obj;
10494         BUG_ON(!obj);
10495
10496         fb = &dev_priv->fbdev->fb->base;
10497         if (fb->pitches[0] < intel_framebuffer_pitch_for_width(mode->hdisplay,
10498                                                                fb->bits_per_pixel))
10499                 return NULL;
10500
10501         if (obj->base.size < mode->vdisplay * fb->pitches[0])
10502                 return NULL;
10503
10504         drm_framebuffer_reference(fb);
10505         return fb;
10506 #else
10507         return NULL;
10508 #endif
10509 }
10510
10511 static int intel_modeset_setup_plane_state(struct drm_atomic_state *state,
10512                                            struct drm_crtc *crtc,
10513                                            struct drm_display_mode *mode,
10514                                            struct drm_framebuffer *fb,
10515                                            int x, int y)
10516 {
10517         struct drm_plane_state *plane_state;
10518         int hdisplay, vdisplay;
10519         int ret;
10520
10521         plane_state = drm_atomic_get_plane_state(state, crtc->primary);
10522         if (IS_ERR(plane_state))
10523                 return PTR_ERR(plane_state);
10524
10525         if (mode)
10526                 drm_crtc_get_hv_timing(mode, &hdisplay, &vdisplay);
10527         else
10528                 hdisplay = vdisplay = 0;
10529
10530         ret = drm_atomic_set_crtc_for_plane(plane_state, fb ? crtc : NULL);
10531         if (ret)
10532                 return ret;
10533         drm_atomic_set_fb_for_plane(plane_state, fb);
10534         plane_state->crtc_x = 0;
10535         plane_state->crtc_y = 0;
10536         plane_state->crtc_w = hdisplay;
10537         plane_state->crtc_h = vdisplay;
10538         plane_state->src_x = x << 16;
10539         plane_state->src_y = y << 16;
10540         plane_state->src_w = hdisplay << 16;
10541         plane_state->src_h = vdisplay << 16;
10542
10543         return 0;
10544 }
10545
10546 bool intel_get_load_detect_pipe(struct drm_connector *connector,
10547                                 struct drm_display_mode *mode,
10548                                 struct intel_load_detect_pipe *old,
10549                                 struct drm_modeset_acquire_ctx *ctx)
10550 {
10551         struct intel_crtc *intel_crtc;
10552         struct intel_encoder *intel_encoder =
10553                 intel_attached_encoder(connector);
10554         struct drm_crtc *possible_crtc;
10555         struct drm_encoder *encoder = &intel_encoder->base;
10556         struct drm_crtc *crtc = NULL;
10557         struct drm_device *dev = encoder->dev;
10558         struct drm_framebuffer *fb;
10559         struct drm_mode_config *config = &dev->mode_config;
10560         struct drm_atomic_state *state = NULL, *restore_state = NULL;
10561         struct drm_connector_state *connector_state;
10562         struct intel_crtc_state *crtc_state;
10563         int ret, i = -1;
10564
10565         DRM_DEBUG_KMS("[CONNECTOR:%d:%s], [ENCODER:%d:%s]\n",
10566                       connector->base.id, connector->name,
10567                       encoder->base.id, encoder->name);
10568
10569         old->restore_state = NULL;
10570
10571 retry:
10572         ret = drm_modeset_lock(&config->connection_mutex, ctx);
10573         if (ret)
10574                 goto fail;
10575
10576         /*
10577          * Algorithm gets a little messy:
10578          *
10579          *   - if the connector already has an assigned crtc, use it (but make
10580          *     sure it's on first)
10581          *
10582          *   - try to find the first unused crtc that can drive this connector,
10583          *     and use that if we find one
10584          */
10585
10586         /* See if we already have a CRTC for this connector */
10587         if (connector->state->crtc) {
10588                 crtc = connector->state->crtc;
10589
10590                 ret = drm_modeset_lock(&crtc->mutex, ctx);
10591                 if (ret)
10592                         goto fail;
10593
10594                 /* Make sure the crtc and connector are running */
10595                 goto found;
10596         }
10597
10598         /* Find an unused one (if possible) */
10599         for_each_crtc(dev, possible_crtc) {
10600                 i++;
10601                 if (!(encoder->possible_crtcs & (1 << i)))
10602                         continue;
10603
10604                 ret = drm_modeset_lock(&possible_crtc->mutex, ctx);
10605                 if (ret)
10606                         goto fail;
10607
10608                 if (possible_crtc->state->enable) {
10609                         drm_modeset_unlock(&possible_crtc->mutex);
10610                         continue;
10611                 }
10612
10613                 crtc = possible_crtc;
10614                 break;
10615         }
10616
10617         /*
10618          * If we didn't find an unused CRTC, don't use any.
10619          */
10620         if (!crtc) {
10621                 DRM_DEBUG_KMS("no pipe available for load-detect\n");
10622                 goto fail;
10623         }
10624
10625 found:
10626         intel_crtc = to_intel_crtc(crtc);
10627
10628         ret = drm_modeset_lock(&crtc->primary->mutex, ctx);
10629         if (ret)
10630                 goto fail;
10631
10632         state = drm_atomic_state_alloc(dev);
10633         restore_state = drm_atomic_state_alloc(dev);
10634         if (!state || !restore_state) {
10635                 ret = -ENOMEM;
10636                 goto fail;
10637         }
10638
10639         state->acquire_ctx = ctx;
10640         restore_state->acquire_ctx = ctx;
10641
10642         connector_state = drm_atomic_get_connector_state(state, connector);
10643         if (IS_ERR(connector_state)) {
10644                 ret = PTR_ERR(connector_state);
10645                 goto fail;
10646         }
10647
10648         ret = drm_atomic_set_crtc_for_connector(connector_state, crtc);
10649         if (ret)
10650                 goto fail;
10651
10652         crtc_state = intel_atomic_get_crtc_state(state, intel_crtc);
10653         if (IS_ERR(crtc_state)) {
10654                 ret = PTR_ERR(crtc_state);
10655                 goto fail;
10656         }
10657
10658         crtc_state->base.active = crtc_state->base.enable = true;
10659
10660         if (!mode)
10661                 mode = &load_detect_mode;
10662
10663         /* We need a framebuffer large enough to accommodate all accesses
10664          * that the plane may generate whilst we perform load detection.
10665          * We can not rely on the fbcon either being present (we get called
10666          * during its initialisation to detect all boot displays, or it may
10667          * not even exist) or that it is large enough to satisfy the
10668          * requested mode.
10669          */
10670         fb = mode_fits_in_fbdev(dev, mode);
10671         if (fb == NULL) {
10672                 DRM_DEBUG_KMS("creating tmp fb for load-detection\n");
10673                 fb = intel_framebuffer_create_for_mode(dev, mode, 24, 32);
10674         } else
10675                 DRM_DEBUG_KMS("reusing fbdev for load-detection framebuffer\n");
10676         if (IS_ERR(fb)) {
10677                 DRM_DEBUG_KMS("failed to allocate framebuffer for load-detection\n");
10678                 goto fail;
10679         }
10680
10681         ret = intel_modeset_setup_plane_state(state, crtc, mode, fb, 0, 0);
10682         if (ret)
10683                 goto fail;
10684
10685         drm_framebuffer_unreference(fb);
10686
10687         ret = drm_atomic_set_mode_for_crtc(&crtc_state->base, mode);
10688         if (ret)
10689                 goto fail;
10690
10691         ret = PTR_ERR_OR_ZERO(drm_atomic_get_connector_state(restore_state, connector));
10692         if (!ret)
10693                 ret = PTR_ERR_OR_ZERO(drm_atomic_get_crtc_state(restore_state, crtc));
10694         if (!ret)
10695                 ret = PTR_ERR_OR_ZERO(drm_atomic_get_plane_state(restore_state, crtc->primary));
10696         if (ret) {
10697                 DRM_DEBUG_KMS("Failed to create a copy of old state to restore: %i\n", ret);
10698                 goto fail;
10699         }
10700
10701         ret = drm_atomic_commit(state);
10702         if (ret) {
10703                 DRM_DEBUG_KMS("failed to set mode on load-detect pipe\n");
10704                 goto fail;
10705         }
10706
10707         old->restore_state = restore_state;
10708
10709         /* let the connector get through one full cycle before testing */
10710         intel_wait_for_vblank(dev, intel_crtc->pipe);
10711         return true;
10712
10713 fail:
10714         drm_atomic_state_free(state);
10715         drm_atomic_state_free(restore_state);
10716         restore_state = state = NULL;
10717
10718         if (ret == -EDEADLK) {
10719                 drm_modeset_backoff(ctx);
10720                 goto retry;
10721         }
10722
10723         return false;
10724 }
10725
10726 void intel_release_load_detect_pipe(struct drm_connector *connector,
10727                                     struct intel_load_detect_pipe *old,
10728                                     struct drm_modeset_acquire_ctx *ctx)
10729 {
10730         struct intel_encoder *intel_encoder =
10731                 intel_attached_encoder(connector);
10732         struct drm_encoder *encoder = &intel_encoder->base;
10733         struct drm_atomic_state *state = old->restore_state;
10734         int ret;
10735
10736         DRM_DEBUG_KMS("[CONNECTOR:%d:%s], [ENCODER:%d:%s]\n",
10737                       connector->base.id, connector->name,
10738                       encoder->base.id, encoder->name);
10739
10740         if (!state)
10741                 return;
10742
10743         ret = drm_atomic_commit(state);
10744         if (ret) {
10745                 DRM_DEBUG_KMS("Couldn't release load detect pipe: %i\n", ret);
10746                 drm_atomic_state_free(state);
10747         }
10748 }
10749
10750 static int i9xx_pll_refclk(struct drm_device *dev,
10751                            const struct intel_crtc_state *pipe_config)
10752 {
10753         struct drm_i915_private *dev_priv = dev->dev_private;
10754         u32 dpll = pipe_config->dpll_hw_state.dpll;
10755
10756         if ((dpll & PLL_REF_INPUT_MASK) == PLLB_REF_INPUT_SPREADSPECTRUMIN)
10757                 return dev_priv->vbt.lvds_ssc_freq;
10758         else if (HAS_PCH_SPLIT(dev))
10759                 return 120000;
10760         else if (!IS_GEN2(dev))
10761                 return 96000;
10762         else
10763                 return 48000;
10764 }
10765
10766 /* Returns the clock of the currently programmed mode of the given pipe. */
10767 static void i9xx_crtc_clock_get(struct intel_crtc *crtc,
10768                                 struct intel_crtc_state *pipe_config)
10769 {
10770         struct drm_device *dev = crtc->base.dev;
10771         struct drm_i915_private *dev_priv = dev->dev_private;
10772         int pipe = pipe_config->cpu_transcoder;
10773         u32 dpll = pipe_config->dpll_hw_state.dpll;
10774         u32 fp;
10775         struct dpll clock;
10776         int port_clock;
10777         int refclk = i9xx_pll_refclk(dev, pipe_config);
10778
10779         if ((dpll & DISPLAY_RATE_SELECT_FPA1) == 0)
10780                 fp = pipe_config->dpll_hw_state.fp0;
10781         else
10782                 fp = pipe_config->dpll_hw_state.fp1;
10783
10784         clock.m1 = (fp & FP_M1_DIV_MASK) >> FP_M1_DIV_SHIFT;
10785         if (IS_PINEVIEW(dev)) {
10786                 clock.n = ffs((fp & FP_N_PINEVIEW_DIV_MASK) >> FP_N_DIV_SHIFT) - 1;
10787                 clock.m2 = (fp & FP_M2_PINEVIEW_DIV_MASK) >> FP_M2_DIV_SHIFT;
10788         } else {
10789                 clock.n = (fp & FP_N_DIV_MASK) >> FP_N_DIV_SHIFT;
10790                 clock.m2 = (fp & FP_M2_DIV_MASK) >> FP_M2_DIV_SHIFT;
10791         }
10792
10793         if (!IS_GEN2(dev)) {
10794                 if (IS_PINEVIEW(dev))
10795                         clock.p1 = ffs((dpll & DPLL_FPA01_P1_POST_DIV_MASK_PINEVIEW) >>
10796                                 DPLL_FPA01_P1_POST_DIV_SHIFT_PINEVIEW);
10797                 else
10798                         clock.p1 = ffs((dpll & DPLL_FPA01_P1_POST_DIV_MASK) >>
10799                                DPLL_FPA01_P1_POST_DIV_SHIFT);
10800
10801                 switch (dpll & DPLL_MODE_MASK) {
10802                 case DPLLB_MODE_DAC_SERIAL:
10803                         clock.p2 = dpll & DPLL_DAC_SERIAL_P2_CLOCK_DIV_5 ?
10804                                 5 : 10;
10805                         break;
10806                 case DPLLB_MODE_LVDS:
10807                         clock.p2 = dpll & DPLLB_LVDS_P2_CLOCK_DIV_7 ?
10808                                 7 : 14;
10809                         break;
10810                 default:
10811                         DRM_DEBUG_KMS("Unknown DPLL mode %08x in programmed "
10812                                   "mode\n", (int)(dpll & DPLL_MODE_MASK));
10813                         return;
10814                 }
10815
10816                 if (IS_PINEVIEW(dev))
10817                         port_clock = pnv_calc_dpll_params(refclk, &clock);
10818                 else
10819                         port_clock = i9xx_calc_dpll_params(refclk, &clock);
10820         } else {
10821                 u32 lvds = IS_I830(dev) ? 0 : I915_READ(LVDS);
10822                 bool is_lvds = (pipe == 1) && (lvds & LVDS_PORT_EN);
10823
10824                 if (is_lvds) {
10825                         clock.p1 = ffs((dpll & DPLL_FPA01_P1_POST_DIV_MASK_I830_LVDS) >>
10826                                        DPLL_FPA01_P1_POST_DIV_SHIFT);
10827
10828                         if (lvds & LVDS_CLKB_POWER_UP)
10829                                 clock.p2 = 7;
10830                         else
10831                                 clock.p2 = 14;
10832                 } else {
10833                         if (dpll & PLL_P1_DIVIDE_BY_TWO)
10834                                 clock.p1 = 2;
10835                         else {
10836                                 clock.p1 = ((dpll & DPLL_FPA01_P1_POST_DIV_MASK_I830) >>
10837                                             DPLL_FPA01_P1_POST_DIV_SHIFT) + 2;
10838                         }
10839                         if (dpll & PLL_P2_DIVIDE_BY_4)
10840                                 clock.p2 = 4;
10841                         else
10842                                 clock.p2 = 2;
10843                 }
10844
10845                 port_clock = i9xx_calc_dpll_params(refclk, &clock);
10846         }
10847
10848         /*
10849          * This value includes pixel_multiplier. We will use
10850          * port_clock to compute adjusted_mode.crtc_clock in the
10851          * encoder's get_config() function.
10852          */
10853         pipe_config->port_clock = port_clock;
10854 }
10855
10856 int intel_dotclock_calculate(int link_freq,
10857                              const struct intel_link_m_n *m_n)
10858 {
10859         /*
10860          * The calculation for the data clock is:
10861          * pixel_clock = ((m/n)*(link_clock * nr_lanes))/bpp
10862          * But we want to avoid losing precison if possible, so:
10863          * pixel_clock = ((m * link_clock * nr_lanes)/(n*bpp))
10864          *
10865          * and the link clock is simpler:
10866          * link_clock = (m * link_clock) / n
10867          */
10868
10869         if (!m_n->link_n)
10870                 return 0;
10871
10872         return div_u64((u64)m_n->link_m * link_freq, m_n->link_n);
10873 }
10874
10875 static void ironlake_pch_clock_get(struct intel_crtc *crtc,
10876                                    struct intel_crtc_state *pipe_config)
10877 {
10878         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
10879
10880         /* read out port_clock from the DPLL */
10881         i9xx_crtc_clock_get(crtc, pipe_config);
10882
10883         /*
10884          * In case there is an active pipe without active ports,
10885          * we may need some idea for the dotclock anyway.
10886          * Calculate one based on the FDI configuration.
10887          */
10888         pipe_config->base.adjusted_mode.crtc_clock =
10889                 intel_dotclock_calculate(intel_fdi_link_freq(dev_priv, pipe_config),
10890                                          &pipe_config->fdi_m_n);
10891 }
10892
10893 /** Returns the currently programmed mode of the given pipe. */
10894 struct drm_display_mode *intel_crtc_mode_get(struct drm_device *dev,
10895                                              struct drm_crtc *crtc)
10896 {
10897         struct drm_i915_private *dev_priv = dev->dev_private;
10898         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
10899         enum transcoder cpu_transcoder = intel_crtc->config->cpu_transcoder;
10900         struct drm_display_mode *mode;
10901         struct intel_crtc_state *pipe_config;
10902         int htot = I915_READ(HTOTAL(cpu_transcoder));
10903         int hsync = I915_READ(HSYNC(cpu_transcoder));
10904         int vtot = I915_READ(VTOTAL(cpu_transcoder));
10905         int vsync = I915_READ(VSYNC(cpu_transcoder));
10906         enum pipe pipe = intel_crtc->pipe;
10907
10908         mode = kzalloc(sizeof(*mode), GFP_KERNEL);
10909         if (!mode)
10910                 return NULL;
10911
10912         pipe_config = kzalloc(sizeof(*pipe_config), GFP_KERNEL);
10913         if (!pipe_config) {
10914                 kfree(mode);
10915                 return NULL;
10916         }
10917
10918         /*
10919          * Construct a pipe_config sufficient for getting the clock info
10920          * back out of crtc_clock_get.
10921          *
10922          * Note, if LVDS ever uses a non-1 pixel multiplier, we'll need
10923          * to use a real value here instead.
10924          */
10925         pipe_config->cpu_transcoder = (enum transcoder) pipe;
10926         pipe_config->pixel_multiplier = 1;
10927         pipe_config->dpll_hw_state.dpll = I915_READ(DPLL(pipe));
10928         pipe_config->dpll_hw_state.fp0 = I915_READ(FP0(pipe));
10929         pipe_config->dpll_hw_state.fp1 = I915_READ(FP1(pipe));
10930         i9xx_crtc_clock_get(intel_crtc, pipe_config);
10931
10932         mode->clock = pipe_config->port_clock / pipe_config->pixel_multiplier;
10933         mode->hdisplay = (htot & 0xffff) + 1;
10934         mode->htotal = ((htot & 0xffff0000) >> 16) + 1;
10935         mode->hsync_start = (hsync & 0xffff) + 1;
10936         mode->hsync_end = ((hsync & 0xffff0000) >> 16) + 1;
10937         mode->vdisplay = (vtot & 0xffff) + 1;
10938         mode->vtotal = ((vtot & 0xffff0000) >> 16) + 1;
10939         mode->vsync_start = (vsync & 0xffff) + 1;
10940         mode->vsync_end = ((vsync & 0xffff0000) >> 16) + 1;
10941
10942         drm_mode_set_name(mode);
10943
10944         kfree(pipe_config);
10945
10946         return mode;
10947 }
10948
10949 void intel_mark_busy(struct drm_i915_private *dev_priv)
10950 {
10951         if (dev_priv->mm.busy)
10952                 return;
10953
10954         intel_runtime_pm_get(dev_priv);
10955         i915_update_gfx_val(dev_priv);
10956         if (INTEL_GEN(dev_priv) >= 6)
10957                 gen6_rps_busy(dev_priv);
10958         dev_priv->mm.busy = true;
10959 }
10960
10961 void intel_mark_idle(struct drm_i915_private *dev_priv)
10962 {
10963         if (!dev_priv->mm.busy)
10964                 return;
10965
10966         dev_priv->mm.busy = false;
10967
10968         if (INTEL_GEN(dev_priv) >= 6)
10969                 gen6_rps_idle(dev_priv);
10970
10971         intel_runtime_pm_put(dev_priv);
10972 }
10973
10974 static void intel_crtc_destroy(struct drm_crtc *crtc)
10975 {
10976         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
10977         struct drm_device *dev = crtc->dev;
10978         struct intel_flip_work *work;
10979
10980         spin_lock_irq(&dev->event_lock);
10981         work = intel_crtc->flip_work;
10982         intel_crtc->flip_work = NULL;
10983         spin_unlock_irq(&dev->event_lock);
10984
10985         if (work) {
10986                 cancel_work_sync(&work->mmio_work);
10987                 cancel_work_sync(&work->unpin_work);
10988                 kfree(work);
10989         }
10990
10991         drm_crtc_cleanup(crtc);
10992
10993         kfree(intel_crtc);
10994 }
10995
10996 static void intel_unpin_work_fn(struct work_struct *__work)
10997 {
10998         struct intel_flip_work *work =
10999                 container_of(__work, struct intel_flip_work, unpin_work);
11000         struct intel_crtc *crtc = to_intel_crtc(work->crtc);
11001         struct drm_device *dev = crtc->base.dev;
11002         struct drm_plane *primary = crtc->base.primary;
11003
11004         if (is_mmio_work(work))
11005                 flush_work(&work->mmio_work);
11006
11007         mutex_lock(&dev->struct_mutex);
11008         intel_unpin_fb_obj(work->old_fb, primary->state->rotation);
11009         drm_gem_object_unreference(&work->pending_flip_obj->base);
11010
11011         if (work->flip_queued_req)
11012                 i915_gem_request_assign(&work->flip_queued_req, NULL);
11013         mutex_unlock(&dev->struct_mutex);
11014
11015         intel_frontbuffer_flip_complete(dev, to_intel_plane(primary)->frontbuffer_bit);
11016         intel_fbc_post_update(crtc);
11017         drm_framebuffer_unreference(work->old_fb);
11018
11019         BUG_ON(atomic_read(&crtc->unpin_work_count) == 0);
11020         atomic_dec(&crtc->unpin_work_count);
11021
11022         kfree(work);
11023 }
11024
11025 /* Is 'a' after or equal to 'b'? */
11026 static bool g4x_flip_count_after_eq(u32 a, u32 b)
11027 {
11028         return !((a - b) & 0x80000000);
11029 }
11030
11031 static bool __pageflip_finished_cs(struct intel_crtc *crtc,
11032                                    struct intel_flip_work *work)
11033 {
11034         struct drm_device *dev = crtc->base.dev;
11035         struct drm_i915_private *dev_priv = dev->dev_private;
11036         unsigned reset_counter;
11037
11038         reset_counter = i915_reset_counter(&dev_priv->gpu_error);
11039         if (crtc->reset_counter != reset_counter)
11040                 return true;
11041
11042         /*
11043          * The relevant registers doen't exist on pre-ctg.
11044          * As the flip done interrupt doesn't trigger for mmio
11045          * flips on gmch platforms, a flip count check isn't
11046          * really needed there. But since ctg has the registers,
11047          * include it in the check anyway.
11048          */
11049         if (INTEL_INFO(dev)->gen < 5 && !IS_G4X(dev))
11050                 return true;
11051
11052         /*
11053          * BDW signals flip done immediately if the plane
11054          * is disabled, even if the plane enable is already
11055          * armed to occur at the next vblank :(
11056          */
11057
11058         /*
11059          * A DSPSURFLIVE check isn't enough in case the mmio and CS flips
11060          * used the same base address. In that case the mmio flip might
11061          * have completed, but the CS hasn't even executed the flip yet.
11062          *
11063          * A flip count check isn't enough as the CS might have updated
11064          * the base address just after start of vblank, but before we
11065          * managed to process the interrupt. This means we'd complete the
11066          * CS flip too soon.
11067          *
11068          * Combining both checks should get us a good enough result. It may
11069          * still happen that the CS flip has been executed, but has not
11070          * yet actually completed. But in case the base address is the same
11071          * anyway, we don't really care.
11072          */
11073         return (I915_READ(DSPSURFLIVE(crtc->plane)) & ~0xfff) ==
11074                 crtc->flip_work->gtt_offset &&
11075                 g4x_flip_count_after_eq(I915_READ(PIPE_FLIPCOUNT_G4X(crtc->pipe)),
11076                                     crtc->flip_work->flip_count);
11077 }
11078
11079 static bool
11080 __pageflip_finished_mmio(struct intel_crtc *crtc,
11081                                struct intel_flip_work *work)
11082 {
11083         /*
11084          * MMIO work completes when vblank is different from
11085          * flip_queued_vblank.
11086          *
11087          * Reset counter value doesn't matter, this is handled by
11088          * i915_wait_request finishing early, so no need to handle
11089          * reset here.
11090          */
11091         return intel_crtc_get_vblank_counter(crtc) != work->flip_queued_vblank;
11092 }
11093
11094
11095 static bool pageflip_finished(struct intel_crtc *crtc,
11096                               struct intel_flip_work *work)
11097 {
11098         if (!atomic_read(&work->pending))
11099                 return false;
11100
11101         smp_rmb();
11102
11103         if (is_mmio_work(work))
11104                 return __pageflip_finished_mmio(crtc, work);
11105         else
11106                 return __pageflip_finished_cs(crtc, work);
11107 }
11108
11109 void intel_finish_page_flip_cs(struct drm_i915_private *dev_priv, int pipe)
11110 {
11111         struct drm_device *dev = dev_priv->dev;
11112         struct drm_crtc *crtc = dev_priv->pipe_to_crtc_mapping[pipe];
11113         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
11114         struct intel_flip_work *work;
11115         unsigned long flags;
11116
11117         /* Ignore early vblank irqs */
11118         if (!crtc)
11119                 return;
11120
11121         /*
11122          * This is called both by irq handlers and the reset code (to complete
11123          * lost pageflips) so needs the full irqsave spinlocks.
11124          */
11125         spin_lock_irqsave(&dev->event_lock, flags);
11126         work = intel_crtc->flip_work;
11127
11128         if (work != NULL &&
11129             !is_mmio_work(work) &&
11130             pageflip_finished(intel_crtc, work))
11131                 page_flip_completed(intel_crtc);
11132
11133         spin_unlock_irqrestore(&dev->event_lock, flags);
11134 }
11135
11136 void intel_finish_page_flip_mmio(struct drm_i915_private *dev_priv, int pipe)
11137 {
11138         struct drm_device *dev = dev_priv->dev;
11139         struct drm_crtc *crtc = dev_priv->pipe_to_crtc_mapping[pipe];
11140         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
11141         struct intel_flip_work *work;
11142         unsigned long flags;
11143
11144         /* Ignore early vblank irqs */
11145         if (!crtc)
11146                 return;
11147
11148         /*
11149          * This is called both by irq handlers and the reset code (to complete
11150          * lost pageflips) so needs the full irqsave spinlocks.
11151          */
11152         spin_lock_irqsave(&dev->event_lock, flags);
11153         work = intel_crtc->flip_work;
11154
11155         if (work != NULL &&
11156             is_mmio_work(work) &&
11157             pageflip_finished(intel_crtc, work))
11158                 page_flip_completed(intel_crtc);
11159
11160         spin_unlock_irqrestore(&dev->event_lock, flags);
11161 }
11162
11163 static inline void intel_mark_page_flip_active(struct intel_crtc *crtc,
11164                                                struct intel_flip_work *work)
11165 {
11166         work->flip_queued_vblank = intel_crtc_get_vblank_counter(crtc);
11167
11168         /* Ensure that the work item is consistent when activating it ... */
11169         smp_mb__before_atomic();
11170         atomic_set(&work->pending, 1);
11171 }
11172
11173 static int intel_gen2_queue_flip(struct drm_device *dev,
11174                                  struct drm_crtc *crtc,
11175                                  struct drm_framebuffer *fb,
11176                                  struct drm_i915_gem_object *obj,
11177                                  struct drm_i915_gem_request *req,
11178                                  uint32_t flags)
11179 {
11180         struct intel_engine_cs *engine = req->engine;
11181         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
11182         u32 flip_mask;
11183         int ret;
11184
11185         ret = intel_ring_begin(req, 6);
11186         if (ret)
11187                 return ret;
11188
11189         /* Can't queue multiple flips, so wait for the previous
11190          * one to finish before executing the next.
11191          */
11192         if (intel_crtc->plane)
11193                 flip_mask = MI_WAIT_FOR_PLANE_B_FLIP;
11194         else
11195                 flip_mask = MI_WAIT_FOR_PLANE_A_FLIP;
11196         intel_ring_emit(engine, MI_WAIT_FOR_EVENT | flip_mask);
11197         intel_ring_emit(engine, MI_NOOP);
11198         intel_ring_emit(engine, MI_DISPLAY_FLIP |
11199                         MI_DISPLAY_FLIP_PLANE(intel_crtc->plane));
11200         intel_ring_emit(engine, fb->pitches[0]);
11201         intel_ring_emit(engine, intel_crtc->flip_work->gtt_offset);
11202         intel_ring_emit(engine, 0); /* aux display base address, unused */
11203
11204         return 0;
11205 }
11206
11207 static int intel_gen3_queue_flip(struct drm_device *dev,
11208                                  struct drm_crtc *crtc,
11209                                  struct drm_framebuffer *fb,
11210                                  struct drm_i915_gem_object *obj,
11211                                  struct drm_i915_gem_request *req,
11212                                  uint32_t flags)
11213 {
11214         struct intel_engine_cs *engine = req->engine;
11215         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
11216         u32 flip_mask;
11217         int ret;
11218
11219         ret = intel_ring_begin(req, 6);
11220         if (ret)
11221                 return ret;
11222
11223         if (intel_crtc->plane)
11224                 flip_mask = MI_WAIT_FOR_PLANE_B_FLIP;
11225         else
11226                 flip_mask = MI_WAIT_FOR_PLANE_A_FLIP;
11227         intel_ring_emit(engine, MI_WAIT_FOR_EVENT | flip_mask);
11228         intel_ring_emit(engine, MI_NOOP);
11229         intel_ring_emit(engine, MI_DISPLAY_FLIP_I915 |
11230                         MI_DISPLAY_FLIP_PLANE(intel_crtc->plane));
11231         intel_ring_emit(engine, fb->pitches[0]);
11232         intel_ring_emit(engine, intel_crtc->flip_work->gtt_offset);
11233         intel_ring_emit(engine, MI_NOOP);
11234
11235         return 0;
11236 }
11237
11238 static int intel_gen4_queue_flip(struct drm_device *dev,
11239                                  struct drm_crtc *crtc,
11240                                  struct drm_framebuffer *fb,
11241                                  struct drm_i915_gem_object *obj,
11242                                  struct drm_i915_gem_request *req,
11243                                  uint32_t flags)
11244 {
11245         struct intel_engine_cs *engine = req->engine;
11246         struct drm_i915_private *dev_priv = dev->dev_private;
11247         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
11248         uint32_t pf, pipesrc;
11249         int ret;
11250
11251         ret = intel_ring_begin(req, 4);
11252         if (ret)
11253                 return ret;
11254
11255         /* i965+ uses the linear or tiled offsets from the
11256          * Display Registers (which do not change across a page-flip)
11257          * so we need only reprogram the base address.
11258          */
11259         intel_ring_emit(engine, MI_DISPLAY_FLIP |
11260                         MI_DISPLAY_FLIP_PLANE(intel_crtc->plane));
11261         intel_ring_emit(engine, fb->pitches[0]);
11262         intel_ring_emit(engine, intel_crtc->flip_work->gtt_offset |
11263                         obj->tiling_mode);
11264
11265         /* XXX Enabling the panel-fitter across page-flip is so far
11266          * untested on non-native modes, so ignore it for now.
11267          * pf = I915_READ(pipe == 0 ? PFA_CTL_1 : PFB_CTL_1) & PF_ENABLE;
11268          */
11269         pf = 0;
11270         pipesrc = I915_READ(PIPESRC(intel_crtc->pipe)) & 0x0fff0fff;
11271         intel_ring_emit(engine, pf | pipesrc);
11272
11273         return 0;
11274 }
11275
11276 static int intel_gen6_queue_flip(struct drm_device *dev,
11277                                  struct drm_crtc *crtc,
11278                                  struct drm_framebuffer *fb,
11279                                  struct drm_i915_gem_object *obj,
11280                                  struct drm_i915_gem_request *req,
11281                                  uint32_t flags)
11282 {
11283         struct intel_engine_cs *engine = req->engine;
11284         struct drm_i915_private *dev_priv = dev->dev_private;
11285         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
11286         uint32_t pf, pipesrc;
11287         int ret;
11288
11289         ret = intel_ring_begin(req, 4);
11290         if (ret)
11291                 return ret;
11292
11293         intel_ring_emit(engine, MI_DISPLAY_FLIP |
11294                         MI_DISPLAY_FLIP_PLANE(intel_crtc->plane));
11295         intel_ring_emit(engine, fb->pitches[0] | obj->tiling_mode);
11296         intel_ring_emit(engine, intel_crtc->flip_work->gtt_offset);
11297
11298         /* Contrary to the suggestions in the documentation,
11299          * "Enable Panel Fitter" does not seem to be required when page
11300          * flipping with a non-native mode, and worse causes a normal
11301          * modeset to fail.
11302          * pf = I915_READ(PF_CTL(intel_crtc->pipe)) & PF_ENABLE;
11303          */
11304         pf = 0;
11305         pipesrc = I915_READ(PIPESRC(intel_crtc->pipe)) & 0x0fff0fff;
11306         intel_ring_emit(engine, pf | pipesrc);
11307
11308         return 0;
11309 }
11310
11311 static int intel_gen7_queue_flip(struct drm_device *dev,
11312                                  struct drm_crtc *crtc,
11313                                  struct drm_framebuffer *fb,
11314                                  struct drm_i915_gem_object *obj,
11315                                  struct drm_i915_gem_request *req,
11316                                  uint32_t flags)
11317 {
11318         struct intel_engine_cs *engine = req->engine;
11319         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
11320         uint32_t plane_bit = 0;
11321         int len, ret;
11322
11323         switch (intel_crtc->plane) {
11324         case PLANE_A:
11325                 plane_bit = MI_DISPLAY_FLIP_IVB_PLANE_A;
11326                 break;
11327         case PLANE_B:
11328                 plane_bit = MI_DISPLAY_FLIP_IVB_PLANE_B;
11329                 break;
11330         case PLANE_C:
11331                 plane_bit = MI_DISPLAY_FLIP_IVB_PLANE_C;
11332                 break;
11333         default:
11334                 WARN_ONCE(1, "unknown plane in flip command\n");
11335                 return -ENODEV;
11336         }
11337
11338         len = 4;
11339         if (engine->id == RCS) {
11340                 len += 6;
11341                 /*
11342                  * On Gen 8, SRM is now taking an extra dword to accommodate
11343                  * 48bits addresses, and we need a NOOP for the batch size to
11344                  * stay even.
11345                  */
11346                 if (IS_GEN8(dev))
11347                         len += 2;
11348         }
11349
11350         /*
11351          * BSpec MI_DISPLAY_FLIP for IVB:
11352          * "The full packet must be contained within the same cache line."
11353          *
11354          * Currently the LRI+SRM+MI_DISPLAY_FLIP all fit within the same
11355          * cacheline, if we ever start emitting more commands before
11356          * the MI_DISPLAY_FLIP we may need to first emit everything else,
11357          * then do the cacheline alignment, and finally emit the
11358          * MI_DISPLAY_FLIP.
11359          */
11360         ret = intel_ring_cacheline_align(req);
11361         if (ret)
11362                 return ret;
11363
11364         ret = intel_ring_begin(req, len);
11365         if (ret)
11366                 return ret;
11367
11368         /* Unmask the flip-done completion message. Note that the bspec says that
11369          * we should do this for both the BCS and RCS, and that we must not unmask
11370          * more than one flip event at any time (or ensure that one flip message
11371          * can be sent by waiting for flip-done prior to queueing new flips).
11372          * Experimentation says that BCS works despite DERRMR masking all
11373          * flip-done completion events and that unmasking all planes at once
11374          * for the RCS also doesn't appear to drop events. Setting the DERRMR
11375          * to zero does lead to lockups within MI_DISPLAY_FLIP.
11376          */
11377         if (engine->id == RCS) {
11378                 intel_ring_emit(engine, MI_LOAD_REGISTER_IMM(1));
11379                 intel_ring_emit_reg(engine, DERRMR);
11380                 intel_ring_emit(engine, ~(DERRMR_PIPEA_PRI_FLIP_DONE |
11381                                           DERRMR_PIPEB_PRI_FLIP_DONE |
11382                                           DERRMR_PIPEC_PRI_FLIP_DONE));
11383                 if (IS_GEN8(dev))
11384                         intel_ring_emit(engine, MI_STORE_REGISTER_MEM_GEN8 |
11385                                               MI_SRM_LRM_GLOBAL_GTT);
11386                 else
11387                         intel_ring_emit(engine, MI_STORE_REGISTER_MEM |
11388                                               MI_SRM_LRM_GLOBAL_GTT);
11389                 intel_ring_emit_reg(engine, DERRMR);
11390                 intel_ring_emit(engine, engine->scratch.gtt_offset + 256);
11391                 if (IS_GEN8(dev)) {
11392                         intel_ring_emit(engine, 0);
11393                         intel_ring_emit(engine, MI_NOOP);
11394                 }
11395         }
11396
11397         intel_ring_emit(engine, MI_DISPLAY_FLIP_I915 | plane_bit);
11398         intel_ring_emit(engine, (fb->pitches[0] | obj->tiling_mode));
11399         intel_ring_emit(engine, intel_crtc->flip_work->gtt_offset);
11400         intel_ring_emit(engine, (MI_NOOP));
11401
11402         return 0;
11403 }
11404
11405 static bool use_mmio_flip(struct intel_engine_cs *engine,
11406                           struct drm_i915_gem_object *obj)
11407 {
11408         /*
11409          * This is not being used for older platforms, because
11410          * non-availability of flip done interrupt forces us to use
11411          * CS flips. Older platforms derive flip done using some clever
11412          * tricks involving the flip_pending status bits and vblank irqs.
11413          * So using MMIO flips there would disrupt this mechanism.
11414          */
11415
11416         if (engine == NULL)
11417                 return true;
11418
11419         if (INTEL_GEN(engine->i915) < 5)
11420                 return false;
11421
11422         if (i915.use_mmio_flip < 0)
11423                 return false;
11424         else if (i915.use_mmio_flip > 0)
11425                 return true;
11426         else if (i915.enable_execlists)
11427                 return true;
11428         else if (obj->base.dma_buf &&
11429                  !reservation_object_test_signaled_rcu(obj->base.dma_buf->resv,
11430                                                        false))
11431                 return true;
11432         else
11433                 return engine != i915_gem_request_get_engine(obj->last_write_req);
11434 }
11435
11436 static void skl_do_mmio_flip(struct intel_crtc *intel_crtc,
11437                              unsigned int rotation,
11438                              struct intel_flip_work *work)
11439 {
11440         struct drm_device *dev = intel_crtc->base.dev;
11441         struct drm_i915_private *dev_priv = dev->dev_private;
11442         struct drm_framebuffer *fb = intel_crtc->base.primary->fb;
11443         const enum pipe pipe = intel_crtc->pipe;
11444         u32 ctl, stride, tile_height;
11445
11446         ctl = I915_READ(PLANE_CTL(pipe, 0));
11447         ctl &= ~PLANE_CTL_TILED_MASK;
11448         switch (fb->modifier[0]) {
11449         case DRM_FORMAT_MOD_NONE:
11450                 break;
11451         case I915_FORMAT_MOD_X_TILED:
11452                 ctl |= PLANE_CTL_TILED_X;
11453                 break;
11454         case I915_FORMAT_MOD_Y_TILED:
11455                 ctl |= PLANE_CTL_TILED_Y;
11456                 break;
11457         case I915_FORMAT_MOD_Yf_TILED:
11458                 ctl |= PLANE_CTL_TILED_YF;
11459                 break;
11460         default:
11461                 MISSING_CASE(fb->modifier[0]);
11462         }
11463
11464         /*
11465          * The stride is either expressed as a multiple of 64 bytes chunks for
11466          * linear buffers or in number of tiles for tiled buffers.
11467          */
11468         if (intel_rotation_90_or_270(rotation)) {
11469                 /* stride = Surface height in tiles */
11470                 tile_height = intel_tile_height(dev_priv, fb->modifier[0], 0);
11471                 stride = DIV_ROUND_UP(fb->height, tile_height);
11472         } else {
11473                 stride = fb->pitches[0] /
11474                         intel_fb_stride_alignment(dev_priv, fb->modifier[0],
11475                                                   fb->pixel_format);
11476         }
11477
11478         /*
11479          * Both PLANE_CTL and PLANE_STRIDE are not updated on vblank but on
11480          * PLANE_SURF updates, the update is then guaranteed to be atomic.
11481          */
11482         I915_WRITE(PLANE_CTL(pipe, 0), ctl);
11483         I915_WRITE(PLANE_STRIDE(pipe, 0), stride);
11484
11485         I915_WRITE(PLANE_SURF(pipe, 0), work->gtt_offset);
11486         POSTING_READ(PLANE_SURF(pipe, 0));
11487 }
11488
11489 static void ilk_do_mmio_flip(struct intel_crtc *intel_crtc,
11490                              struct intel_flip_work *work)
11491 {
11492         struct drm_device *dev = intel_crtc->base.dev;
11493         struct drm_i915_private *dev_priv = dev->dev_private;
11494         struct intel_framebuffer *intel_fb =
11495                 to_intel_framebuffer(intel_crtc->base.primary->fb);
11496         struct drm_i915_gem_object *obj = intel_fb->obj;
11497         i915_reg_t reg = DSPCNTR(intel_crtc->plane);
11498         u32 dspcntr;
11499
11500         dspcntr = I915_READ(reg);
11501
11502         if (obj->tiling_mode != I915_TILING_NONE)
11503                 dspcntr |= DISPPLANE_TILED;
11504         else
11505                 dspcntr &= ~DISPPLANE_TILED;
11506
11507         I915_WRITE(reg, dspcntr);
11508
11509         I915_WRITE(DSPSURF(intel_crtc->plane), work->gtt_offset);
11510         POSTING_READ(DSPSURF(intel_crtc->plane));
11511 }
11512
11513 static void intel_mmio_flip_work_func(struct work_struct *w)
11514 {
11515         struct intel_flip_work *work =
11516                 container_of(w, struct intel_flip_work, mmio_work);
11517         struct intel_crtc *crtc = to_intel_crtc(work->crtc);
11518         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
11519         struct intel_framebuffer *intel_fb =
11520                 to_intel_framebuffer(crtc->base.primary->fb);
11521         struct drm_i915_gem_object *obj = intel_fb->obj;
11522
11523         if (work->flip_queued_req)
11524                 WARN_ON(__i915_wait_request(work->flip_queued_req,
11525                                             false, NULL,
11526                                             &dev_priv->rps.mmioflips));
11527
11528         /* For framebuffer backed by dmabuf, wait for fence */
11529         if (obj->base.dma_buf)
11530                 WARN_ON(reservation_object_wait_timeout_rcu(obj->base.dma_buf->resv,
11531                                                             false, false,
11532                                                             MAX_SCHEDULE_TIMEOUT) < 0);
11533
11534         intel_pipe_update_start(crtc);
11535
11536         if (INTEL_GEN(dev_priv) >= 9)
11537                 skl_do_mmio_flip(crtc, work->rotation, work);
11538         else
11539                 /* use_mmio_flip() retricts MMIO flips to ilk+ */
11540                 ilk_do_mmio_flip(crtc, work);
11541
11542         intel_pipe_update_end(crtc, work);
11543 }
11544
11545 static int intel_default_queue_flip(struct drm_device *dev,
11546                                     struct drm_crtc *crtc,
11547                                     struct drm_framebuffer *fb,
11548                                     struct drm_i915_gem_object *obj,
11549                                     struct drm_i915_gem_request *req,
11550                                     uint32_t flags)
11551 {
11552         return -ENODEV;
11553 }
11554
11555 static bool __pageflip_stall_check_cs(struct drm_i915_private *dev_priv,
11556                                       struct intel_crtc *intel_crtc,
11557                                       struct intel_flip_work *work)
11558 {
11559         u32 addr, vblank;
11560
11561         if (!atomic_read(&work->pending))
11562                 return false;
11563
11564         smp_rmb();
11565
11566         vblank = intel_crtc_get_vblank_counter(intel_crtc);
11567         if (work->flip_ready_vblank == 0) {
11568                 if (work->flip_queued_req &&
11569                     !i915_gem_request_completed(work->flip_queued_req, true))
11570                         return false;
11571
11572                 work->flip_ready_vblank = vblank;
11573         }
11574
11575         if (vblank - work->flip_ready_vblank < 3)
11576                 return false;
11577
11578         /* Potential stall - if we see that the flip has happened,
11579          * assume a missed interrupt. */
11580         if (INTEL_GEN(dev_priv) >= 4)
11581                 addr = I915_HI_DISPBASE(I915_READ(DSPSURF(intel_crtc->plane)));
11582         else
11583                 addr = I915_READ(DSPADDR(intel_crtc->plane));
11584
11585         /* There is a potential issue here with a false positive after a flip
11586          * to the same address. We could address this by checking for a
11587          * non-incrementing frame counter.
11588          */
11589         return addr == work->gtt_offset;
11590 }
11591
11592 void intel_check_page_flip(struct drm_i915_private *dev_priv, int pipe)
11593 {
11594         struct drm_device *dev = dev_priv->dev;
11595         struct drm_crtc *crtc = dev_priv->pipe_to_crtc_mapping[pipe];
11596         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
11597         struct intel_flip_work *work;
11598
11599         WARN_ON(!in_interrupt());
11600
11601         if (crtc == NULL)
11602                 return;
11603
11604         spin_lock(&dev->event_lock);
11605         work = intel_crtc->flip_work;
11606
11607         if (work != NULL && !is_mmio_work(work) &&
11608             __pageflip_stall_check_cs(dev_priv, intel_crtc, work)) {
11609                 WARN_ONCE(1,
11610                           "Kicking stuck page flip: queued at %d, now %d\n",
11611                         work->flip_queued_vblank, intel_crtc_get_vblank_counter(intel_crtc));
11612                 page_flip_completed(intel_crtc);
11613                 work = NULL;
11614         }
11615
11616         if (work != NULL && !is_mmio_work(work) &&
11617             intel_crtc_get_vblank_counter(intel_crtc) - work->flip_queued_vblank > 1)
11618                 intel_queue_rps_boost_for_request(work->flip_queued_req);
11619         spin_unlock(&dev->event_lock);
11620 }
11621
11622 static int intel_crtc_page_flip(struct drm_crtc *crtc,
11623                                 struct drm_framebuffer *fb,
11624                                 struct drm_pending_vblank_event *event,
11625                                 uint32_t page_flip_flags)
11626 {
11627         struct drm_device *dev = crtc->dev;
11628         struct drm_i915_private *dev_priv = dev->dev_private;
11629         struct drm_framebuffer *old_fb = crtc->primary->fb;
11630         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
11631         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
11632         struct drm_plane *primary = crtc->primary;
11633         enum pipe pipe = intel_crtc->pipe;
11634         struct intel_flip_work *work;
11635         struct intel_engine_cs *engine;
11636         bool mmio_flip;
11637         struct drm_i915_gem_request *request = NULL;
11638         int ret;
11639
11640         /*
11641          * drm_mode_page_flip_ioctl() should already catch this, but double
11642          * check to be safe.  In the future we may enable pageflipping from
11643          * a disabled primary plane.
11644          */
11645         if (WARN_ON(intel_fb_obj(old_fb) == NULL))
11646                 return -EBUSY;
11647
11648         /* Can't change pixel format via MI display flips. */
11649         if (fb->pixel_format != crtc->primary->fb->pixel_format)
11650                 return -EINVAL;
11651
11652         /*
11653          * TILEOFF/LINOFF registers can't be changed via MI display flips.
11654          * Note that pitch changes could also affect these register.
11655          */
11656         if (INTEL_INFO(dev)->gen > 3 &&
11657             (fb->offsets[0] != crtc->primary->fb->offsets[0] ||
11658              fb->pitches[0] != crtc->primary->fb->pitches[0]))
11659                 return -EINVAL;
11660
11661         if (i915_terminally_wedged(&dev_priv->gpu_error))
11662                 goto out_hang;
11663
11664         work = kzalloc(sizeof(*work), GFP_KERNEL);
11665         if (work == NULL)
11666                 return -ENOMEM;
11667
11668         work->event = event;
11669         work->crtc = crtc;
11670         work->old_fb = old_fb;
11671         INIT_WORK(&work->unpin_work, intel_unpin_work_fn);
11672
11673         ret = drm_crtc_vblank_get(crtc);
11674         if (ret)
11675                 goto free_work;
11676
11677         /* We borrow the event spin lock for protecting flip_work */
11678         spin_lock_irq(&dev->event_lock);
11679         if (intel_crtc->flip_work) {
11680                 /* Before declaring the flip queue wedged, check if
11681                  * the hardware completed the operation behind our backs.
11682                  */
11683                 if (pageflip_finished(intel_crtc, intel_crtc->flip_work)) {
11684                         DRM_DEBUG_DRIVER("flip queue: previous flip completed, continuing\n");
11685                         page_flip_completed(intel_crtc);
11686                 } else {
11687                         DRM_DEBUG_DRIVER("flip queue: crtc already busy\n");
11688                         spin_unlock_irq(&dev->event_lock);
11689
11690                         drm_crtc_vblank_put(crtc);
11691                         kfree(work);
11692                         return -EBUSY;
11693                 }
11694         }
11695         intel_crtc->flip_work = work;
11696         spin_unlock_irq(&dev->event_lock);
11697
11698         if (atomic_read(&intel_crtc->unpin_work_count) >= 2)
11699                 flush_workqueue(dev_priv->wq);
11700
11701         /* Reference the objects for the scheduled work. */
11702         drm_framebuffer_reference(work->old_fb);
11703         drm_gem_object_reference(&obj->base);
11704
11705         crtc->primary->fb = fb;
11706         update_state_fb(crtc->primary);
11707         intel_fbc_pre_update(intel_crtc);
11708
11709         work->pending_flip_obj = obj;
11710
11711         ret = i915_mutex_lock_interruptible(dev);
11712         if (ret)
11713                 goto cleanup;
11714
11715         intel_crtc->reset_counter = i915_reset_counter(&dev_priv->gpu_error);
11716         if (__i915_reset_in_progress_or_wedged(intel_crtc->reset_counter)) {
11717                 ret = -EIO;
11718                 goto cleanup;
11719         }
11720
11721         atomic_inc(&intel_crtc->unpin_work_count);
11722
11723         if (INTEL_INFO(dev)->gen >= 5 || IS_G4X(dev))
11724                 work->flip_count = I915_READ(PIPE_FLIPCOUNT_G4X(pipe)) + 1;
11725
11726         if (IS_VALLEYVIEW(dev) || IS_CHERRYVIEW(dev)) {
11727                 engine = &dev_priv->engine[BCS];
11728                 if (obj->tiling_mode != intel_fb_obj(work->old_fb)->tiling_mode)
11729                         /* vlv: DISPLAY_FLIP fails to change tiling */
11730                         engine = NULL;
11731         } else if (IS_IVYBRIDGE(dev) || IS_HASWELL(dev)) {
11732                 engine = &dev_priv->engine[BCS];
11733         } else if (INTEL_INFO(dev)->gen >= 7) {
11734                 engine = i915_gem_request_get_engine(obj->last_write_req);
11735                 if (engine == NULL || engine->id != RCS)
11736                         engine = &dev_priv->engine[BCS];
11737         } else {
11738                 engine = &dev_priv->engine[RCS];
11739         }
11740
11741         mmio_flip = use_mmio_flip(engine, obj);
11742
11743         /* When using CS flips, we want to emit semaphores between rings.
11744          * However, when using mmio flips we will create a task to do the
11745          * synchronisation, so all we want here is to pin the framebuffer
11746          * into the display plane and skip any waits.
11747          */
11748         if (!mmio_flip) {
11749                 ret = i915_gem_object_sync(obj, engine, &request);
11750                 if (!ret && !request) {
11751                         request = i915_gem_request_alloc(engine, NULL);
11752                         ret = PTR_ERR_OR_ZERO(request);
11753                 }
11754
11755                 if (ret)
11756                         goto cleanup_pending;
11757         }
11758
11759         ret = intel_pin_and_fence_fb_obj(fb, primary->state->rotation);
11760         if (ret)
11761                 goto cleanup_pending;
11762
11763         work->gtt_offset = intel_plane_obj_offset(to_intel_plane(primary),
11764                                                   obj, 0);
11765         work->gtt_offset += intel_crtc->dspaddr_offset;
11766         work->rotation = crtc->primary->state->rotation;
11767
11768         if (mmio_flip) {
11769                 INIT_WORK(&work->mmio_work, intel_mmio_flip_work_func);
11770
11771                 i915_gem_request_assign(&work->flip_queued_req,
11772                                         obj->last_write_req);
11773
11774                 schedule_work(&work->mmio_work);
11775         } else {
11776                 i915_gem_request_assign(&work->flip_queued_req, request);
11777                 ret = dev_priv->display.queue_flip(dev, crtc, fb, obj, request,
11778                                                    page_flip_flags);
11779                 if (ret)
11780                         goto cleanup_unpin;
11781
11782                 intel_mark_page_flip_active(intel_crtc, work);
11783
11784                 i915_add_request_no_flush(request);
11785         }
11786
11787         i915_gem_track_fb(intel_fb_obj(old_fb), obj,
11788                           to_intel_plane(primary)->frontbuffer_bit);
11789         mutex_unlock(&dev->struct_mutex);
11790
11791         intel_frontbuffer_flip_prepare(dev,
11792                                        to_intel_plane(primary)->frontbuffer_bit);
11793
11794         trace_i915_flip_request(intel_crtc->plane, obj);
11795
11796         return 0;
11797
11798 cleanup_unpin:
11799         intel_unpin_fb_obj(fb, crtc->primary->state->rotation);
11800 cleanup_pending:
11801         if (!IS_ERR_OR_NULL(request))
11802                 i915_add_request_no_flush(request);
11803         atomic_dec(&intel_crtc->unpin_work_count);
11804         mutex_unlock(&dev->struct_mutex);
11805 cleanup:
11806         crtc->primary->fb = old_fb;
11807         update_state_fb(crtc->primary);
11808
11809         drm_gem_object_unreference_unlocked(&obj->base);
11810         drm_framebuffer_unreference(work->old_fb);
11811
11812         spin_lock_irq(&dev->event_lock);
11813         intel_crtc->flip_work = NULL;
11814         spin_unlock_irq(&dev->event_lock);
11815
11816         drm_crtc_vblank_put(crtc);
11817 free_work:
11818         kfree(work);
11819
11820         if (ret == -EIO) {
11821                 struct drm_atomic_state *state;
11822                 struct drm_plane_state *plane_state;
11823
11824 out_hang:
11825                 state = drm_atomic_state_alloc(dev);
11826                 if (!state)
11827                         return -ENOMEM;
11828                 state->acquire_ctx = drm_modeset_legacy_acquire_ctx(crtc);
11829
11830 retry:
11831                 plane_state = drm_atomic_get_plane_state(state, primary);
11832                 ret = PTR_ERR_OR_ZERO(plane_state);
11833                 if (!ret) {
11834                         drm_atomic_set_fb_for_plane(plane_state, fb);
11835
11836                         ret = drm_atomic_set_crtc_for_plane(plane_state, crtc);
11837                         if (!ret)
11838                                 ret = drm_atomic_commit(state);
11839                 }
11840
11841                 if (ret == -EDEADLK) {
11842                         drm_modeset_backoff(state->acquire_ctx);
11843                         drm_atomic_state_clear(state);
11844                         goto retry;
11845                 }
11846
11847                 if (ret)
11848                         drm_atomic_state_free(state);
11849
11850                 if (ret == 0 && event) {
11851                         spin_lock_irq(&dev->event_lock);
11852                         drm_crtc_send_vblank_event(crtc, event);
11853                         spin_unlock_irq(&dev->event_lock);
11854                 }
11855         }
11856         return ret;
11857 }
11858
11859
11860 /**
11861  * intel_wm_need_update - Check whether watermarks need updating
11862  * @plane: drm plane
11863  * @state: new plane state
11864  *
11865  * Check current plane state versus the new one to determine whether
11866  * watermarks need to be recalculated.
11867  *
11868  * Returns true or false.
11869  */
11870 static bool intel_wm_need_update(struct drm_plane *plane,
11871                                  struct drm_plane_state *state)
11872 {
11873         struct intel_plane_state *new = to_intel_plane_state(state);
11874         struct intel_plane_state *cur = to_intel_plane_state(plane->state);
11875
11876         /* Update watermarks on tiling or size changes. */
11877         if (new->visible != cur->visible)
11878                 return true;
11879
11880         if (!cur->base.fb || !new->base.fb)
11881                 return false;
11882
11883         if (cur->base.fb->modifier[0] != new->base.fb->modifier[0] ||
11884             cur->base.rotation != new->base.rotation ||
11885             drm_rect_width(&new->src) != drm_rect_width(&cur->src) ||
11886             drm_rect_height(&new->src) != drm_rect_height(&cur->src) ||
11887             drm_rect_width(&new->dst) != drm_rect_width(&cur->dst) ||
11888             drm_rect_height(&new->dst) != drm_rect_height(&cur->dst))
11889                 return true;
11890
11891         return false;
11892 }
11893
11894 static bool needs_scaling(struct intel_plane_state *state)
11895 {
11896         int src_w = drm_rect_width(&state->src) >> 16;
11897         int src_h = drm_rect_height(&state->src) >> 16;
11898         int dst_w = drm_rect_width(&state->dst);
11899         int dst_h = drm_rect_height(&state->dst);
11900
11901         return (src_w != dst_w || src_h != dst_h);
11902 }
11903
11904 int intel_plane_atomic_calc_changes(struct drm_crtc_state *crtc_state,
11905                                     struct drm_plane_state *plane_state)
11906 {
11907         struct intel_crtc_state *pipe_config = to_intel_crtc_state(crtc_state);
11908         struct drm_crtc *crtc = crtc_state->crtc;
11909         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
11910         struct drm_plane *plane = plane_state->plane;
11911         struct drm_device *dev = crtc->dev;
11912         struct drm_i915_private *dev_priv = to_i915(dev);
11913         struct intel_plane_state *old_plane_state =
11914                 to_intel_plane_state(plane->state);
11915         bool mode_changed = needs_modeset(crtc_state);
11916         bool was_crtc_enabled = crtc->state->active;
11917         bool is_crtc_enabled = crtc_state->active;
11918         bool turn_off, turn_on, visible, was_visible;
11919         struct drm_framebuffer *fb = plane_state->fb;
11920         int ret;
11921
11922         if (crtc_state && INTEL_INFO(dev)->gen >= 9 &&
11923             plane->type != DRM_PLANE_TYPE_CURSOR) {
11924                 ret = skl_update_scaler_plane(
11925                         to_intel_crtc_state(crtc_state),
11926                         to_intel_plane_state(plane_state));
11927                 if (ret)
11928                         return ret;
11929         }
11930
11931         was_visible = old_plane_state->visible;
11932         visible = to_intel_plane_state(plane_state)->visible;
11933
11934         if (!was_crtc_enabled && WARN_ON(was_visible))
11935                 was_visible = false;
11936
11937         /*
11938          * Visibility is calculated as if the crtc was on, but
11939          * after scaler setup everything depends on it being off
11940          * when the crtc isn't active.
11941          *
11942          * FIXME this is wrong for watermarks. Watermarks should also
11943          * be computed as if the pipe would be active. Perhaps move
11944          * per-plane wm computation to the .check_plane() hook, and
11945          * only combine the results from all planes in the current place?
11946          */
11947         if (!is_crtc_enabled)
11948                 to_intel_plane_state(plane_state)->visible = visible = false;
11949
11950         if (!was_visible && !visible)
11951                 return 0;
11952
11953         if (fb != old_plane_state->base.fb)
11954                 pipe_config->fb_changed = true;
11955
11956         turn_off = was_visible && (!visible || mode_changed);
11957         turn_on = visible && (!was_visible || mode_changed);
11958
11959         DRM_DEBUG_ATOMIC("[CRTC:%d:%s] has [PLANE:%d:%s] with fb %i\n",
11960                          intel_crtc->base.base.id,
11961                          intel_crtc->base.name,
11962                          plane->base.id, plane->name,
11963                          fb ? fb->base.id : -1);
11964
11965         DRM_DEBUG_ATOMIC("[PLANE:%d:%s] visible %i -> %i, off %i, on %i, ms %i\n",
11966                          plane->base.id, plane->name,
11967                          was_visible, visible,
11968                          turn_off, turn_on, mode_changed);
11969
11970         if (turn_on) {
11971                 pipe_config->update_wm_pre = true;
11972
11973                 /* must disable cxsr around plane enable/disable */
11974                 if (plane->type != DRM_PLANE_TYPE_CURSOR)
11975                         pipe_config->disable_cxsr = true;
11976         } else if (turn_off) {
11977                 pipe_config->update_wm_post = true;
11978
11979                 /* must disable cxsr around plane enable/disable */
11980                 if (plane->type != DRM_PLANE_TYPE_CURSOR)
11981                         pipe_config->disable_cxsr = true;
11982         } else if (intel_wm_need_update(plane, plane_state)) {
11983                 /* FIXME bollocks */
11984                 pipe_config->update_wm_pre = true;
11985                 pipe_config->update_wm_post = true;
11986         }
11987
11988         /* Pre-gen9 platforms need two-step watermark updates */
11989         if ((pipe_config->update_wm_pre || pipe_config->update_wm_post) &&
11990             INTEL_INFO(dev)->gen < 9 && dev_priv->display.optimize_watermarks)
11991                 to_intel_crtc_state(crtc_state)->wm.need_postvbl_update = true;
11992
11993         if (visible || was_visible)
11994                 pipe_config->fb_bits |= to_intel_plane(plane)->frontbuffer_bit;
11995
11996         /*
11997          * WaCxSRDisabledForSpriteScaling:ivb
11998          *
11999          * cstate->update_wm was already set above, so this flag will
12000          * take effect when we commit and program watermarks.
12001          */
12002         if (plane->type == DRM_PLANE_TYPE_OVERLAY && IS_IVYBRIDGE(dev) &&
12003             needs_scaling(to_intel_plane_state(plane_state)) &&
12004             !needs_scaling(old_plane_state))
12005                 pipe_config->disable_lp_wm = true;
12006
12007         return 0;
12008 }
12009
12010 static bool encoders_cloneable(const struct intel_encoder *a,
12011                                const struct intel_encoder *b)
12012 {
12013         /* masks could be asymmetric, so check both ways */
12014         return a == b || (a->cloneable & (1 << b->type) &&
12015                           b->cloneable & (1 << a->type));
12016 }
12017
12018 static bool check_single_encoder_cloning(struct drm_atomic_state *state,
12019                                          struct intel_crtc *crtc,
12020                                          struct intel_encoder *encoder)
12021 {
12022         struct intel_encoder *source_encoder;
12023         struct drm_connector *connector;
12024         struct drm_connector_state *connector_state;
12025         int i;
12026
12027         for_each_connector_in_state(state, connector, connector_state, i) {
12028                 if (connector_state->crtc != &crtc->base)
12029                         continue;
12030
12031                 source_encoder =
12032                         to_intel_encoder(connector_state->best_encoder);
12033                 if (!encoders_cloneable(encoder, source_encoder))
12034                         return false;
12035         }
12036
12037         return true;
12038 }
12039
12040 static bool check_encoder_cloning(struct drm_atomic_state *state,
12041                                   struct intel_crtc *crtc)
12042 {
12043         struct intel_encoder *encoder;
12044         struct drm_connector *connector;
12045         struct drm_connector_state *connector_state;
12046         int i;
12047
12048         for_each_connector_in_state(state, connector, connector_state, i) {
12049                 if (connector_state->crtc != &crtc->base)
12050                         continue;
12051
12052                 encoder = to_intel_encoder(connector_state->best_encoder);
12053                 if (!check_single_encoder_cloning(state, crtc, encoder))
12054                         return false;
12055         }
12056
12057         return true;
12058 }
12059
12060 static int intel_crtc_atomic_check(struct drm_crtc *crtc,
12061                                    struct drm_crtc_state *crtc_state)
12062 {
12063         struct drm_device *dev = crtc->dev;
12064         struct drm_i915_private *dev_priv = dev->dev_private;
12065         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
12066         struct intel_crtc_state *pipe_config =
12067                 to_intel_crtc_state(crtc_state);
12068         struct drm_atomic_state *state = crtc_state->state;
12069         int ret;
12070         bool mode_changed = needs_modeset(crtc_state);
12071
12072         if (mode_changed && !check_encoder_cloning(state, intel_crtc)) {
12073                 DRM_DEBUG_KMS("rejecting invalid cloning configuration\n");
12074                 return -EINVAL;
12075         }
12076
12077         if (mode_changed && !crtc_state->active)
12078                 pipe_config->update_wm_post = true;
12079
12080         if (mode_changed && crtc_state->enable &&
12081             dev_priv->display.crtc_compute_clock &&
12082             !WARN_ON(pipe_config->shared_dpll)) {
12083                 ret = dev_priv->display.crtc_compute_clock(intel_crtc,
12084                                                            pipe_config);
12085                 if (ret)
12086                         return ret;
12087         }
12088
12089         if (crtc_state->color_mgmt_changed) {
12090                 ret = intel_color_check(crtc, crtc_state);
12091                 if (ret)
12092                         return ret;
12093         }
12094
12095         ret = 0;
12096         if (dev_priv->display.compute_pipe_wm) {
12097                 ret = dev_priv->display.compute_pipe_wm(pipe_config);
12098                 if (ret) {
12099                         DRM_DEBUG_KMS("Target pipe watermarks are invalid\n");
12100                         return ret;
12101                 }
12102         }
12103
12104         if (dev_priv->display.compute_intermediate_wm &&
12105             !to_intel_atomic_state(state)->skip_intermediate_wm) {
12106                 if (WARN_ON(!dev_priv->display.compute_pipe_wm))
12107                         return 0;
12108
12109                 /*
12110                  * Calculate 'intermediate' watermarks that satisfy both the
12111                  * old state and the new state.  We can program these
12112                  * immediately.
12113                  */
12114                 ret = dev_priv->display.compute_intermediate_wm(crtc->dev,
12115                                                                 intel_crtc,
12116                                                                 pipe_config);
12117                 if (ret) {
12118                         DRM_DEBUG_KMS("No valid intermediate pipe watermarks are possible\n");
12119                         return ret;
12120                 }
12121         } else if (dev_priv->display.compute_intermediate_wm) {
12122                 if (HAS_PCH_SPLIT(dev_priv) && INTEL_GEN(dev_priv) < 9)
12123                         pipe_config->wm.ilk.intermediate = pipe_config->wm.ilk.optimal;
12124         }
12125
12126         if (INTEL_INFO(dev)->gen >= 9) {
12127                 if (mode_changed)
12128                         ret = skl_update_scaler_crtc(pipe_config);
12129
12130                 if (!ret)
12131                         ret = intel_atomic_setup_scalers(dev, intel_crtc,
12132                                                          pipe_config);
12133         }
12134
12135         return ret;
12136 }
12137
12138 static const struct drm_crtc_helper_funcs intel_helper_funcs = {
12139         .mode_set_base_atomic = intel_pipe_set_base_atomic,
12140         .atomic_begin = intel_begin_crtc_commit,
12141         .atomic_flush = intel_finish_crtc_commit,
12142         .atomic_check = intel_crtc_atomic_check,
12143 };
12144
12145 static void intel_modeset_update_connector_atomic_state(struct drm_device *dev)
12146 {
12147         struct intel_connector *connector;
12148
12149         for_each_intel_connector(dev, connector) {
12150                 if (connector->base.state->crtc)
12151                         drm_connector_unreference(&connector->base);
12152
12153                 if (connector->base.encoder) {
12154                         connector->base.state->best_encoder =
12155                                 connector->base.encoder;
12156                         connector->base.state->crtc =
12157                                 connector->base.encoder->crtc;
12158
12159                         drm_connector_reference(&connector->base);
12160                 } else {
12161                         connector->base.state->best_encoder = NULL;
12162                         connector->base.state->crtc = NULL;
12163                 }
12164         }
12165 }
12166
12167 static void
12168 connected_sink_compute_bpp(struct intel_connector *connector,
12169                            struct intel_crtc_state *pipe_config)
12170 {
12171         int bpp = pipe_config->pipe_bpp;
12172
12173         DRM_DEBUG_KMS("[CONNECTOR:%d:%s] checking for sink bpp constrains\n",
12174                 connector->base.base.id,
12175                 connector->base.name);
12176
12177         /* Don't use an invalid EDID bpc value */
12178         if (connector->base.display_info.bpc &&
12179             connector->base.display_info.bpc * 3 < bpp) {
12180                 DRM_DEBUG_KMS("clamping display bpp (was %d) to EDID reported max of %d\n",
12181                               bpp, connector->base.display_info.bpc*3);
12182                 pipe_config->pipe_bpp = connector->base.display_info.bpc*3;
12183         }
12184
12185         /* Clamp bpp to default limit on screens without EDID 1.4 */
12186         if (connector->base.display_info.bpc == 0) {
12187                 int type = connector->base.connector_type;
12188                 int clamp_bpp = 24;
12189
12190                 /* Fall back to 18 bpp when DP sink capability is unknown. */
12191                 if (type == DRM_MODE_CONNECTOR_DisplayPort ||
12192                     type == DRM_MODE_CONNECTOR_eDP)
12193                         clamp_bpp = 18;
12194
12195                 if (bpp > clamp_bpp) {
12196                         DRM_DEBUG_KMS("clamping display bpp (was %d) to default limit of %d\n",
12197                                       bpp, clamp_bpp);
12198                         pipe_config->pipe_bpp = clamp_bpp;
12199                 }
12200         }
12201 }
12202
12203 static int
12204 compute_baseline_pipe_bpp(struct intel_crtc *crtc,
12205                           struct intel_crtc_state *pipe_config)
12206 {
12207         struct drm_device *dev = crtc->base.dev;
12208         struct drm_atomic_state *state;
12209         struct drm_connector *connector;
12210         struct drm_connector_state *connector_state;
12211         int bpp, i;
12212
12213         if ((IS_G4X(dev) || IS_VALLEYVIEW(dev) || IS_CHERRYVIEW(dev)))
12214                 bpp = 10*3;
12215         else if (INTEL_INFO(dev)->gen >= 5)
12216                 bpp = 12*3;
12217         else
12218                 bpp = 8*3;
12219
12220
12221         pipe_config->pipe_bpp = bpp;
12222
12223         state = pipe_config->base.state;
12224
12225         /* Clamp display bpp to EDID value */
12226         for_each_connector_in_state(state, connector, connector_state, i) {
12227                 if (connector_state->crtc != &crtc->base)
12228                         continue;
12229
12230                 connected_sink_compute_bpp(to_intel_connector(connector),
12231                                            pipe_config);
12232         }
12233
12234         return bpp;
12235 }
12236
12237 static void intel_dump_crtc_timings(const struct drm_display_mode *mode)
12238 {
12239         DRM_DEBUG_KMS("crtc timings: %d %d %d %d %d %d %d %d %d, "
12240                         "type: 0x%x flags: 0x%x\n",
12241                 mode->crtc_clock,
12242                 mode->crtc_hdisplay, mode->crtc_hsync_start,
12243                 mode->crtc_hsync_end, mode->crtc_htotal,
12244                 mode->crtc_vdisplay, mode->crtc_vsync_start,
12245                 mode->crtc_vsync_end, mode->crtc_vtotal, mode->type, mode->flags);
12246 }
12247
12248 static void intel_dump_pipe_config(struct intel_crtc *crtc,
12249                                    struct intel_crtc_state *pipe_config,
12250                                    const char *context)
12251 {
12252         struct drm_device *dev = crtc->base.dev;
12253         struct drm_plane *plane;
12254         struct intel_plane *intel_plane;
12255         struct intel_plane_state *state;
12256         struct drm_framebuffer *fb;
12257
12258         DRM_DEBUG_KMS("[CRTC:%d:%s]%s config %p for pipe %c\n",
12259                       crtc->base.base.id, crtc->base.name,
12260                       context, pipe_config, pipe_name(crtc->pipe));
12261
12262         DRM_DEBUG_KMS("cpu_transcoder: %s\n", transcoder_name(pipe_config->cpu_transcoder));
12263         DRM_DEBUG_KMS("pipe bpp: %i, dithering: %i\n",
12264                       pipe_config->pipe_bpp, pipe_config->dither);
12265         DRM_DEBUG_KMS("fdi/pch: %i, lanes: %i, gmch_m: %u, gmch_n: %u, link_m: %u, link_n: %u, tu: %u\n",
12266                       pipe_config->has_pch_encoder,
12267                       pipe_config->fdi_lanes,
12268                       pipe_config->fdi_m_n.gmch_m, pipe_config->fdi_m_n.gmch_n,
12269                       pipe_config->fdi_m_n.link_m, pipe_config->fdi_m_n.link_n,
12270                       pipe_config->fdi_m_n.tu);
12271         DRM_DEBUG_KMS("dp: %i, lanes: %i, gmch_m: %u, gmch_n: %u, link_m: %u, link_n: %u, tu: %u\n",
12272                       pipe_config->has_dp_encoder,
12273                       pipe_config->lane_count,
12274                       pipe_config->dp_m_n.gmch_m, pipe_config->dp_m_n.gmch_n,
12275                       pipe_config->dp_m_n.link_m, pipe_config->dp_m_n.link_n,
12276                       pipe_config->dp_m_n.tu);
12277
12278         DRM_DEBUG_KMS("dp: %i, lanes: %i, gmch_m2: %u, gmch_n2: %u, link_m2: %u, link_n2: %u, tu2: %u\n",
12279                       pipe_config->has_dp_encoder,
12280                       pipe_config->lane_count,
12281                       pipe_config->dp_m2_n2.gmch_m,
12282                       pipe_config->dp_m2_n2.gmch_n,
12283                       pipe_config->dp_m2_n2.link_m,
12284                       pipe_config->dp_m2_n2.link_n,
12285                       pipe_config->dp_m2_n2.tu);
12286
12287         DRM_DEBUG_KMS("audio: %i, infoframes: %i\n",
12288                       pipe_config->has_audio,
12289                       pipe_config->has_infoframe);
12290
12291         DRM_DEBUG_KMS("requested mode:\n");
12292         drm_mode_debug_printmodeline(&pipe_config->base.mode);
12293         DRM_DEBUG_KMS("adjusted mode:\n");
12294         drm_mode_debug_printmodeline(&pipe_config->base.adjusted_mode);
12295         intel_dump_crtc_timings(&pipe_config->base.adjusted_mode);
12296         DRM_DEBUG_KMS("port clock: %d\n", pipe_config->port_clock);
12297         DRM_DEBUG_KMS("pipe src size: %dx%d\n",
12298                       pipe_config->pipe_src_w, pipe_config->pipe_src_h);
12299         DRM_DEBUG_KMS("num_scalers: %d, scaler_users: 0x%x, scaler_id: %d\n",
12300                       crtc->num_scalers,
12301                       pipe_config->scaler_state.scaler_users,
12302                       pipe_config->scaler_state.scaler_id);
12303         DRM_DEBUG_KMS("gmch pfit: control: 0x%08x, ratios: 0x%08x, lvds border: 0x%08x\n",
12304                       pipe_config->gmch_pfit.control,
12305                       pipe_config->gmch_pfit.pgm_ratios,
12306                       pipe_config->gmch_pfit.lvds_border_bits);
12307         DRM_DEBUG_KMS("pch pfit: pos: 0x%08x, size: 0x%08x, %s\n",
12308                       pipe_config->pch_pfit.pos,
12309                       pipe_config->pch_pfit.size,
12310                       pipe_config->pch_pfit.enabled ? "enabled" : "disabled");
12311         DRM_DEBUG_KMS("ips: %i\n", pipe_config->ips_enabled);
12312         DRM_DEBUG_KMS("double wide: %i\n", pipe_config->double_wide);
12313
12314         if (IS_BROXTON(dev)) {
12315                 DRM_DEBUG_KMS("ddi_pll_sel: %u; dpll_hw_state: ebb0: 0x%x, ebb4: 0x%x,"
12316                               "pll0: 0x%x, pll1: 0x%x, pll2: 0x%x, pll3: 0x%x, "
12317                               "pll6: 0x%x, pll8: 0x%x, pll9: 0x%x, pll10: 0x%x, pcsdw12: 0x%x\n",
12318                               pipe_config->ddi_pll_sel,
12319                               pipe_config->dpll_hw_state.ebb0,
12320                               pipe_config->dpll_hw_state.ebb4,
12321                               pipe_config->dpll_hw_state.pll0,
12322                               pipe_config->dpll_hw_state.pll1,
12323                               pipe_config->dpll_hw_state.pll2,
12324                               pipe_config->dpll_hw_state.pll3,
12325                               pipe_config->dpll_hw_state.pll6,
12326                               pipe_config->dpll_hw_state.pll8,
12327                               pipe_config->dpll_hw_state.pll9,
12328                               pipe_config->dpll_hw_state.pll10,
12329                               pipe_config->dpll_hw_state.pcsdw12);
12330         } else if (IS_SKYLAKE(dev) || IS_KABYLAKE(dev)) {
12331                 DRM_DEBUG_KMS("ddi_pll_sel: %u; dpll_hw_state: "
12332                               "ctrl1: 0x%x, cfgcr1: 0x%x, cfgcr2: 0x%x\n",
12333                               pipe_config->ddi_pll_sel,
12334                               pipe_config->dpll_hw_state.ctrl1,
12335                               pipe_config->dpll_hw_state.cfgcr1,
12336                               pipe_config->dpll_hw_state.cfgcr2);
12337         } else if (HAS_DDI(dev)) {
12338                 DRM_DEBUG_KMS("ddi_pll_sel: 0x%x; dpll_hw_state: wrpll: 0x%x spll: 0x%x\n",
12339                               pipe_config->ddi_pll_sel,
12340                               pipe_config->dpll_hw_state.wrpll,
12341                               pipe_config->dpll_hw_state.spll);
12342         } else {
12343                 DRM_DEBUG_KMS("dpll_hw_state: dpll: 0x%x, dpll_md: 0x%x, "
12344                               "fp0: 0x%x, fp1: 0x%x\n",
12345                               pipe_config->dpll_hw_state.dpll,
12346                               pipe_config->dpll_hw_state.dpll_md,
12347                               pipe_config->dpll_hw_state.fp0,
12348                               pipe_config->dpll_hw_state.fp1);
12349         }
12350
12351         DRM_DEBUG_KMS("planes on this crtc\n");
12352         list_for_each_entry(plane, &dev->mode_config.plane_list, head) {
12353                 intel_plane = to_intel_plane(plane);
12354                 if (intel_plane->pipe != crtc->pipe)
12355                         continue;
12356
12357                 state = to_intel_plane_state(plane->state);
12358                 fb = state->base.fb;
12359                 if (!fb) {
12360                         DRM_DEBUG_KMS("[PLANE:%d:%s] disabled, scaler_id = %d\n",
12361                                       plane->base.id, plane->name, state->scaler_id);
12362                         continue;
12363                 }
12364
12365                 DRM_DEBUG_KMS("[PLANE:%d:%s] enabled",
12366                               plane->base.id, plane->name);
12367                 DRM_DEBUG_KMS("\tFB:%d, fb = %ux%u format = %s",
12368                               fb->base.id, fb->width, fb->height,
12369                               drm_get_format_name(fb->pixel_format));
12370                 DRM_DEBUG_KMS("\tscaler:%d src %dx%d+%d+%d dst %dx%d+%d+%d\n",
12371                               state->scaler_id,
12372                               state->src.x1 >> 16, state->src.y1 >> 16,
12373                               drm_rect_width(&state->src) >> 16,
12374                               drm_rect_height(&state->src) >> 16,
12375                               state->dst.x1, state->dst.y1,
12376                               drm_rect_width(&state->dst),
12377                               drm_rect_height(&state->dst));
12378         }
12379 }
12380
12381 static bool check_digital_port_conflicts(struct drm_atomic_state *state)
12382 {
12383         struct drm_device *dev = state->dev;
12384         struct drm_connector *connector;
12385         unsigned int used_ports = 0;
12386
12387         /*
12388          * Walk the connector list instead of the encoder
12389          * list to detect the problem on ddi platforms
12390          * where there's just one encoder per digital port.
12391          */
12392         drm_for_each_connector(connector, dev) {
12393                 struct drm_connector_state *connector_state;
12394                 struct intel_encoder *encoder;
12395
12396                 connector_state = drm_atomic_get_existing_connector_state(state, connector);
12397                 if (!connector_state)
12398                         connector_state = connector->state;
12399
12400                 if (!connector_state->best_encoder)
12401                         continue;
12402
12403                 encoder = to_intel_encoder(connector_state->best_encoder);
12404
12405                 WARN_ON(!connector_state->crtc);
12406
12407                 switch (encoder->type) {
12408                         unsigned int port_mask;
12409                 case INTEL_OUTPUT_UNKNOWN:
12410                         if (WARN_ON(!HAS_DDI(dev)))
12411                                 break;
12412                 case INTEL_OUTPUT_DISPLAYPORT:
12413                 case INTEL_OUTPUT_HDMI:
12414                 case INTEL_OUTPUT_EDP:
12415                         port_mask = 1 << enc_to_dig_port(&encoder->base)->port;
12416
12417                         /* the same port mustn't appear more than once */
12418                         if (used_ports & port_mask)
12419                                 return false;
12420
12421                         used_ports |= port_mask;
12422                 default:
12423                         break;
12424                 }
12425         }
12426
12427         return true;
12428 }
12429
12430 static void
12431 clear_intel_crtc_state(struct intel_crtc_state *crtc_state)
12432 {
12433         struct drm_crtc_state tmp_state;
12434         struct intel_crtc_scaler_state scaler_state;
12435         struct intel_dpll_hw_state dpll_hw_state;
12436         struct intel_shared_dpll *shared_dpll;
12437         uint32_t ddi_pll_sel;
12438         bool force_thru;
12439
12440         /* FIXME: before the switch to atomic started, a new pipe_config was
12441          * kzalloc'd. Code that depends on any field being zero should be
12442          * fixed, so that the crtc_state can be safely duplicated. For now,
12443          * only fields that are know to not cause problems are preserved. */
12444
12445         tmp_state = crtc_state->base;
12446         scaler_state = crtc_state->scaler_state;
12447         shared_dpll = crtc_state->shared_dpll;
12448         dpll_hw_state = crtc_state->dpll_hw_state;
12449         ddi_pll_sel = crtc_state->ddi_pll_sel;
12450         force_thru = crtc_state->pch_pfit.force_thru;
12451
12452         memset(crtc_state, 0, sizeof *crtc_state);
12453
12454         crtc_state->base = tmp_state;
12455         crtc_state->scaler_state = scaler_state;
12456         crtc_state->shared_dpll = shared_dpll;
12457         crtc_state->dpll_hw_state = dpll_hw_state;
12458         crtc_state->ddi_pll_sel = ddi_pll_sel;
12459         crtc_state->pch_pfit.force_thru = force_thru;
12460 }
12461
12462 static int
12463 intel_modeset_pipe_config(struct drm_crtc *crtc,
12464                           struct intel_crtc_state *pipe_config)
12465 {
12466         struct drm_atomic_state *state = pipe_config->base.state;
12467         struct intel_encoder *encoder;
12468         struct drm_connector *connector;
12469         struct drm_connector_state *connector_state;
12470         int base_bpp, ret = -EINVAL;
12471         int i;
12472         bool retry = true;
12473
12474         clear_intel_crtc_state(pipe_config);
12475
12476         pipe_config->cpu_transcoder =
12477                 (enum transcoder) to_intel_crtc(crtc)->pipe;
12478
12479         /*
12480          * Sanitize sync polarity flags based on requested ones. If neither
12481          * positive or negative polarity is requested, treat this as meaning
12482          * negative polarity.
12483          */
12484         if (!(pipe_config->base.adjusted_mode.flags &
12485               (DRM_MODE_FLAG_PHSYNC | DRM_MODE_FLAG_NHSYNC)))
12486                 pipe_config->base.adjusted_mode.flags |= DRM_MODE_FLAG_NHSYNC;
12487
12488         if (!(pipe_config->base.adjusted_mode.flags &
12489               (DRM_MODE_FLAG_PVSYNC | DRM_MODE_FLAG_NVSYNC)))
12490                 pipe_config->base.adjusted_mode.flags |= DRM_MODE_FLAG_NVSYNC;
12491
12492         base_bpp = compute_baseline_pipe_bpp(to_intel_crtc(crtc),
12493                                              pipe_config);
12494         if (base_bpp < 0)
12495                 goto fail;
12496
12497         /*
12498          * Determine the real pipe dimensions. Note that stereo modes can
12499          * increase the actual pipe size due to the frame doubling and
12500          * insertion of additional space for blanks between the frame. This
12501          * is stored in the crtc timings. We use the requested mode to do this
12502          * computation to clearly distinguish it from the adjusted mode, which
12503          * can be changed by the connectors in the below retry loop.
12504          */
12505         drm_crtc_get_hv_timing(&pipe_config->base.mode,
12506                                &pipe_config->pipe_src_w,
12507                                &pipe_config->pipe_src_h);
12508
12509 encoder_retry:
12510         /* Ensure the port clock defaults are reset when retrying. */
12511         pipe_config->port_clock = 0;
12512         pipe_config->pixel_multiplier = 1;
12513
12514         /* Fill in default crtc timings, allow encoders to overwrite them. */
12515         drm_mode_set_crtcinfo(&pipe_config->base.adjusted_mode,
12516                               CRTC_STEREO_DOUBLE);
12517
12518         /* Pass our mode to the connectors and the CRTC to give them a chance to
12519          * adjust it according to limitations or connector properties, and also
12520          * a chance to reject the mode entirely.
12521          */
12522         for_each_connector_in_state(state, connector, connector_state, i) {
12523                 if (connector_state->crtc != crtc)
12524                         continue;
12525
12526                 encoder = to_intel_encoder(connector_state->best_encoder);
12527
12528                 if (!(encoder->compute_config(encoder, pipe_config))) {
12529                         DRM_DEBUG_KMS("Encoder config failure\n");
12530                         goto fail;
12531                 }
12532         }
12533
12534         /* Set default port clock if not overwritten by the encoder. Needs to be
12535          * done afterwards in case the encoder adjusts the mode. */
12536         if (!pipe_config->port_clock)
12537                 pipe_config->port_clock = pipe_config->base.adjusted_mode.crtc_clock
12538                         * pipe_config->pixel_multiplier;
12539
12540         ret = intel_crtc_compute_config(to_intel_crtc(crtc), pipe_config);
12541         if (ret < 0) {
12542                 DRM_DEBUG_KMS("CRTC fixup failed\n");
12543                 goto fail;
12544         }
12545
12546         if (ret == RETRY) {
12547                 if (WARN(!retry, "loop in pipe configuration computation\n")) {
12548                         ret = -EINVAL;
12549                         goto fail;
12550                 }
12551
12552                 DRM_DEBUG_KMS("CRTC bw constrained, retrying\n");
12553                 retry = false;
12554                 goto encoder_retry;
12555         }
12556
12557         /* Dithering seems to not pass-through bits correctly when it should, so
12558          * only enable it on 6bpc panels. */
12559         pipe_config->dither = pipe_config->pipe_bpp == 6*3;
12560         DRM_DEBUG_KMS("hw max bpp: %i, pipe bpp: %i, dithering: %i\n",
12561                       base_bpp, pipe_config->pipe_bpp, pipe_config->dither);
12562
12563 fail:
12564         return ret;
12565 }
12566
12567 static void
12568 intel_modeset_update_crtc_state(struct drm_atomic_state *state)
12569 {
12570         struct drm_crtc *crtc;
12571         struct drm_crtc_state *crtc_state;
12572         int i;
12573
12574         /* Double check state. */
12575         for_each_crtc_in_state(state, crtc, crtc_state, i) {
12576                 to_intel_crtc(crtc)->config = to_intel_crtc_state(crtc->state);
12577
12578                 /* Update hwmode for vblank functions */
12579                 if (crtc->state->active)
12580                         crtc->hwmode = crtc->state->adjusted_mode;
12581                 else
12582                         crtc->hwmode.crtc_clock = 0;
12583
12584                 /*
12585                  * Update legacy state to satisfy fbc code. This can
12586                  * be removed when fbc uses the atomic state.
12587                  */
12588                 if (drm_atomic_get_existing_plane_state(state, crtc->primary)) {
12589                         struct drm_plane_state *plane_state = crtc->primary->state;
12590
12591                         crtc->primary->fb = plane_state->fb;
12592                         crtc->x = plane_state->src_x >> 16;
12593                         crtc->y = plane_state->src_y >> 16;
12594                 }
12595         }
12596 }
12597
12598 static bool intel_fuzzy_clock_check(int clock1, int clock2)
12599 {
12600         int diff;
12601
12602         if (clock1 == clock2)
12603                 return true;
12604
12605         if (!clock1 || !clock2)
12606                 return false;
12607
12608         diff = abs(clock1 - clock2);
12609
12610         if (((((diff + clock1 + clock2) * 100)) / (clock1 + clock2)) < 105)
12611                 return true;
12612
12613         return false;
12614 }
12615
12616 #define for_each_intel_crtc_masked(dev, mask, intel_crtc) \
12617         list_for_each_entry((intel_crtc), \
12618                             &(dev)->mode_config.crtc_list, \
12619                             base.head) \
12620                 for_each_if (mask & (1 <<(intel_crtc)->pipe))
12621
12622 static bool
12623 intel_compare_m_n(unsigned int m, unsigned int n,
12624                   unsigned int m2, unsigned int n2,
12625                   bool exact)
12626 {
12627         if (m == m2 && n == n2)
12628                 return true;
12629
12630         if (exact || !m || !n || !m2 || !n2)
12631                 return false;
12632
12633         BUILD_BUG_ON(DATA_LINK_M_N_MASK > INT_MAX);
12634
12635         if (n > n2) {
12636                 while (n > n2) {
12637                         m2 <<= 1;
12638                         n2 <<= 1;
12639                 }
12640         } else if (n < n2) {
12641                 while (n < n2) {
12642                         m <<= 1;
12643                         n <<= 1;
12644                 }
12645         }
12646
12647         if (n != n2)
12648                 return false;
12649
12650         return intel_fuzzy_clock_check(m, m2);
12651 }
12652
12653 static bool
12654 intel_compare_link_m_n(const struct intel_link_m_n *m_n,
12655                        struct intel_link_m_n *m2_n2,
12656                        bool adjust)
12657 {
12658         if (m_n->tu == m2_n2->tu &&
12659             intel_compare_m_n(m_n->gmch_m, m_n->gmch_n,
12660                               m2_n2->gmch_m, m2_n2->gmch_n, !adjust) &&
12661             intel_compare_m_n(m_n->link_m, m_n->link_n,
12662                               m2_n2->link_m, m2_n2->link_n, !adjust)) {
12663                 if (adjust)
12664                         *m2_n2 = *m_n;
12665
12666                 return true;
12667         }
12668
12669         return false;
12670 }
12671
12672 static bool
12673 intel_pipe_config_compare(struct drm_device *dev,
12674                           struct intel_crtc_state *current_config,
12675                           struct intel_crtc_state *pipe_config,
12676                           bool adjust)
12677 {
12678         bool ret = true;
12679
12680 #define INTEL_ERR_OR_DBG_KMS(fmt, ...) \
12681         do { \
12682                 if (!adjust) \
12683                         DRM_ERROR(fmt, ##__VA_ARGS__); \
12684                 else \
12685                         DRM_DEBUG_KMS(fmt, ##__VA_ARGS__); \
12686         } while (0)
12687
12688 #define PIPE_CONF_CHECK_X(name) \
12689         if (current_config->name != pipe_config->name) { \
12690                 INTEL_ERR_OR_DBG_KMS("mismatch in " #name " " \
12691                           "(expected 0x%08x, found 0x%08x)\n", \
12692                           current_config->name, \
12693                           pipe_config->name); \
12694                 ret = false; \
12695         }
12696
12697 #define PIPE_CONF_CHECK_I(name) \
12698         if (current_config->name != pipe_config->name) { \
12699                 INTEL_ERR_OR_DBG_KMS("mismatch in " #name " " \
12700                           "(expected %i, found %i)\n", \
12701                           current_config->name, \
12702                           pipe_config->name); \
12703                 ret = false; \
12704         }
12705
12706 #define PIPE_CONF_CHECK_P(name) \
12707         if (current_config->name != pipe_config->name) { \
12708                 INTEL_ERR_OR_DBG_KMS("mismatch in " #name " " \
12709                           "(expected %p, found %p)\n", \
12710                           current_config->name, \
12711                           pipe_config->name); \
12712                 ret = false; \
12713         }
12714
12715 #define PIPE_CONF_CHECK_M_N(name) \
12716         if (!intel_compare_link_m_n(&current_config->name, \
12717                                     &pipe_config->name,\
12718                                     adjust)) { \
12719                 INTEL_ERR_OR_DBG_KMS("mismatch in " #name " " \
12720                           "(expected tu %i gmch %i/%i link %i/%i, " \
12721                           "found tu %i, gmch %i/%i link %i/%i)\n", \
12722                           current_config->name.tu, \
12723                           current_config->name.gmch_m, \
12724                           current_config->name.gmch_n, \
12725                           current_config->name.link_m, \
12726                           current_config->name.link_n, \
12727                           pipe_config->name.tu, \
12728                           pipe_config->name.gmch_m, \
12729                           pipe_config->name.gmch_n, \
12730                           pipe_config->name.link_m, \
12731                           pipe_config->name.link_n); \
12732                 ret = false; \
12733         }
12734
12735 /* This is required for BDW+ where there is only one set of registers for
12736  * switching between high and low RR.
12737  * This macro can be used whenever a comparison has to be made between one
12738  * hw state and multiple sw state variables.
12739  */
12740 #define PIPE_CONF_CHECK_M_N_ALT(name, alt_name) \
12741         if (!intel_compare_link_m_n(&current_config->name, \
12742                                     &pipe_config->name, adjust) && \
12743             !intel_compare_link_m_n(&current_config->alt_name, \
12744                                     &pipe_config->name, adjust)) { \
12745                 INTEL_ERR_OR_DBG_KMS("mismatch in " #name " " \
12746                           "(expected tu %i gmch %i/%i link %i/%i, " \
12747                           "or tu %i gmch %i/%i link %i/%i, " \
12748                           "found tu %i, gmch %i/%i link %i/%i)\n", \
12749                           current_config->name.tu, \
12750                           current_config->name.gmch_m, \
12751                           current_config->name.gmch_n, \
12752                           current_config->name.link_m, \
12753                           current_config->name.link_n, \
12754                           current_config->alt_name.tu, \
12755                           current_config->alt_name.gmch_m, \
12756                           current_config->alt_name.gmch_n, \
12757                           current_config->alt_name.link_m, \
12758                           current_config->alt_name.link_n, \
12759                           pipe_config->name.tu, \
12760                           pipe_config->name.gmch_m, \
12761                           pipe_config->name.gmch_n, \
12762                           pipe_config->name.link_m, \
12763                           pipe_config->name.link_n); \
12764                 ret = false; \
12765         }
12766
12767 #define PIPE_CONF_CHECK_FLAGS(name, mask)       \
12768         if ((current_config->name ^ pipe_config->name) & (mask)) { \
12769                 INTEL_ERR_OR_DBG_KMS("mismatch in " #name "(" #mask ") " \
12770                           "(expected %i, found %i)\n", \
12771                           current_config->name & (mask), \
12772                           pipe_config->name & (mask)); \
12773                 ret = false; \
12774         }
12775
12776 #define PIPE_CONF_CHECK_CLOCK_FUZZY(name) \
12777         if (!intel_fuzzy_clock_check(current_config->name, pipe_config->name)) { \
12778                 INTEL_ERR_OR_DBG_KMS("mismatch in " #name " " \
12779                           "(expected %i, found %i)\n", \
12780                           current_config->name, \
12781                           pipe_config->name); \
12782                 ret = false; \
12783         }
12784
12785 #define PIPE_CONF_QUIRK(quirk)  \
12786         ((current_config->quirks | pipe_config->quirks) & (quirk))
12787
12788         PIPE_CONF_CHECK_I(cpu_transcoder);
12789
12790         PIPE_CONF_CHECK_I(has_pch_encoder);
12791         PIPE_CONF_CHECK_I(fdi_lanes);
12792         PIPE_CONF_CHECK_M_N(fdi_m_n);
12793
12794         PIPE_CONF_CHECK_I(has_dp_encoder);
12795         PIPE_CONF_CHECK_I(lane_count);
12796
12797         if (INTEL_INFO(dev)->gen < 8) {
12798                 PIPE_CONF_CHECK_M_N(dp_m_n);
12799
12800                 if (current_config->has_drrs)
12801                         PIPE_CONF_CHECK_M_N(dp_m2_n2);
12802         } else
12803                 PIPE_CONF_CHECK_M_N_ALT(dp_m_n, dp_m2_n2);
12804
12805         PIPE_CONF_CHECK_I(has_dsi_encoder);
12806
12807         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hdisplay);
12808         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_htotal);
12809         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hblank_start);
12810         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hblank_end);
12811         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hsync_start);
12812         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hsync_end);
12813
12814         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vdisplay);
12815         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vtotal);
12816         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vblank_start);
12817         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vblank_end);
12818         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vsync_start);
12819         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vsync_end);
12820
12821         PIPE_CONF_CHECK_I(pixel_multiplier);
12822         PIPE_CONF_CHECK_I(has_hdmi_sink);
12823         if ((INTEL_INFO(dev)->gen < 8 && !IS_HASWELL(dev)) ||
12824             IS_VALLEYVIEW(dev) || IS_CHERRYVIEW(dev))
12825                 PIPE_CONF_CHECK_I(limited_color_range);
12826         PIPE_CONF_CHECK_I(has_infoframe);
12827
12828         PIPE_CONF_CHECK_I(has_audio);
12829
12830         PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
12831                               DRM_MODE_FLAG_INTERLACE);
12832
12833         if (!PIPE_CONF_QUIRK(PIPE_CONFIG_QUIRK_MODE_SYNC_FLAGS)) {
12834                 PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
12835                                       DRM_MODE_FLAG_PHSYNC);
12836                 PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
12837                                       DRM_MODE_FLAG_NHSYNC);
12838                 PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
12839                                       DRM_MODE_FLAG_PVSYNC);
12840                 PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
12841                                       DRM_MODE_FLAG_NVSYNC);
12842         }
12843
12844         PIPE_CONF_CHECK_X(gmch_pfit.control);
12845         /* pfit ratios are autocomputed by the hw on gen4+ */
12846         if (INTEL_INFO(dev)->gen < 4)
12847                 PIPE_CONF_CHECK_X(gmch_pfit.pgm_ratios);
12848         PIPE_CONF_CHECK_X(gmch_pfit.lvds_border_bits);
12849
12850         if (!adjust) {
12851                 PIPE_CONF_CHECK_I(pipe_src_w);
12852                 PIPE_CONF_CHECK_I(pipe_src_h);
12853
12854                 PIPE_CONF_CHECK_I(pch_pfit.enabled);
12855                 if (current_config->pch_pfit.enabled) {
12856                         PIPE_CONF_CHECK_X(pch_pfit.pos);
12857                         PIPE_CONF_CHECK_X(pch_pfit.size);
12858                 }
12859
12860                 PIPE_CONF_CHECK_I(scaler_state.scaler_id);
12861         }
12862
12863         /* BDW+ don't expose a synchronous way to read the state */
12864         if (IS_HASWELL(dev))
12865                 PIPE_CONF_CHECK_I(ips_enabled);
12866
12867         PIPE_CONF_CHECK_I(double_wide);
12868
12869         PIPE_CONF_CHECK_X(ddi_pll_sel);
12870
12871         PIPE_CONF_CHECK_P(shared_dpll);
12872         PIPE_CONF_CHECK_X(dpll_hw_state.dpll);
12873         PIPE_CONF_CHECK_X(dpll_hw_state.dpll_md);
12874         PIPE_CONF_CHECK_X(dpll_hw_state.fp0);
12875         PIPE_CONF_CHECK_X(dpll_hw_state.fp1);
12876         PIPE_CONF_CHECK_X(dpll_hw_state.wrpll);
12877         PIPE_CONF_CHECK_X(dpll_hw_state.spll);
12878         PIPE_CONF_CHECK_X(dpll_hw_state.ctrl1);
12879         PIPE_CONF_CHECK_X(dpll_hw_state.cfgcr1);
12880         PIPE_CONF_CHECK_X(dpll_hw_state.cfgcr2);
12881
12882         PIPE_CONF_CHECK_X(dsi_pll.ctrl);
12883         PIPE_CONF_CHECK_X(dsi_pll.div);
12884
12885         if (IS_G4X(dev) || INTEL_INFO(dev)->gen >= 5)
12886                 PIPE_CONF_CHECK_I(pipe_bpp);
12887
12888         PIPE_CONF_CHECK_CLOCK_FUZZY(base.adjusted_mode.crtc_clock);
12889         PIPE_CONF_CHECK_CLOCK_FUZZY(port_clock);
12890
12891 #undef PIPE_CONF_CHECK_X
12892 #undef PIPE_CONF_CHECK_I
12893 #undef PIPE_CONF_CHECK_P
12894 #undef PIPE_CONF_CHECK_FLAGS
12895 #undef PIPE_CONF_CHECK_CLOCK_FUZZY
12896 #undef PIPE_CONF_QUIRK
12897 #undef INTEL_ERR_OR_DBG_KMS
12898
12899         return ret;
12900 }
12901
12902 static void intel_pipe_config_sanity_check(struct drm_i915_private *dev_priv,
12903                                            const struct intel_crtc_state *pipe_config)
12904 {
12905         if (pipe_config->has_pch_encoder) {
12906                 int fdi_dotclock = intel_dotclock_calculate(intel_fdi_link_freq(dev_priv, pipe_config),
12907                                                             &pipe_config->fdi_m_n);
12908                 int dotclock = pipe_config->base.adjusted_mode.crtc_clock;
12909
12910                 /*
12911                  * FDI already provided one idea for the dotclock.
12912                  * Yell if the encoder disagrees.
12913                  */
12914                 WARN(!intel_fuzzy_clock_check(fdi_dotclock, dotclock),
12915                      "FDI dotclock and encoder dotclock mismatch, fdi: %i, encoder: %i\n",
12916                      fdi_dotclock, dotclock);
12917         }
12918 }
12919
12920 static void verify_wm_state(struct drm_crtc *crtc,
12921                             struct drm_crtc_state *new_state)
12922 {
12923         struct drm_device *dev = crtc->dev;
12924         struct drm_i915_private *dev_priv = dev->dev_private;
12925         struct skl_ddb_allocation hw_ddb, *sw_ddb;
12926         struct skl_ddb_entry *hw_entry, *sw_entry;
12927         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
12928         const enum pipe pipe = intel_crtc->pipe;
12929         int plane;
12930
12931         if (INTEL_INFO(dev)->gen < 9 || !new_state->active)
12932                 return;
12933
12934         skl_ddb_get_hw_state(dev_priv, &hw_ddb);
12935         sw_ddb = &dev_priv->wm.skl_hw.ddb;
12936
12937         /* planes */
12938         for_each_plane(dev_priv, pipe, plane) {
12939                 hw_entry = &hw_ddb.plane[pipe][plane];
12940                 sw_entry = &sw_ddb->plane[pipe][plane];
12941
12942                 if (skl_ddb_entry_equal(hw_entry, sw_entry))
12943                         continue;
12944
12945                 DRM_ERROR("mismatch in DDB state pipe %c plane %d "
12946                           "(expected (%u,%u), found (%u,%u))\n",
12947                           pipe_name(pipe), plane + 1,
12948                           sw_entry->start, sw_entry->end,
12949                           hw_entry->start, hw_entry->end);
12950         }
12951
12952         /* cursor */
12953         hw_entry = &hw_ddb.plane[pipe][PLANE_CURSOR];
12954         sw_entry = &sw_ddb->plane[pipe][PLANE_CURSOR];
12955
12956         if (!skl_ddb_entry_equal(hw_entry, sw_entry)) {
12957                 DRM_ERROR("mismatch in DDB state pipe %c cursor "
12958                           "(expected (%u,%u), found (%u,%u))\n",
12959                           pipe_name(pipe),
12960                           sw_entry->start, sw_entry->end,
12961                           hw_entry->start, hw_entry->end);
12962         }
12963 }
12964
12965 static void
12966 verify_connector_state(struct drm_device *dev, struct drm_crtc *crtc)
12967 {
12968         struct drm_connector *connector;
12969
12970         drm_for_each_connector(connector, dev) {
12971                 struct drm_encoder *encoder = connector->encoder;
12972                 struct drm_connector_state *state = connector->state;
12973
12974                 if (state->crtc != crtc)
12975                         continue;
12976
12977                 intel_connector_verify_state(to_intel_connector(connector));
12978
12979                 I915_STATE_WARN(state->best_encoder != encoder,
12980                      "connector's atomic encoder doesn't match legacy encoder\n");
12981         }
12982 }
12983
12984 static void
12985 verify_encoder_state(struct drm_device *dev)
12986 {
12987         struct intel_encoder *encoder;
12988         struct intel_connector *connector;
12989
12990         for_each_intel_encoder(dev, encoder) {
12991                 bool enabled = false;
12992                 enum pipe pipe;
12993
12994                 DRM_DEBUG_KMS("[ENCODER:%d:%s]\n",
12995                               encoder->base.base.id,
12996                               encoder->base.name);
12997
12998                 for_each_intel_connector(dev, connector) {
12999                         if (connector->base.state->best_encoder != &encoder->base)
13000                                 continue;
13001                         enabled = true;
13002
13003                         I915_STATE_WARN(connector->base.state->crtc !=
13004                                         encoder->base.crtc,
13005                              "connector's crtc doesn't match encoder crtc\n");
13006                 }
13007
13008                 I915_STATE_WARN(!!encoder->base.crtc != enabled,
13009                      "encoder's enabled state mismatch "
13010                      "(expected %i, found %i)\n",
13011                      !!encoder->base.crtc, enabled);
13012
13013                 if (!encoder->base.crtc) {
13014                         bool active;
13015
13016                         active = encoder->get_hw_state(encoder, &pipe);
13017                         I915_STATE_WARN(active,
13018                              "encoder detached but still enabled on pipe %c.\n",
13019                              pipe_name(pipe));
13020                 }
13021         }
13022 }
13023
13024 static void
13025 verify_crtc_state(struct drm_crtc *crtc,
13026                   struct drm_crtc_state *old_crtc_state,
13027                   struct drm_crtc_state *new_crtc_state)
13028 {
13029         struct drm_device *dev = crtc->dev;
13030         struct drm_i915_private *dev_priv = dev->dev_private;
13031         struct intel_encoder *encoder;
13032         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
13033         struct intel_crtc_state *pipe_config, *sw_config;
13034         struct drm_atomic_state *old_state;
13035         bool active;
13036
13037         old_state = old_crtc_state->state;
13038         __drm_atomic_helper_crtc_destroy_state(old_crtc_state);
13039         pipe_config = to_intel_crtc_state(old_crtc_state);
13040         memset(pipe_config, 0, sizeof(*pipe_config));
13041         pipe_config->base.crtc = crtc;
13042         pipe_config->base.state = old_state;
13043
13044         DRM_DEBUG_KMS("[CRTC:%d:%s]\n", crtc->base.id, crtc->name);
13045
13046         active = dev_priv->display.get_pipe_config(intel_crtc, pipe_config);
13047
13048         /* hw state is inconsistent with the pipe quirk */
13049         if ((intel_crtc->pipe == PIPE_A && dev_priv->quirks & QUIRK_PIPEA_FORCE) ||
13050             (intel_crtc->pipe == PIPE_B && dev_priv->quirks & QUIRK_PIPEB_FORCE))
13051                 active = new_crtc_state->active;
13052
13053         I915_STATE_WARN(new_crtc_state->active != active,
13054              "crtc active state doesn't match with hw state "
13055              "(expected %i, found %i)\n", new_crtc_state->active, active);
13056
13057         I915_STATE_WARN(intel_crtc->active != new_crtc_state->active,
13058              "transitional active state does not match atomic hw state "
13059              "(expected %i, found %i)\n", new_crtc_state->active, intel_crtc->active);
13060
13061         for_each_encoder_on_crtc(dev, crtc, encoder) {
13062                 enum pipe pipe;
13063
13064                 active = encoder->get_hw_state(encoder, &pipe);
13065                 I915_STATE_WARN(active != new_crtc_state->active,
13066                         "[ENCODER:%i] active %i with crtc active %i\n",
13067                         encoder->base.base.id, active, new_crtc_state->active);
13068
13069                 I915_STATE_WARN(active && intel_crtc->pipe != pipe,
13070                                 "Encoder connected to wrong pipe %c\n",
13071                                 pipe_name(pipe));
13072
13073                 if (active)
13074                         encoder->get_config(encoder, pipe_config);
13075         }
13076
13077         if (!new_crtc_state->active)
13078                 return;
13079
13080         intel_pipe_config_sanity_check(dev_priv, pipe_config);
13081
13082         sw_config = to_intel_crtc_state(crtc->state);
13083         if (!intel_pipe_config_compare(dev, sw_config,
13084                                        pipe_config, false)) {
13085                 I915_STATE_WARN(1, "pipe state doesn't match!\n");
13086                 intel_dump_pipe_config(intel_crtc, pipe_config,
13087                                        "[hw state]");
13088                 intel_dump_pipe_config(intel_crtc, sw_config,
13089                                        "[sw state]");
13090         }
13091 }
13092
13093 static void
13094 verify_single_dpll_state(struct drm_i915_private *dev_priv,
13095                          struct intel_shared_dpll *pll,
13096                          struct drm_crtc *crtc,
13097                          struct drm_crtc_state *new_state)
13098 {
13099         struct intel_dpll_hw_state dpll_hw_state;
13100         unsigned crtc_mask;
13101         bool active;
13102
13103         memset(&dpll_hw_state, 0, sizeof(dpll_hw_state));
13104
13105         DRM_DEBUG_KMS("%s\n", pll->name);
13106
13107         active = pll->funcs.get_hw_state(dev_priv, pll, &dpll_hw_state);
13108
13109         if (!(pll->flags & INTEL_DPLL_ALWAYS_ON)) {
13110                 I915_STATE_WARN(!pll->on && pll->active_mask,
13111                      "pll in active use but not on in sw tracking\n");
13112                 I915_STATE_WARN(pll->on && !pll->active_mask,
13113                      "pll is on but not used by any active crtc\n");
13114                 I915_STATE_WARN(pll->on != active,
13115                      "pll on state mismatch (expected %i, found %i)\n",
13116                      pll->on, active);
13117         }
13118
13119         if (!crtc) {
13120                 I915_STATE_WARN(pll->active_mask & ~pll->config.crtc_mask,
13121                                 "more active pll users than references: %x vs %x\n",
13122                                 pll->active_mask, pll->config.crtc_mask);
13123
13124                 return;
13125         }
13126
13127         crtc_mask = 1 << drm_crtc_index(crtc);
13128
13129         if (new_state->active)
13130                 I915_STATE_WARN(!(pll->active_mask & crtc_mask),
13131                                 "pll active mismatch (expected pipe %c in active mask 0x%02x)\n",
13132                                 pipe_name(drm_crtc_index(crtc)), pll->active_mask);
13133         else
13134                 I915_STATE_WARN(pll->active_mask & crtc_mask,
13135                                 "pll active mismatch (didn't expect pipe %c in active mask 0x%02x)\n",
13136                                 pipe_name(drm_crtc_index(crtc)), pll->active_mask);
13137
13138         I915_STATE_WARN(!(pll->config.crtc_mask & crtc_mask),
13139                         "pll enabled crtcs mismatch (expected 0x%x in 0x%02x)\n",
13140                         crtc_mask, pll->config.crtc_mask);
13141
13142         I915_STATE_WARN(pll->on && memcmp(&pll->config.hw_state,
13143                                           &dpll_hw_state,
13144                                           sizeof(dpll_hw_state)),
13145                         "pll hw state mismatch\n");
13146 }
13147
13148 static void
13149 verify_shared_dpll_state(struct drm_device *dev, struct drm_crtc *crtc,
13150                          struct drm_crtc_state *old_crtc_state,
13151                          struct drm_crtc_state *new_crtc_state)
13152 {
13153         struct drm_i915_private *dev_priv = dev->dev_private;
13154         struct intel_crtc_state *old_state = to_intel_crtc_state(old_crtc_state);
13155         struct intel_crtc_state *new_state = to_intel_crtc_state(new_crtc_state);
13156
13157         if (new_state->shared_dpll)
13158                 verify_single_dpll_state(dev_priv, new_state->shared_dpll, crtc, new_crtc_state);
13159
13160         if (old_state->shared_dpll &&
13161             old_state->shared_dpll != new_state->shared_dpll) {
13162                 unsigned crtc_mask = 1 << drm_crtc_index(crtc);
13163                 struct intel_shared_dpll *pll = old_state->shared_dpll;
13164
13165                 I915_STATE_WARN(pll->active_mask & crtc_mask,
13166                                 "pll active mismatch (didn't expect pipe %c in active mask)\n",
13167                                 pipe_name(drm_crtc_index(crtc)));
13168                 I915_STATE_WARN(pll->config.crtc_mask & crtc_mask,
13169                                 "pll enabled crtcs mismatch (found %x in enabled mask)\n",
13170                                 pipe_name(drm_crtc_index(crtc)));
13171         }
13172 }
13173
13174 static void
13175 intel_modeset_verify_crtc(struct drm_crtc *crtc,
13176                          struct drm_crtc_state *old_state,
13177                          struct drm_crtc_state *new_state)
13178 {
13179         if (!needs_modeset(new_state) &&
13180             !to_intel_crtc_state(new_state)->update_pipe)
13181                 return;
13182
13183         verify_wm_state(crtc, new_state);
13184         verify_connector_state(crtc->dev, crtc);
13185         verify_crtc_state(crtc, old_state, new_state);
13186         verify_shared_dpll_state(crtc->dev, crtc, old_state, new_state);
13187 }
13188
13189 static void
13190 verify_disabled_dpll_state(struct drm_device *dev)
13191 {
13192         struct drm_i915_private *dev_priv = dev->dev_private;
13193         int i;
13194
13195         for (i = 0; i < dev_priv->num_shared_dpll; i++)
13196                 verify_single_dpll_state(dev_priv, &dev_priv->shared_dplls[i], NULL, NULL);
13197 }
13198
13199 static void
13200 intel_modeset_verify_disabled(struct drm_device *dev)
13201 {
13202         verify_encoder_state(dev);
13203         verify_connector_state(dev, NULL);
13204         verify_disabled_dpll_state(dev);
13205 }
13206
13207 static void update_scanline_offset(struct intel_crtc *crtc)
13208 {
13209         struct drm_device *dev = crtc->base.dev;
13210
13211         /*
13212          * The scanline counter increments at the leading edge of hsync.
13213          *
13214          * On most platforms it starts counting from vtotal-1 on the
13215          * first active line. That means the scanline counter value is
13216          * always one less than what we would expect. Ie. just after
13217          * start of vblank, which also occurs at start of hsync (on the
13218          * last active line), the scanline counter will read vblank_start-1.
13219          *
13220          * On gen2 the scanline counter starts counting from 1 instead
13221          * of vtotal-1, so we have to subtract one (or rather add vtotal-1
13222          * to keep the value positive), instead of adding one.
13223          *
13224          * On HSW+ the behaviour of the scanline counter depends on the output
13225          * type. For DP ports it behaves like most other platforms, but on HDMI
13226          * there's an extra 1 line difference. So we need to add two instead of
13227          * one to the value.
13228          */
13229         if (IS_GEN2(dev)) {
13230                 const struct drm_display_mode *adjusted_mode = &crtc->config->base.adjusted_mode;
13231                 int vtotal;
13232
13233                 vtotal = adjusted_mode->crtc_vtotal;
13234                 if (adjusted_mode->flags & DRM_MODE_FLAG_INTERLACE)
13235                         vtotal /= 2;
13236
13237                 crtc->scanline_offset = vtotal - 1;
13238         } else if (HAS_DDI(dev) &&
13239                    intel_pipe_has_type(crtc, INTEL_OUTPUT_HDMI)) {
13240                 crtc->scanline_offset = 2;
13241         } else
13242                 crtc->scanline_offset = 1;
13243 }
13244
13245 static void intel_modeset_clear_plls(struct drm_atomic_state *state)
13246 {
13247         struct drm_device *dev = state->dev;
13248         struct drm_i915_private *dev_priv = to_i915(dev);
13249         struct intel_shared_dpll_config *shared_dpll = NULL;
13250         struct drm_crtc *crtc;
13251         struct drm_crtc_state *crtc_state;
13252         int i;
13253
13254         if (!dev_priv->display.crtc_compute_clock)
13255                 return;
13256
13257         for_each_crtc_in_state(state, crtc, crtc_state, i) {
13258                 struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
13259                 struct intel_shared_dpll *old_dpll =
13260                         to_intel_crtc_state(crtc->state)->shared_dpll;
13261
13262                 if (!needs_modeset(crtc_state))
13263                         continue;
13264
13265                 to_intel_crtc_state(crtc_state)->shared_dpll = NULL;
13266
13267                 if (!old_dpll)
13268                         continue;
13269
13270                 if (!shared_dpll)
13271                         shared_dpll = intel_atomic_get_shared_dpll_state(state);
13272
13273                 intel_shared_dpll_config_put(shared_dpll, old_dpll, intel_crtc);
13274         }
13275 }
13276
13277 /*
13278  * This implements the workaround described in the "notes" section of the mode
13279  * set sequence documentation. When going from no pipes or single pipe to
13280  * multiple pipes, and planes are enabled after the pipe, we need to wait at
13281  * least 2 vblanks on the first pipe before enabling planes on the second pipe.
13282  */
13283 static int haswell_mode_set_planes_workaround(struct drm_atomic_state *state)
13284 {
13285         struct drm_crtc_state *crtc_state;
13286         struct intel_crtc *intel_crtc;
13287         struct drm_crtc *crtc;
13288         struct intel_crtc_state *first_crtc_state = NULL;
13289         struct intel_crtc_state *other_crtc_state = NULL;
13290         enum pipe first_pipe = INVALID_PIPE, enabled_pipe = INVALID_PIPE;
13291         int i;
13292
13293         /* look at all crtc's that are going to be enabled in during modeset */
13294         for_each_crtc_in_state(state, crtc, crtc_state, i) {
13295                 intel_crtc = to_intel_crtc(crtc);
13296
13297                 if (!crtc_state->active || !needs_modeset(crtc_state))
13298                         continue;
13299
13300                 if (first_crtc_state) {
13301                         other_crtc_state = to_intel_crtc_state(crtc_state);
13302                         break;
13303                 } else {
13304                         first_crtc_state = to_intel_crtc_state(crtc_state);
13305                         first_pipe = intel_crtc->pipe;
13306                 }
13307         }
13308
13309         /* No workaround needed? */
13310         if (!first_crtc_state)
13311                 return 0;
13312
13313         /* w/a possibly needed, check how many crtc's are already enabled. */
13314         for_each_intel_crtc(state->dev, intel_crtc) {
13315                 struct intel_crtc_state *pipe_config;
13316
13317                 pipe_config = intel_atomic_get_crtc_state(state, intel_crtc);
13318                 if (IS_ERR(pipe_config))
13319                         return PTR_ERR(pipe_config);
13320
13321                 pipe_config->hsw_workaround_pipe = INVALID_PIPE;
13322
13323                 if (!pipe_config->base.active ||
13324                     needs_modeset(&pipe_config->base))
13325                         continue;
13326
13327                 /* 2 or more enabled crtcs means no need for w/a */
13328                 if (enabled_pipe != INVALID_PIPE)
13329                         return 0;
13330
13331                 enabled_pipe = intel_crtc->pipe;
13332         }
13333
13334         if (enabled_pipe != INVALID_PIPE)
13335                 first_crtc_state->hsw_workaround_pipe = enabled_pipe;
13336         else if (other_crtc_state)
13337                 other_crtc_state->hsw_workaround_pipe = first_pipe;
13338
13339         return 0;
13340 }
13341
13342 static int intel_modeset_all_pipes(struct drm_atomic_state *state)
13343 {
13344         struct drm_crtc *crtc;
13345         struct drm_crtc_state *crtc_state;
13346         int ret = 0;
13347
13348         /* add all active pipes to the state */
13349         for_each_crtc(state->dev, crtc) {
13350                 crtc_state = drm_atomic_get_crtc_state(state, crtc);
13351                 if (IS_ERR(crtc_state))
13352                         return PTR_ERR(crtc_state);
13353
13354                 if (!crtc_state->active || needs_modeset(crtc_state))
13355                         continue;
13356
13357                 crtc_state->mode_changed = true;
13358
13359                 ret = drm_atomic_add_affected_connectors(state, crtc);
13360                 if (ret)
13361                         break;
13362
13363                 ret = drm_atomic_add_affected_planes(state, crtc);
13364                 if (ret)
13365                         break;
13366         }
13367
13368         return ret;
13369 }
13370
13371 static int intel_modeset_checks(struct drm_atomic_state *state)
13372 {
13373         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
13374         struct drm_i915_private *dev_priv = state->dev->dev_private;
13375         struct drm_crtc *crtc;
13376         struct drm_crtc_state *crtc_state;
13377         int ret = 0, i;
13378
13379         if (!check_digital_port_conflicts(state)) {
13380                 DRM_DEBUG_KMS("rejecting conflicting digital port configuration\n");
13381                 return -EINVAL;
13382         }
13383
13384         intel_state->modeset = true;
13385         intel_state->active_crtcs = dev_priv->active_crtcs;
13386
13387         for_each_crtc_in_state(state, crtc, crtc_state, i) {
13388                 if (crtc_state->active)
13389                         intel_state->active_crtcs |= 1 << i;
13390                 else
13391                         intel_state->active_crtcs &= ~(1 << i);
13392
13393                 if (crtc_state->active != crtc->state->active)
13394                         intel_state->active_pipe_changes |= drm_crtc_mask(crtc);
13395         }
13396
13397         /*
13398          * See if the config requires any additional preparation, e.g.
13399          * to adjust global state with pipes off.  We need to do this
13400          * here so we can get the modeset_pipe updated config for the new
13401          * mode set on this crtc.  For other crtcs we need to use the
13402          * adjusted_mode bits in the crtc directly.
13403          */
13404         if (dev_priv->display.modeset_calc_cdclk) {
13405                 if (!intel_state->cdclk_pll_vco)
13406                         intel_state->cdclk_pll_vco = dev_priv->cdclk_pll.vco;
13407                 if (!intel_state->cdclk_pll_vco)
13408                         intel_state->cdclk_pll_vco = dev_priv->skl_preferred_vco_freq;
13409
13410                 ret = dev_priv->display.modeset_calc_cdclk(state);
13411                 if (ret < 0)
13412                         return ret;
13413
13414                 if (intel_state->dev_cdclk != dev_priv->cdclk_freq ||
13415                     intel_state->cdclk_pll_vco != dev_priv->cdclk_pll.vco)
13416                         ret = intel_modeset_all_pipes(state);
13417
13418                 if (ret < 0)
13419                         return ret;
13420
13421                 DRM_DEBUG_KMS("New cdclk calculated to be atomic %u, actual %u\n",
13422                               intel_state->cdclk, intel_state->dev_cdclk);
13423         } else
13424                 to_intel_atomic_state(state)->cdclk = dev_priv->atomic_cdclk_freq;
13425
13426         intel_modeset_clear_plls(state);
13427
13428         if (IS_HASWELL(dev_priv))
13429                 return haswell_mode_set_planes_workaround(state);
13430
13431         return 0;
13432 }
13433
13434 /*
13435  * Handle calculation of various watermark data at the end of the atomic check
13436  * phase.  The code here should be run after the per-crtc and per-plane 'check'
13437  * handlers to ensure that all derived state has been updated.
13438  */
13439 static int calc_watermark_data(struct drm_atomic_state *state)
13440 {
13441         struct drm_device *dev = state->dev;
13442         struct drm_i915_private *dev_priv = to_i915(dev);
13443
13444         /* Is there platform-specific watermark information to calculate? */
13445         if (dev_priv->display.compute_global_watermarks)
13446                 return dev_priv->display.compute_global_watermarks(state);
13447
13448         return 0;
13449 }
13450
13451 /**
13452  * intel_atomic_check - validate state object
13453  * @dev: drm device
13454  * @state: state to validate
13455  */
13456 static int intel_atomic_check(struct drm_device *dev,
13457                               struct drm_atomic_state *state)
13458 {
13459         struct drm_i915_private *dev_priv = to_i915(dev);
13460         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
13461         struct drm_crtc *crtc;
13462         struct drm_crtc_state *crtc_state;
13463         int ret, i;
13464         bool any_ms = false;
13465
13466         ret = drm_atomic_helper_check_modeset(dev, state);
13467         if (ret)
13468                 return ret;
13469
13470         for_each_crtc_in_state(state, crtc, crtc_state, i) {
13471                 struct intel_crtc_state *pipe_config =
13472                         to_intel_crtc_state(crtc_state);
13473
13474                 /* Catch I915_MODE_FLAG_INHERITED */
13475                 if (crtc_state->mode.private_flags != crtc->state->mode.private_flags)
13476                         crtc_state->mode_changed = true;
13477
13478                 if (!needs_modeset(crtc_state))
13479                         continue;
13480
13481                 if (!crtc_state->enable) {
13482                         any_ms = true;
13483                         continue;
13484                 }
13485
13486                 /* FIXME: For only active_changed we shouldn't need to do any
13487                  * state recomputation at all. */
13488
13489                 ret = drm_atomic_add_affected_connectors(state, crtc);
13490                 if (ret)
13491                         return ret;
13492
13493                 ret = intel_modeset_pipe_config(crtc, pipe_config);
13494                 if (ret) {
13495                         intel_dump_pipe_config(to_intel_crtc(crtc),
13496                                                pipe_config, "[failed]");
13497                         return ret;
13498                 }
13499
13500                 if (i915.fastboot &&
13501                     intel_pipe_config_compare(dev,
13502                                         to_intel_crtc_state(crtc->state),
13503                                         pipe_config, true)) {
13504                         crtc_state->mode_changed = false;
13505                         to_intel_crtc_state(crtc_state)->update_pipe = true;
13506                 }
13507
13508                 if (needs_modeset(crtc_state))
13509                         any_ms = true;
13510
13511                 ret = drm_atomic_add_affected_planes(state, crtc);
13512                 if (ret)
13513                         return ret;
13514
13515                 intel_dump_pipe_config(to_intel_crtc(crtc), pipe_config,
13516                                        needs_modeset(crtc_state) ?
13517                                        "[modeset]" : "[fastset]");
13518         }
13519
13520         if (any_ms) {
13521                 ret = intel_modeset_checks(state);
13522
13523                 if (ret)
13524                         return ret;
13525         } else
13526                 intel_state->cdclk = dev_priv->cdclk_freq;
13527
13528         ret = drm_atomic_helper_check_planes(dev, state);
13529         if (ret)
13530                 return ret;
13531
13532         intel_fbc_choose_crtc(dev_priv, state);
13533         return calc_watermark_data(state);
13534 }
13535
13536 static int intel_atomic_prepare_commit(struct drm_device *dev,
13537                                        struct drm_atomic_state *state,
13538                                        bool nonblock)
13539 {
13540         struct drm_i915_private *dev_priv = dev->dev_private;
13541         struct drm_plane_state *plane_state;
13542         struct drm_crtc_state *crtc_state;
13543         struct drm_plane *plane;
13544         struct drm_crtc *crtc;
13545         int i, ret;
13546
13547         if (nonblock) {
13548                 DRM_DEBUG_KMS("i915 does not yet support nonblocking commit\n");
13549                 return -EINVAL;
13550         }
13551
13552         for_each_crtc_in_state(state, crtc, crtc_state, i) {
13553                 if (state->legacy_cursor_update)
13554                         continue;
13555
13556                 ret = intel_crtc_wait_for_pending_flips(crtc);
13557                 if (ret)
13558                         return ret;
13559
13560                 if (atomic_read(&to_intel_crtc(crtc)->unpin_work_count) >= 2)
13561                         flush_workqueue(dev_priv->wq);
13562         }
13563
13564         ret = mutex_lock_interruptible(&dev->struct_mutex);
13565         if (ret)
13566                 return ret;
13567
13568         ret = drm_atomic_helper_prepare_planes(dev, state);
13569         mutex_unlock(&dev->struct_mutex);
13570
13571         if (!ret && !nonblock) {
13572                 for_each_plane_in_state(state, plane, plane_state, i) {
13573                         struct intel_plane_state *intel_plane_state =
13574                                 to_intel_plane_state(plane_state);
13575
13576                         if (!intel_plane_state->wait_req)
13577                                 continue;
13578
13579                         ret = __i915_wait_request(intel_plane_state->wait_req,
13580                                                   true, NULL, NULL);
13581                         if (ret) {
13582                                 /* Any hang should be swallowed by the wait */
13583                                 WARN_ON(ret == -EIO);
13584                                 mutex_lock(&dev->struct_mutex);
13585                                 drm_atomic_helper_cleanup_planes(dev, state);
13586                                 mutex_unlock(&dev->struct_mutex);
13587                                 break;
13588                         }
13589                 }
13590         }
13591
13592         return ret;
13593 }
13594
13595 u32 intel_crtc_get_vblank_counter(struct intel_crtc *crtc)
13596 {
13597         struct drm_device *dev = crtc->base.dev;
13598
13599         if (!dev->max_vblank_count)
13600                 return drm_accurate_vblank_count(&crtc->base);
13601
13602         return dev->driver->get_vblank_counter(dev, crtc->pipe);
13603 }
13604
13605 static void intel_atomic_wait_for_vblanks(struct drm_device *dev,
13606                                           struct drm_i915_private *dev_priv,
13607                                           unsigned crtc_mask)
13608 {
13609         unsigned last_vblank_count[I915_MAX_PIPES];
13610         enum pipe pipe;
13611         int ret;
13612
13613         if (!crtc_mask)
13614                 return;
13615
13616         for_each_pipe(dev_priv, pipe) {
13617                 struct drm_crtc *crtc = dev_priv->pipe_to_crtc_mapping[pipe];
13618
13619                 if (!((1 << pipe) & crtc_mask))
13620                         continue;
13621
13622                 ret = drm_crtc_vblank_get(crtc);
13623                 if (WARN_ON(ret != 0)) {
13624                         crtc_mask &= ~(1 << pipe);
13625                         continue;
13626                 }
13627
13628                 last_vblank_count[pipe] = drm_crtc_vblank_count(crtc);
13629         }
13630
13631         for_each_pipe(dev_priv, pipe) {
13632                 struct drm_crtc *crtc = dev_priv->pipe_to_crtc_mapping[pipe];
13633                 long lret;
13634
13635                 if (!((1 << pipe) & crtc_mask))
13636                         continue;
13637
13638                 lret = wait_event_timeout(dev->vblank[pipe].queue,
13639                                 last_vblank_count[pipe] !=
13640                                         drm_crtc_vblank_count(crtc),
13641                                 msecs_to_jiffies(50));
13642
13643                 WARN(!lret, "pipe %c vblank wait timed out\n", pipe_name(pipe));
13644
13645                 drm_crtc_vblank_put(crtc);
13646         }
13647 }
13648
13649 static bool needs_vblank_wait(struct intel_crtc_state *crtc_state)
13650 {
13651         /* fb updated, need to unpin old fb */
13652         if (crtc_state->fb_changed)
13653                 return true;
13654
13655         /* wm changes, need vblank before final wm's */
13656         if (crtc_state->update_wm_post)
13657                 return true;
13658
13659         /*
13660          * cxsr is re-enabled after vblank.
13661          * This is already handled by crtc_state->update_wm_post,
13662          * but added for clarity.
13663          */
13664         if (crtc_state->disable_cxsr)
13665                 return true;
13666
13667         return false;
13668 }
13669
13670 /**
13671  * intel_atomic_commit - commit validated state object
13672  * @dev: DRM device
13673  * @state: the top-level driver state object
13674  * @nonblock: nonblocking commit
13675  *
13676  * This function commits a top-level state object that has been validated
13677  * with drm_atomic_helper_check().
13678  *
13679  * FIXME:  Atomic modeset support for i915 is not yet complete.  At the moment
13680  * we can only handle plane-related operations and do not yet support
13681  * nonblocking commit.
13682  *
13683  * RETURNS
13684  * Zero for success or -errno.
13685  */
13686 static int intel_atomic_commit(struct drm_device *dev,
13687                                struct drm_atomic_state *state,
13688                                bool nonblock)
13689 {
13690         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
13691         struct drm_i915_private *dev_priv = dev->dev_private;
13692         struct drm_crtc_state *old_crtc_state;
13693         struct drm_crtc *crtc;
13694         struct intel_crtc_state *intel_cstate;
13695         int ret = 0, i;
13696         bool hw_check = intel_state->modeset;
13697         unsigned long put_domains[I915_MAX_PIPES] = {};
13698         unsigned crtc_vblank_mask = 0;
13699
13700         ret = intel_atomic_prepare_commit(dev, state, nonblock);
13701         if (ret) {
13702                 DRM_DEBUG_ATOMIC("Preparing state failed with %i\n", ret);
13703                 return ret;
13704         }
13705
13706         drm_atomic_helper_swap_state(dev, state);
13707         dev_priv->wm.distrust_bios_wm = false;
13708         dev_priv->wm.skl_results = intel_state->wm_results;
13709         intel_shared_dpll_commit(state);
13710
13711         if (intel_state->modeset) {
13712                 memcpy(dev_priv->min_pixclk, intel_state->min_pixclk,
13713                        sizeof(intel_state->min_pixclk));
13714                 dev_priv->active_crtcs = intel_state->active_crtcs;
13715                 dev_priv->atomic_cdclk_freq = intel_state->cdclk;
13716
13717                 intel_display_power_get(dev_priv, POWER_DOMAIN_MODESET);
13718         }
13719
13720         for_each_crtc_in_state(state, crtc, old_crtc_state, i) {
13721                 struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
13722
13723                 if (needs_modeset(crtc->state) ||
13724                     to_intel_crtc_state(crtc->state)->update_pipe) {
13725                         hw_check = true;
13726
13727                         put_domains[to_intel_crtc(crtc)->pipe] =
13728                                 modeset_get_crtc_power_domains(crtc,
13729                                         to_intel_crtc_state(crtc->state));
13730                 }
13731
13732                 if (!needs_modeset(crtc->state))
13733                         continue;
13734
13735                 intel_pre_plane_update(to_intel_crtc_state(old_crtc_state));
13736
13737                 if (old_crtc_state->active) {
13738                         intel_crtc_disable_planes(crtc, old_crtc_state->plane_mask);
13739                         dev_priv->display.crtc_disable(crtc);
13740                         intel_crtc->active = false;
13741                         intel_fbc_disable(intel_crtc);
13742                         intel_disable_shared_dpll(intel_crtc);
13743
13744                         /*
13745                          * Underruns don't always raise
13746                          * interrupts, so check manually.
13747                          */
13748                         intel_check_cpu_fifo_underruns(dev_priv);
13749                         intel_check_pch_fifo_underruns(dev_priv);
13750
13751                         if (!crtc->state->active)
13752                                 intel_update_watermarks(crtc);
13753                 }
13754         }
13755
13756         /* Only after disabling all output pipelines that will be changed can we
13757          * update the the output configuration. */
13758         intel_modeset_update_crtc_state(state);
13759
13760         if (intel_state->modeset) {
13761                 drm_atomic_helper_update_legacy_modeset_state(state->dev, state);
13762
13763                 if (dev_priv->display.modeset_commit_cdclk &&
13764                     (intel_state->dev_cdclk != dev_priv->cdclk_freq ||
13765                      intel_state->cdclk_pll_vco != dev_priv->cdclk_pll.vco))
13766                         dev_priv->display.modeset_commit_cdclk(state);
13767
13768                 intel_modeset_verify_disabled(dev);
13769         }
13770
13771         /* Now enable the clocks, plane, pipe, and connectors that we set up. */
13772         for_each_crtc_in_state(state, crtc, old_crtc_state, i) {
13773                 struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
13774                 bool modeset = needs_modeset(crtc->state);
13775                 struct intel_crtc_state *pipe_config =
13776                         to_intel_crtc_state(crtc->state);
13777                 bool update_pipe = !modeset && pipe_config->update_pipe;
13778
13779                 if (modeset && crtc->state->active) {
13780                         update_scanline_offset(to_intel_crtc(crtc));
13781                         dev_priv->display.crtc_enable(crtc);
13782                 }
13783
13784                 if (!modeset)
13785                         intel_pre_plane_update(to_intel_crtc_state(old_crtc_state));
13786
13787                 if (crtc->state->active &&
13788                     drm_atomic_get_existing_plane_state(state, crtc->primary))
13789                         intel_fbc_enable(intel_crtc);
13790
13791                 if (crtc->state->active &&
13792                     (crtc->state->planes_changed || update_pipe))
13793                         drm_atomic_helper_commit_planes_on_crtc(old_crtc_state);
13794
13795                 if (pipe_config->base.active && needs_vblank_wait(pipe_config))
13796                         crtc_vblank_mask |= 1 << i;
13797         }
13798
13799         /* FIXME: add subpixel order */
13800
13801         if (!state->legacy_cursor_update)
13802                 intel_atomic_wait_for_vblanks(dev, dev_priv, crtc_vblank_mask);
13803
13804         /*
13805          * Now that the vblank has passed, we can go ahead and program the
13806          * optimal watermarks on platforms that need two-step watermark
13807          * programming.
13808          *
13809          * TODO: Move this (and other cleanup) to an async worker eventually.
13810          */
13811         for_each_crtc_in_state(state, crtc, old_crtc_state, i) {
13812                 intel_cstate = to_intel_crtc_state(crtc->state);
13813
13814                 if (dev_priv->display.optimize_watermarks)
13815                         dev_priv->display.optimize_watermarks(intel_cstate);
13816         }
13817
13818         for_each_crtc_in_state(state, crtc, old_crtc_state, i) {
13819                 intel_post_plane_update(to_intel_crtc_state(old_crtc_state));
13820
13821                 if (put_domains[i])
13822                         modeset_put_power_domains(dev_priv, put_domains[i]);
13823
13824                 intel_modeset_verify_crtc(crtc, old_crtc_state, crtc->state);
13825         }
13826
13827         if (intel_state->modeset)
13828                 intel_display_power_put(dev_priv, POWER_DOMAIN_MODESET);
13829
13830         mutex_lock(&dev->struct_mutex);
13831         drm_atomic_helper_cleanup_planes(dev, state);
13832         mutex_unlock(&dev->struct_mutex);
13833
13834         drm_atomic_state_free(state);
13835
13836         /* As one of the primary mmio accessors, KMS has a high likelihood
13837          * of triggering bugs in unclaimed access. After we finish
13838          * modesetting, see if an error has been flagged, and if so
13839          * enable debugging for the next modeset - and hope we catch
13840          * the culprit.
13841          *
13842          * XXX note that we assume display power is on at this point.
13843          * This might hold true now but we need to add pm helper to check
13844          * unclaimed only when the hardware is on, as atomic commits
13845          * can happen also when the device is completely off.
13846          */
13847         intel_uncore_arm_unclaimed_mmio_detection(dev_priv);
13848
13849         return 0;
13850 }
13851
13852 void intel_crtc_restore_mode(struct drm_crtc *crtc)
13853 {
13854         struct drm_device *dev = crtc->dev;
13855         struct drm_atomic_state *state;
13856         struct drm_crtc_state *crtc_state;
13857         int ret;
13858
13859         state = drm_atomic_state_alloc(dev);
13860         if (!state) {
13861                 DRM_DEBUG_KMS("[CRTC:%d:%s] crtc restore failed, out of memory",
13862                               crtc->base.id, crtc->name);
13863                 return;
13864         }
13865
13866         state->acquire_ctx = drm_modeset_legacy_acquire_ctx(crtc);
13867
13868 retry:
13869         crtc_state = drm_atomic_get_crtc_state(state, crtc);
13870         ret = PTR_ERR_OR_ZERO(crtc_state);
13871         if (!ret) {
13872                 if (!crtc_state->active)
13873                         goto out;
13874
13875                 crtc_state->mode_changed = true;
13876                 ret = drm_atomic_commit(state);
13877         }
13878
13879         if (ret == -EDEADLK) {
13880                 drm_atomic_state_clear(state);
13881                 drm_modeset_backoff(state->acquire_ctx);
13882                 goto retry;
13883         }
13884
13885         if (ret)
13886 out:
13887                 drm_atomic_state_free(state);
13888 }
13889
13890 #undef for_each_intel_crtc_masked
13891
13892 static const struct drm_crtc_funcs intel_crtc_funcs = {
13893         .gamma_set = drm_atomic_helper_legacy_gamma_set,
13894         .set_config = drm_atomic_helper_set_config,
13895         .set_property = drm_atomic_helper_crtc_set_property,
13896         .destroy = intel_crtc_destroy,
13897         .page_flip = intel_crtc_page_flip,
13898         .atomic_duplicate_state = intel_crtc_duplicate_state,
13899         .atomic_destroy_state = intel_crtc_destroy_state,
13900 };
13901
13902 /**
13903  * intel_prepare_plane_fb - Prepare fb for usage on plane
13904  * @plane: drm plane to prepare for
13905  * @fb: framebuffer to prepare for presentation
13906  *
13907  * Prepares a framebuffer for usage on a display plane.  Generally this
13908  * involves pinning the underlying object and updating the frontbuffer tracking
13909  * bits.  Some older platforms need special physical address handling for
13910  * cursor planes.
13911  *
13912  * Must be called with struct_mutex held.
13913  *
13914  * Returns 0 on success, negative error code on failure.
13915  */
13916 int
13917 intel_prepare_plane_fb(struct drm_plane *plane,
13918                        const struct drm_plane_state *new_state)
13919 {
13920         struct drm_device *dev = plane->dev;
13921         struct drm_framebuffer *fb = new_state->fb;
13922         struct intel_plane *intel_plane = to_intel_plane(plane);
13923         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
13924         struct drm_i915_gem_object *old_obj = intel_fb_obj(plane->state->fb);
13925         int ret = 0;
13926
13927         if (!obj && !old_obj)
13928                 return 0;
13929
13930         if (old_obj) {
13931                 struct drm_crtc_state *crtc_state =
13932                         drm_atomic_get_existing_crtc_state(new_state->state, plane->state->crtc);
13933
13934                 /* Big Hammer, we also need to ensure that any pending
13935                  * MI_WAIT_FOR_EVENT inside a user batch buffer on the
13936                  * current scanout is retired before unpinning the old
13937                  * framebuffer. Note that we rely on userspace rendering
13938                  * into the buffer attached to the pipe they are waiting
13939                  * on. If not, userspace generates a GPU hang with IPEHR
13940                  * point to the MI_WAIT_FOR_EVENT.
13941                  *
13942                  * This should only fail upon a hung GPU, in which case we
13943                  * can safely continue.
13944                  */
13945                 if (needs_modeset(crtc_state))
13946                         ret = i915_gem_object_wait_rendering(old_obj, true);
13947                 if (ret) {
13948                         /* GPU hangs should have been swallowed by the wait */
13949                         WARN_ON(ret == -EIO);
13950                         return ret;
13951                 }
13952         }
13953
13954         /* For framebuffer backed by dmabuf, wait for fence */
13955         if (obj && obj->base.dma_buf) {
13956                 long lret;
13957
13958                 lret = reservation_object_wait_timeout_rcu(obj->base.dma_buf->resv,
13959                                                            false, true,
13960                                                            MAX_SCHEDULE_TIMEOUT);
13961                 if (lret == -ERESTARTSYS)
13962                         return lret;
13963
13964                 WARN(lret < 0, "waiting returns %li\n", lret);
13965         }
13966
13967         if (!obj) {
13968                 ret = 0;
13969         } else if (plane->type == DRM_PLANE_TYPE_CURSOR &&
13970             INTEL_INFO(dev)->cursor_needs_physical) {
13971                 int align = IS_I830(dev) ? 16 * 1024 : 256;
13972                 ret = i915_gem_object_attach_phys(obj, align);
13973                 if (ret)
13974                         DRM_DEBUG_KMS("failed to attach phys object\n");
13975         } else {
13976                 ret = intel_pin_and_fence_fb_obj(fb, new_state->rotation);
13977         }
13978
13979         if (ret == 0) {
13980                 if (obj) {
13981                         struct intel_plane_state *plane_state =
13982                                 to_intel_plane_state(new_state);
13983
13984                         i915_gem_request_assign(&plane_state->wait_req,
13985                                                 obj->last_write_req);
13986                 }
13987
13988                 i915_gem_track_fb(old_obj, obj, intel_plane->frontbuffer_bit);
13989         }
13990
13991         return ret;
13992 }
13993
13994 /**
13995  * intel_cleanup_plane_fb - Cleans up an fb after plane use
13996  * @plane: drm plane to clean up for
13997  * @fb: old framebuffer that was on plane
13998  *
13999  * Cleans up a framebuffer that has just been removed from a plane.
14000  *
14001  * Must be called with struct_mutex held.
14002  */
14003 void
14004 intel_cleanup_plane_fb(struct drm_plane *plane,
14005                        const struct drm_plane_state *old_state)
14006 {
14007         struct drm_device *dev = plane->dev;
14008         struct intel_plane *intel_plane = to_intel_plane(plane);
14009         struct intel_plane_state *old_intel_state;
14010         struct drm_i915_gem_object *old_obj = intel_fb_obj(old_state->fb);
14011         struct drm_i915_gem_object *obj = intel_fb_obj(plane->state->fb);
14012
14013         old_intel_state = to_intel_plane_state(old_state);
14014
14015         if (!obj && !old_obj)
14016                 return;
14017
14018         if (old_obj && (plane->type != DRM_PLANE_TYPE_CURSOR ||
14019             !INTEL_INFO(dev)->cursor_needs_physical))
14020                 intel_unpin_fb_obj(old_state->fb, old_state->rotation);
14021
14022         /* prepare_fb aborted? */
14023         if ((old_obj && (old_obj->frontbuffer_bits & intel_plane->frontbuffer_bit)) ||
14024             (obj && !(obj->frontbuffer_bits & intel_plane->frontbuffer_bit)))
14025                 i915_gem_track_fb(old_obj, obj, intel_plane->frontbuffer_bit);
14026
14027         i915_gem_request_assign(&old_intel_state->wait_req, NULL);
14028 }
14029
14030 int
14031 skl_max_scale(struct intel_crtc *intel_crtc, struct intel_crtc_state *crtc_state)
14032 {
14033         int max_scale;
14034         struct drm_device *dev;
14035         struct drm_i915_private *dev_priv;
14036         int crtc_clock, cdclk;
14037
14038         if (!intel_crtc || !crtc_state->base.enable)
14039                 return DRM_PLANE_HELPER_NO_SCALING;
14040
14041         dev = intel_crtc->base.dev;
14042         dev_priv = dev->dev_private;
14043         crtc_clock = crtc_state->base.adjusted_mode.crtc_clock;
14044         cdclk = to_intel_atomic_state(crtc_state->base.state)->cdclk;
14045
14046         if (WARN_ON_ONCE(!crtc_clock || cdclk < crtc_clock))
14047                 return DRM_PLANE_HELPER_NO_SCALING;
14048
14049         /*
14050          * skl max scale is lower of:
14051          *    close to 3 but not 3, -1 is for that purpose
14052          *            or
14053          *    cdclk/crtc_clock
14054          */
14055         max_scale = min((1 << 16) * 3 - 1, (1 << 8) * ((cdclk << 8) / crtc_clock));
14056
14057         return max_scale;
14058 }
14059
14060 static int
14061 intel_check_primary_plane(struct drm_plane *plane,
14062                           struct intel_crtc_state *crtc_state,
14063                           struct intel_plane_state *state)
14064 {
14065         struct drm_crtc *crtc = state->base.crtc;
14066         struct drm_framebuffer *fb = state->base.fb;
14067         int min_scale = DRM_PLANE_HELPER_NO_SCALING;
14068         int max_scale = DRM_PLANE_HELPER_NO_SCALING;
14069         bool can_position = false;
14070
14071         if (INTEL_INFO(plane->dev)->gen >= 9) {
14072                 /* use scaler when colorkey is not required */
14073                 if (state->ckey.flags == I915_SET_COLORKEY_NONE) {
14074                         min_scale = 1;
14075                         max_scale = skl_max_scale(to_intel_crtc(crtc), crtc_state);
14076                 }
14077                 can_position = true;
14078         }
14079
14080         return drm_plane_helper_check_update(plane, crtc, fb, &state->src,
14081                                              &state->dst, &state->clip,
14082                                              min_scale, max_scale,
14083                                              can_position, true,
14084                                              &state->visible);
14085 }
14086
14087 static void intel_begin_crtc_commit(struct drm_crtc *crtc,
14088                                     struct drm_crtc_state *old_crtc_state)
14089 {
14090         struct drm_device *dev = crtc->dev;
14091         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
14092         struct intel_crtc_state *old_intel_state =
14093                 to_intel_crtc_state(old_crtc_state);
14094         bool modeset = needs_modeset(crtc->state);
14095
14096         /* Perform vblank evasion around commit operation */
14097         intel_pipe_update_start(intel_crtc);
14098
14099         if (modeset)
14100                 return;
14101
14102         if (crtc->state->color_mgmt_changed || to_intel_crtc_state(crtc->state)->update_pipe) {
14103                 intel_color_set_csc(crtc->state);
14104                 intel_color_load_luts(crtc->state);
14105         }
14106
14107         if (to_intel_crtc_state(crtc->state)->update_pipe)
14108                 intel_update_pipe_config(intel_crtc, old_intel_state);
14109         else if (INTEL_INFO(dev)->gen >= 9)
14110                 skl_detach_scalers(intel_crtc);
14111 }
14112
14113 static void intel_finish_crtc_commit(struct drm_crtc *crtc,
14114                                      struct drm_crtc_state *old_crtc_state)
14115 {
14116         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
14117
14118         intel_pipe_update_end(intel_crtc, NULL);
14119 }
14120
14121 /**
14122  * intel_plane_destroy - destroy a plane
14123  * @plane: plane to destroy
14124  *
14125  * Common destruction function for all types of planes (primary, cursor,
14126  * sprite).
14127  */
14128 void intel_plane_destroy(struct drm_plane *plane)
14129 {
14130         if (!plane)
14131                 return;
14132
14133         drm_plane_cleanup(plane);
14134         kfree(to_intel_plane(plane));
14135 }
14136
14137 const struct drm_plane_funcs intel_plane_funcs = {
14138         .update_plane = drm_atomic_helper_update_plane,
14139         .disable_plane = drm_atomic_helper_disable_plane,
14140         .destroy = intel_plane_destroy,
14141         .set_property = drm_atomic_helper_plane_set_property,
14142         .atomic_get_property = intel_plane_atomic_get_property,
14143         .atomic_set_property = intel_plane_atomic_set_property,
14144         .atomic_duplicate_state = intel_plane_duplicate_state,
14145         .atomic_destroy_state = intel_plane_destroy_state,
14146
14147 };
14148
14149 static struct drm_plane *intel_primary_plane_create(struct drm_device *dev,
14150                                                     int pipe)
14151 {
14152         struct intel_plane *primary = NULL;
14153         struct intel_plane_state *state = NULL;
14154         const uint32_t *intel_primary_formats;
14155         unsigned int num_formats;
14156         int ret;
14157
14158         primary = kzalloc(sizeof(*primary), GFP_KERNEL);
14159         if (!primary)
14160                 goto fail;
14161
14162         state = intel_create_plane_state(&primary->base);
14163         if (!state)
14164                 goto fail;
14165         primary->base.state = &state->base;
14166
14167         primary->can_scale = false;
14168         primary->max_downscale = 1;
14169         if (INTEL_INFO(dev)->gen >= 9) {
14170                 primary->can_scale = true;
14171                 state->scaler_id = -1;
14172         }
14173         primary->pipe = pipe;
14174         primary->plane = pipe;
14175         primary->frontbuffer_bit = INTEL_FRONTBUFFER_PRIMARY(pipe);
14176         primary->check_plane = intel_check_primary_plane;
14177         if (HAS_FBC(dev) && INTEL_INFO(dev)->gen < 4)
14178                 primary->plane = !pipe;
14179
14180         if (INTEL_INFO(dev)->gen >= 9) {
14181                 intel_primary_formats = skl_primary_formats;
14182                 num_formats = ARRAY_SIZE(skl_primary_formats);
14183
14184                 primary->update_plane = skylake_update_primary_plane;
14185                 primary->disable_plane = skylake_disable_primary_plane;
14186         } else if (HAS_PCH_SPLIT(dev)) {
14187                 intel_primary_formats = i965_primary_formats;
14188                 num_formats = ARRAY_SIZE(i965_primary_formats);
14189
14190                 primary->update_plane = ironlake_update_primary_plane;
14191                 primary->disable_plane = i9xx_disable_primary_plane;
14192         } else if (INTEL_INFO(dev)->gen >= 4) {
14193                 intel_primary_formats = i965_primary_formats;
14194                 num_formats = ARRAY_SIZE(i965_primary_formats);
14195
14196                 primary->update_plane = i9xx_update_primary_plane;
14197                 primary->disable_plane = i9xx_disable_primary_plane;
14198         } else {
14199                 intel_primary_formats = i8xx_primary_formats;
14200                 num_formats = ARRAY_SIZE(i8xx_primary_formats);
14201
14202                 primary->update_plane = i9xx_update_primary_plane;
14203                 primary->disable_plane = i9xx_disable_primary_plane;
14204         }
14205
14206         if (INTEL_INFO(dev)->gen >= 9)
14207                 ret = drm_universal_plane_init(dev, &primary->base, 0,
14208                                                &intel_plane_funcs,
14209                                                intel_primary_formats, num_formats,
14210                                                DRM_PLANE_TYPE_PRIMARY,
14211                                                "plane 1%c", pipe_name(pipe));
14212         else if (INTEL_INFO(dev)->gen >= 5 || IS_G4X(dev))
14213                 ret = drm_universal_plane_init(dev, &primary->base, 0,
14214                                                &intel_plane_funcs,
14215                                                intel_primary_formats, num_formats,
14216                                                DRM_PLANE_TYPE_PRIMARY,
14217                                                "primary %c", pipe_name(pipe));
14218         else
14219                 ret = drm_universal_plane_init(dev, &primary->base, 0,
14220                                                &intel_plane_funcs,
14221                                                intel_primary_formats, num_formats,
14222                                                DRM_PLANE_TYPE_PRIMARY,
14223                                                "plane %c", plane_name(primary->plane));
14224         if (ret)
14225                 goto fail;
14226
14227         if (INTEL_INFO(dev)->gen >= 4)
14228                 intel_create_rotation_property(dev, primary);
14229
14230         drm_plane_helper_add(&primary->base, &intel_plane_helper_funcs);
14231
14232         return &primary->base;
14233
14234 fail:
14235         kfree(state);
14236         kfree(primary);
14237
14238         return NULL;
14239 }
14240
14241 void intel_create_rotation_property(struct drm_device *dev, struct intel_plane *plane)
14242 {
14243         if (!dev->mode_config.rotation_property) {
14244                 unsigned long flags = BIT(DRM_ROTATE_0) |
14245                         BIT(DRM_ROTATE_180);
14246
14247                 if (INTEL_INFO(dev)->gen >= 9)
14248                         flags |= BIT(DRM_ROTATE_90) | BIT(DRM_ROTATE_270);
14249
14250                 dev->mode_config.rotation_property =
14251                         drm_mode_create_rotation_property(dev, flags);
14252         }
14253         if (dev->mode_config.rotation_property)
14254                 drm_object_attach_property(&plane->base.base,
14255                                 dev->mode_config.rotation_property,
14256                                 plane->base.state->rotation);
14257 }
14258
14259 static int
14260 intel_check_cursor_plane(struct drm_plane *plane,
14261                          struct intel_crtc_state *crtc_state,
14262                          struct intel_plane_state *state)
14263 {
14264         struct drm_crtc *crtc = crtc_state->base.crtc;
14265         struct drm_framebuffer *fb = state->base.fb;
14266         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
14267         enum pipe pipe = to_intel_plane(plane)->pipe;
14268         unsigned stride;
14269         int ret;
14270
14271         ret = drm_plane_helper_check_update(plane, crtc, fb, &state->src,
14272                                             &state->dst, &state->clip,
14273                                             DRM_PLANE_HELPER_NO_SCALING,
14274                                             DRM_PLANE_HELPER_NO_SCALING,
14275                                             true, true, &state->visible);
14276         if (ret)
14277                 return ret;
14278
14279         /* if we want to turn off the cursor ignore width and height */
14280         if (!obj)
14281                 return 0;
14282
14283         /* Check for which cursor types we support */
14284         if (!cursor_size_ok(plane->dev, state->base.crtc_w, state->base.crtc_h)) {
14285                 DRM_DEBUG("Cursor dimension %dx%d not supported\n",
14286                           state->base.crtc_w, state->base.crtc_h);
14287                 return -EINVAL;
14288         }
14289
14290         stride = roundup_pow_of_two(state->base.crtc_w) * 4;
14291         if (obj->base.size < stride * state->base.crtc_h) {
14292                 DRM_DEBUG_KMS("buffer is too small\n");
14293                 return -ENOMEM;
14294         }
14295
14296         if (fb->modifier[0] != DRM_FORMAT_MOD_NONE) {
14297                 DRM_DEBUG_KMS("cursor cannot be tiled\n");
14298                 return -EINVAL;
14299         }
14300
14301         /*
14302          * There's something wrong with the cursor on CHV pipe C.
14303          * If it straddles the left edge of the screen then
14304          * moving it away from the edge or disabling it often
14305          * results in a pipe underrun, and often that can lead to
14306          * dead pipe (constant underrun reported, and it scans
14307          * out just a solid color). To recover from that, the
14308          * display power well must be turned off and on again.
14309          * Refuse the put the cursor into that compromised position.
14310          */
14311         if (IS_CHERRYVIEW(plane->dev) && pipe == PIPE_C &&
14312             state->visible && state->base.crtc_x < 0) {
14313                 DRM_DEBUG_KMS("CHV cursor C not allowed to straddle the left screen edge\n");
14314                 return -EINVAL;
14315         }
14316
14317         return 0;
14318 }
14319
14320 static void
14321 intel_disable_cursor_plane(struct drm_plane *plane,
14322                            struct drm_crtc *crtc)
14323 {
14324         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
14325
14326         intel_crtc->cursor_addr = 0;
14327         intel_crtc_update_cursor(crtc, NULL);
14328 }
14329
14330 static void
14331 intel_update_cursor_plane(struct drm_plane *plane,
14332                           const struct intel_crtc_state *crtc_state,
14333                           const struct intel_plane_state *state)
14334 {
14335         struct drm_crtc *crtc = crtc_state->base.crtc;
14336         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
14337         struct drm_device *dev = plane->dev;
14338         struct drm_i915_gem_object *obj = intel_fb_obj(state->base.fb);
14339         uint32_t addr;
14340
14341         if (!obj)
14342                 addr = 0;
14343         else if (!INTEL_INFO(dev)->cursor_needs_physical)
14344                 addr = i915_gem_obj_ggtt_offset(obj);
14345         else
14346                 addr = obj->phys_handle->busaddr;
14347
14348         intel_crtc->cursor_addr = addr;
14349         intel_crtc_update_cursor(crtc, state);
14350 }
14351
14352 static struct drm_plane *intel_cursor_plane_create(struct drm_device *dev,
14353                                                    int pipe)
14354 {
14355         struct intel_plane *cursor = NULL;
14356         struct intel_plane_state *state = NULL;
14357         int ret;
14358
14359         cursor = kzalloc(sizeof(*cursor), GFP_KERNEL);
14360         if (!cursor)
14361                 goto fail;
14362
14363         state = intel_create_plane_state(&cursor->base);
14364         if (!state)
14365                 goto fail;
14366         cursor->base.state = &state->base;
14367
14368         cursor->can_scale = false;
14369         cursor->max_downscale = 1;
14370         cursor->pipe = pipe;
14371         cursor->plane = pipe;
14372         cursor->frontbuffer_bit = INTEL_FRONTBUFFER_CURSOR(pipe);
14373         cursor->check_plane = intel_check_cursor_plane;
14374         cursor->update_plane = intel_update_cursor_plane;
14375         cursor->disable_plane = intel_disable_cursor_plane;
14376
14377         ret = drm_universal_plane_init(dev, &cursor->base, 0,
14378                                        &intel_plane_funcs,
14379                                        intel_cursor_formats,
14380                                        ARRAY_SIZE(intel_cursor_formats),
14381                                        DRM_PLANE_TYPE_CURSOR,
14382                                        "cursor %c", pipe_name(pipe));
14383         if (ret)
14384                 goto fail;
14385
14386         if (INTEL_INFO(dev)->gen >= 4) {
14387                 if (!dev->mode_config.rotation_property)
14388                         dev->mode_config.rotation_property =
14389                                 drm_mode_create_rotation_property(dev,
14390                                                         BIT(DRM_ROTATE_0) |
14391                                                         BIT(DRM_ROTATE_180));
14392                 if (dev->mode_config.rotation_property)
14393                         drm_object_attach_property(&cursor->base.base,
14394                                 dev->mode_config.rotation_property,
14395                                 state->base.rotation);
14396         }
14397
14398         if (INTEL_INFO(dev)->gen >=9)
14399                 state->scaler_id = -1;
14400
14401         drm_plane_helper_add(&cursor->base, &intel_plane_helper_funcs);
14402
14403         return &cursor->base;
14404
14405 fail:
14406         kfree(state);
14407         kfree(cursor);
14408
14409         return NULL;
14410 }
14411
14412 static void skl_init_scalers(struct drm_device *dev, struct intel_crtc *intel_crtc,
14413         struct intel_crtc_state *crtc_state)
14414 {
14415         int i;
14416         struct intel_scaler *intel_scaler;
14417         struct intel_crtc_scaler_state *scaler_state = &crtc_state->scaler_state;
14418
14419         for (i = 0; i < intel_crtc->num_scalers; i++) {
14420                 intel_scaler = &scaler_state->scalers[i];
14421                 intel_scaler->in_use = 0;
14422                 intel_scaler->mode = PS_SCALER_MODE_DYN;
14423         }
14424
14425         scaler_state->scaler_id = -1;
14426 }
14427
14428 static void intel_crtc_init(struct drm_device *dev, int pipe)
14429 {
14430         struct drm_i915_private *dev_priv = dev->dev_private;
14431         struct intel_crtc *intel_crtc;
14432         struct intel_crtc_state *crtc_state = NULL;
14433         struct drm_plane *primary = NULL;
14434         struct drm_plane *cursor = NULL;
14435         int ret;
14436
14437         intel_crtc = kzalloc(sizeof(*intel_crtc), GFP_KERNEL);
14438         if (intel_crtc == NULL)
14439                 return;
14440
14441         crtc_state = kzalloc(sizeof(*crtc_state), GFP_KERNEL);
14442         if (!crtc_state)
14443                 goto fail;
14444         intel_crtc->config = crtc_state;
14445         intel_crtc->base.state = &crtc_state->base;
14446         crtc_state->base.crtc = &intel_crtc->base;
14447
14448         /* initialize shared scalers */
14449         if (INTEL_INFO(dev)->gen >= 9) {
14450                 if (pipe == PIPE_C)
14451                         intel_crtc->num_scalers = 1;
14452                 else
14453                         intel_crtc->num_scalers = SKL_NUM_SCALERS;
14454
14455                 skl_init_scalers(dev, intel_crtc, crtc_state);
14456         }
14457
14458         primary = intel_primary_plane_create(dev, pipe);
14459         if (!primary)
14460                 goto fail;
14461
14462         cursor = intel_cursor_plane_create(dev, pipe);
14463         if (!cursor)
14464                 goto fail;
14465
14466         ret = drm_crtc_init_with_planes(dev, &intel_crtc->base, primary,
14467                                         cursor, &intel_crtc_funcs,
14468                                         "pipe %c", pipe_name(pipe));
14469         if (ret)
14470                 goto fail;
14471
14472         /*
14473          * On gen2/3 only plane A can do fbc, but the panel fitter and lvds port
14474          * is hooked to pipe B. Hence we want plane A feeding pipe B.
14475          */
14476         intel_crtc->pipe = pipe;
14477         intel_crtc->plane = pipe;
14478         if (HAS_FBC(dev) && INTEL_INFO(dev)->gen < 4) {
14479                 DRM_DEBUG_KMS("swapping pipes & planes for FBC\n");
14480                 intel_crtc->plane = !pipe;
14481         }
14482
14483         intel_crtc->cursor_base = ~0;
14484         intel_crtc->cursor_cntl = ~0;
14485         intel_crtc->cursor_size = ~0;
14486
14487         intel_crtc->wm.cxsr_allowed = true;
14488
14489         BUG_ON(pipe >= ARRAY_SIZE(dev_priv->plane_to_crtc_mapping) ||
14490                dev_priv->plane_to_crtc_mapping[intel_crtc->plane] != NULL);
14491         dev_priv->plane_to_crtc_mapping[intel_crtc->plane] = &intel_crtc->base;
14492         dev_priv->pipe_to_crtc_mapping[intel_crtc->pipe] = &intel_crtc->base;
14493
14494         drm_crtc_helper_add(&intel_crtc->base, &intel_helper_funcs);
14495
14496         intel_color_init(&intel_crtc->base);
14497
14498         WARN_ON(drm_crtc_index(&intel_crtc->base) != intel_crtc->pipe);
14499         return;
14500
14501 fail:
14502         intel_plane_destroy(primary);
14503         intel_plane_destroy(cursor);
14504         kfree(crtc_state);
14505         kfree(intel_crtc);
14506 }
14507
14508 enum pipe intel_get_pipe_from_connector(struct intel_connector *connector)
14509 {
14510         struct drm_encoder *encoder = connector->base.encoder;
14511         struct drm_device *dev = connector->base.dev;
14512
14513         WARN_ON(!drm_modeset_is_locked(&dev->mode_config.connection_mutex));
14514
14515         if (!encoder || WARN_ON(!encoder->crtc))
14516                 return INVALID_PIPE;
14517
14518         return to_intel_crtc(encoder->crtc)->pipe;
14519 }
14520
14521 int intel_get_pipe_from_crtc_id(struct drm_device *dev, void *data,
14522                                 struct drm_file *file)
14523 {
14524         struct drm_i915_get_pipe_from_crtc_id *pipe_from_crtc_id = data;
14525         struct drm_crtc *drmmode_crtc;
14526         struct intel_crtc *crtc;
14527
14528         drmmode_crtc = drm_crtc_find(dev, pipe_from_crtc_id->crtc_id);
14529
14530         if (!drmmode_crtc) {
14531                 DRM_ERROR("no such CRTC id\n");
14532                 return -ENOENT;
14533         }
14534
14535         crtc = to_intel_crtc(drmmode_crtc);
14536         pipe_from_crtc_id->pipe = crtc->pipe;
14537
14538         return 0;
14539 }
14540
14541 static int intel_encoder_clones(struct intel_encoder *encoder)
14542 {
14543         struct drm_device *dev = encoder->base.dev;
14544         struct intel_encoder *source_encoder;
14545         int index_mask = 0;
14546         int entry = 0;
14547
14548         for_each_intel_encoder(dev, source_encoder) {
14549                 if (encoders_cloneable(encoder, source_encoder))
14550                         index_mask |= (1 << entry);
14551
14552                 entry++;
14553         }
14554
14555         return index_mask;
14556 }
14557
14558 static bool has_edp_a(struct drm_device *dev)
14559 {
14560         struct drm_i915_private *dev_priv = dev->dev_private;
14561
14562         if (!IS_MOBILE(dev))
14563                 return false;
14564
14565         if ((I915_READ(DP_A) & DP_DETECTED) == 0)
14566                 return false;
14567
14568         if (IS_GEN5(dev) && (I915_READ(FUSE_STRAP) & ILK_eDP_A_DISABLE))
14569                 return false;
14570
14571         return true;
14572 }
14573
14574 static bool intel_crt_present(struct drm_device *dev)
14575 {
14576         struct drm_i915_private *dev_priv = dev->dev_private;
14577
14578         if (INTEL_INFO(dev)->gen >= 9)
14579                 return false;
14580
14581         if (IS_HSW_ULT(dev) || IS_BDW_ULT(dev))
14582                 return false;
14583
14584         if (IS_CHERRYVIEW(dev))
14585                 return false;
14586
14587         if (HAS_PCH_LPT_H(dev) && I915_READ(SFUSE_STRAP) & SFUSE_STRAP_CRT_DISABLED)
14588                 return false;
14589
14590         /* DDI E can't be used if DDI A requires 4 lanes */
14591         if (HAS_DDI(dev) && I915_READ(DDI_BUF_CTL(PORT_A)) & DDI_A_4_LANES)
14592                 return false;
14593
14594         if (!dev_priv->vbt.int_crt_support)
14595                 return false;
14596
14597         return true;
14598 }
14599
14600 static void intel_setup_outputs(struct drm_device *dev)
14601 {
14602         struct drm_i915_private *dev_priv = dev->dev_private;
14603         struct intel_encoder *encoder;
14604         bool dpd_is_edp = false;
14605
14606         intel_lvds_init(dev);
14607
14608         if (intel_crt_present(dev))
14609                 intel_crt_init(dev);
14610
14611         if (IS_BROXTON(dev)) {
14612                 /*
14613                  * FIXME: Broxton doesn't support port detection via the
14614                  * DDI_BUF_CTL_A or SFUSE_STRAP registers, find another way to
14615                  * detect the ports.
14616                  */
14617                 intel_ddi_init(dev, PORT_A);
14618                 intel_ddi_init(dev, PORT_B);
14619                 intel_ddi_init(dev, PORT_C);
14620
14621                 intel_dsi_init(dev);
14622         } else if (HAS_DDI(dev)) {
14623                 int found;
14624
14625                 /*
14626                  * Haswell uses DDI functions to detect digital outputs.
14627                  * On SKL pre-D0 the strap isn't connected, so we assume
14628                  * it's there.
14629                  */
14630                 found = I915_READ(DDI_BUF_CTL(PORT_A)) & DDI_INIT_DISPLAY_DETECTED;
14631                 /* WaIgnoreDDIAStrap: skl */
14632                 if (found || IS_SKYLAKE(dev) || IS_KABYLAKE(dev))
14633                         intel_ddi_init(dev, PORT_A);
14634
14635                 /* DDI B, C and D detection is indicated by the SFUSE_STRAP
14636                  * register */
14637                 found = I915_READ(SFUSE_STRAP);
14638
14639                 if (found & SFUSE_STRAP_DDIB_DETECTED)
14640                         intel_ddi_init(dev, PORT_B);
14641                 if (found & SFUSE_STRAP_DDIC_DETECTED)
14642                         intel_ddi_init(dev, PORT_C);
14643                 if (found & SFUSE_STRAP_DDID_DETECTED)
14644                         intel_ddi_init(dev, PORT_D);
14645                 /*
14646                  * On SKL we don't have a way to detect DDI-E so we rely on VBT.
14647                  */
14648                 if ((IS_SKYLAKE(dev) || IS_KABYLAKE(dev)) &&
14649                     (dev_priv->vbt.ddi_port_info[PORT_E].supports_dp ||
14650                      dev_priv->vbt.ddi_port_info[PORT_E].supports_dvi ||
14651                      dev_priv->vbt.ddi_port_info[PORT_E].supports_hdmi))
14652                         intel_ddi_init(dev, PORT_E);
14653
14654         } else if (HAS_PCH_SPLIT(dev)) {
14655                 int found;
14656                 dpd_is_edp = intel_dp_is_edp(dev, PORT_D);
14657
14658                 if (has_edp_a(dev))
14659                         intel_dp_init(dev, DP_A, PORT_A);
14660
14661                 if (I915_READ(PCH_HDMIB) & SDVO_DETECTED) {
14662                         /* PCH SDVOB multiplex with HDMIB */
14663                         found = intel_sdvo_init(dev, PCH_SDVOB, PORT_B);
14664                         if (!found)
14665                                 intel_hdmi_init(dev, PCH_HDMIB, PORT_B);
14666                         if (!found && (I915_READ(PCH_DP_B) & DP_DETECTED))
14667                                 intel_dp_init(dev, PCH_DP_B, PORT_B);
14668                 }
14669
14670                 if (I915_READ(PCH_HDMIC) & SDVO_DETECTED)
14671                         intel_hdmi_init(dev, PCH_HDMIC, PORT_C);
14672
14673                 if (!dpd_is_edp && I915_READ(PCH_HDMID) & SDVO_DETECTED)
14674                         intel_hdmi_init(dev, PCH_HDMID, PORT_D);
14675
14676                 if (I915_READ(PCH_DP_C) & DP_DETECTED)
14677                         intel_dp_init(dev, PCH_DP_C, PORT_C);
14678
14679                 if (I915_READ(PCH_DP_D) & DP_DETECTED)
14680                         intel_dp_init(dev, PCH_DP_D, PORT_D);
14681         } else if (IS_VALLEYVIEW(dev) || IS_CHERRYVIEW(dev)) {
14682                 bool has_edp, has_port;
14683
14684                 /*
14685                  * The DP_DETECTED bit is the latched state of the DDC
14686                  * SDA pin at boot. However since eDP doesn't require DDC
14687                  * (no way to plug in a DP->HDMI dongle) the DDC pins for
14688                  * eDP ports may have been muxed to an alternate function.
14689                  * Thus we can't rely on the DP_DETECTED bit alone to detect
14690                  * eDP ports. Consult the VBT as well as DP_DETECTED to
14691                  * detect eDP ports.
14692                  *
14693                  * Sadly the straps seem to be missing sometimes even for HDMI
14694                  * ports (eg. on Voyo V3 - CHT x7-Z8700), so check both strap
14695                  * and VBT for the presence of the port. Additionally we can't
14696                  * trust the port type the VBT declares as we've seen at least
14697                  * HDMI ports that the VBT claim are DP or eDP.
14698                  */
14699                 has_edp = intel_dp_is_edp(dev, PORT_B);
14700                 has_port = intel_bios_is_port_present(dev_priv, PORT_B);
14701                 if (I915_READ(VLV_DP_B) & DP_DETECTED || has_port)
14702                         has_edp &= intel_dp_init(dev, VLV_DP_B, PORT_B);
14703                 if ((I915_READ(VLV_HDMIB) & SDVO_DETECTED || has_port) && !has_edp)
14704                         intel_hdmi_init(dev, VLV_HDMIB, PORT_B);
14705
14706                 has_edp = intel_dp_is_edp(dev, PORT_C);
14707                 has_port = intel_bios_is_port_present(dev_priv, PORT_C);
14708                 if (I915_READ(VLV_DP_C) & DP_DETECTED || has_port)
14709                         has_edp &= intel_dp_init(dev, VLV_DP_C, PORT_C);
14710                 if ((I915_READ(VLV_HDMIC) & SDVO_DETECTED || has_port) && !has_edp)
14711                         intel_hdmi_init(dev, VLV_HDMIC, PORT_C);
14712
14713                 if (IS_CHERRYVIEW(dev)) {
14714                         /*
14715                          * eDP not supported on port D,
14716                          * so no need to worry about it
14717                          */
14718                         has_port = intel_bios_is_port_present(dev_priv, PORT_D);
14719                         if (I915_READ(CHV_DP_D) & DP_DETECTED || has_port)
14720                                 intel_dp_init(dev, CHV_DP_D, PORT_D);
14721                         if (I915_READ(CHV_HDMID) & SDVO_DETECTED || has_port)
14722                                 intel_hdmi_init(dev, CHV_HDMID, PORT_D);
14723                 }
14724
14725                 intel_dsi_init(dev);
14726         } else if (!IS_GEN2(dev) && !IS_PINEVIEW(dev)) {
14727                 bool found = false;
14728
14729                 if (I915_READ(GEN3_SDVOB) & SDVO_DETECTED) {
14730                         DRM_DEBUG_KMS("probing SDVOB\n");
14731                         found = intel_sdvo_init(dev, GEN3_SDVOB, PORT_B);
14732                         if (!found && IS_G4X(dev)) {
14733                                 DRM_DEBUG_KMS("probing HDMI on SDVOB\n");
14734                                 intel_hdmi_init(dev, GEN4_HDMIB, PORT_B);
14735                         }
14736
14737                         if (!found && IS_G4X(dev))
14738                                 intel_dp_init(dev, DP_B, PORT_B);
14739                 }
14740
14741                 /* Before G4X SDVOC doesn't have its own detect register */
14742
14743                 if (I915_READ(GEN3_SDVOB) & SDVO_DETECTED) {
14744                         DRM_DEBUG_KMS("probing SDVOC\n");
14745                         found = intel_sdvo_init(dev, GEN3_SDVOC, PORT_C);
14746                 }
14747
14748                 if (!found && (I915_READ(GEN3_SDVOC) & SDVO_DETECTED)) {
14749
14750                         if (IS_G4X(dev)) {
14751                                 DRM_DEBUG_KMS("probing HDMI on SDVOC\n");
14752                                 intel_hdmi_init(dev, GEN4_HDMIC, PORT_C);
14753                         }
14754                         if (IS_G4X(dev))
14755                                 intel_dp_init(dev, DP_C, PORT_C);
14756                 }
14757
14758                 if (IS_G4X(dev) &&
14759                     (I915_READ(DP_D) & DP_DETECTED))
14760                         intel_dp_init(dev, DP_D, PORT_D);
14761         } else if (IS_GEN2(dev))
14762                 intel_dvo_init(dev);
14763
14764         if (SUPPORTS_TV(dev))
14765                 intel_tv_init(dev);
14766
14767         intel_psr_init(dev);
14768
14769         for_each_intel_encoder(dev, encoder) {
14770                 encoder->base.possible_crtcs = encoder->crtc_mask;
14771                 encoder->base.possible_clones =
14772                         intel_encoder_clones(encoder);
14773         }
14774
14775         intel_init_pch_refclk(dev);
14776
14777         drm_helper_move_panel_connectors_to_head(dev);
14778 }
14779
14780 static void intel_user_framebuffer_destroy(struct drm_framebuffer *fb)
14781 {
14782         struct drm_device *dev = fb->dev;
14783         struct intel_framebuffer *intel_fb = to_intel_framebuffer(fb);
14784
14785         drm_framebuffer_cleanup(fb);
14786         mutex_lock(&dev->struct_mutex);
14787         WARN_ON(!intel_fb->obj->framebuffer_references--);
14788         drm_gem_object_unreference(&intel_fb->obj->base);
14789         mutex_unlock(&dev->struct_mutex);
14790         kfree(intel_fb);
14791 }
14792
14793 static int intel_user_framebuffer_create_handle(struct drm_framebuffer *fb,
14794                                                 struct drm_file *file,
14795                                                 unsigned int *handle)
14796 {
14797         struct intel_framebuffer *intel_fb = to_intel_framebuffer(fb);
14798         struct drm_i915_gem_object *obj = intel_fb->obj;
14799
14800         if (obj->userptr.mm) {
14801                 DRM_DEBUG("attempting to use a userptr for a framebuffer, denied\n");
14802                 return -EINVAL;
14803         }
14804
14805         return drm_gem_handle_create(file, &obj->base, handle);
14806 }
14807
14808 static int intel_user_framebuffer_dirty(struct drm_framebuffer *fb,
14809                                         struct drm_file *file,
14810                                         unsigned flags, unsigned color,
14811                                         struct drm_clip_rect *clips,
14812                                         unsigned num_clips)
14813 {
14814         struct drm_device *dev = fb->dev;
14815         struct intel_framebuffer *intel_fb = to_intel_framebuffer(fb);
14816         struct drm_i915_gem_object *obj = intel_fb->obj;
14817
14818         mutex_lock(&dev->struct_mutex);
14819         intel_fb_obj_flush(obj, false, ORIGIN_DIRTYFB);
14820         mutex_unlock(&dev->struct_mutex);
14821
14822         return 0;
14823 }
14824
14825 static const struct drm_framebuffer_funcs intel_fb_funcs = {
14826         .destroy = intel_user_framebuffer_destroy,
14827         .create_handle = intel_user_framebuffer_create_handle,
14828         .dirty = intel_user_framebuffer_dirty,
14829 };
14830
14831 static
14832 u32 intel_fb_pitch_limit(struct drm_device *dev, uint64_t fb_modifier,
14833                          uint32_t pixel_format)
14834 {
14835         u32 gen = INTEL_INFO(dev)->gen;
14836
14837         if (gen >= 9) {
14838                 int cpp = drm_format_plane_cpp(pixel_format, 0);
14839
14840                 /* "The stride in bytes must not exceed the of the size of 8K
14841                  *  pixels and 32K bytes."
14842                  */
14843                 return min(8192 * cpp, 32768);
14844         } else if (gen >= 5 && !IS_VALLEYVIEW(dev) && !IS_CHERRYVIEW(dev)) {
14845                 return 32*1024;
14846         } else if (gen >= 4) {
14847                 if (fb_modifier == I915_FORMAT_MOD_X_TILED)
14848                         return 16*1024;
14849                 else
14850                         return 32*1024;
14851         } else if (gen >= 3) {
14852                 if (fb_modifier == I915_FORMAT_MOD_X_TILED)
14853                         return 8*1024;
14854                 else
14855                         return 16*1024;
14856         } else {
14857                 /* XXX DSPC is limited to 4k tiled */
14858                 return 8*1024;
14859         }
14860 }
14861
14862 static int intel_framebuffer_init(struct drm_device *dev,
14863                                   struct intel_framebuffer *intel_fb,
14864                                   struct drm_mode_fb_cmd2 *mode_cmd,
14865                                   struct drm_i915_gem_object *obj)
14866 {
14867         struct drm_i915_private *dev_priv = to_i915(dev);
14868         unsigned int aligned_height;
14869         int ret;
14870         u32 pitch_limit, stride_alignment;
14871
14872         WARN_ON(!mutex_is_locked(&dev->struct_mutex));
14873
14874         if (mode_cmd->flags & DRM_MODE_FB_MODIFIERS) {
14875                 /* Enforce that fb modifier and tiling mode match, but only for
14876                  * X-tiled. This is needed for FBC. */
14877                 if (!!(obj->tiling_mode == I915_TILING_X) !=
14878                     !!(mode_cmd->modifier[0] == I915_FORMAT_MOD_X_TILED)) {
14879                         DRM_DEBUG("tiling_mode doesn't match fb modifier\n");
14880                         return -EINVAL;
14881                 }
14882         } else {
14883                 if (obj->tiling_mode == I915_TILING_X)
14884                         mode_cmd->modifier[0] = I915_FORMAT_MOD_X_TILED;
14885                 else if (obj->tiling_mode == I915_TILING_Y) {
14886                         DRM_DEBUG("No Y tiling for legacy addfb\n");
14887                         return -EINVAL;
14888                 }
14889         }
14890
14891         /* Passed in modifier sanity checking. */
14892         switch (mode_cmd->modifier[0]) {
14893         case I915_FORMAT_MOD_Y_TILED:
14894         case I915_FORMAT_MOD_Yf_TILED:
14895                 if (INTEL_INFO(dev)->gen < 9) {
14896                         DRM_DEBUG("Unsupported tiling 0x%llx!\n",
14897                                   mode_cmd->modifier[0]);
14898                         return -EINVAL;
14899                 }
14900         case DRM_FORMAT_MOD_NONE:
14901         case I915_FORMAT_MOD_X_TILED:
14902                 break;
14903         default:
14904                 DRM_DEBUG("Unsupported fb modifier 0x%llx!\n",
14905                           mode_cmd->modifier[0]);
14906                 return -EINVAL;
14907         }
14908
14909         stride_alignment = intel_fb_stride_alignment(dev_priv,
14910                                                      mode_cmd->modifier[0],
14911                                                      mode_cmd->pixel_format);
14912         if (mode_cmd->pitches[0] & (stride_alignment - 1)) {
14913                 DRM_DEBUG("pitch (%d) must be at least %u byte aligned\n",
14914                           mode_cmd->pitches[0], stride_alignment);
14915                 return -EINVAL;
14916         }
14917
14918         pitch_limit = intel_fb_pitch_limit(dev, mode_cmd->modifier[0],
14919                                            mode_cmd->pixel_format);
14920         if (mode_cmd->pitches[0] > pitch_limit) {
14921                 DRM_DEBUG("%s pitch (%u) must be at less than %d\n",
14922                           mode_cmd->modifier[0] != DRM_FORMAT_MOD_NONE ?
14923                           "tiled" : "linear",
14924                           mode_cmd->pitches[0], pitch_limit);
14925                 return -EINVAL;
14926         }
14927
14928         if (mode_cmd->modifier[0] == I915_FORMAT_MOD_X_TILED &&
14929             mode_cmd->pitches[0] != obj->stride) {
14930                 DRM_DEBUG("pitch (%d) must match tiling stride (%d)\n",
14931                           mode_cmd->pitches[0], obj->stride);
14932                 return -EINVAL;
14933         }
14934
14935         /* Reject formats not supported by any plane early. */
14936         switch (mode_cmd->pixel_format) {
14937         case DRM_FORMAT_C8:
14938         case DRM_FORMAT_RGB565:
14939         case DRM_FORMAT_XRGB8888:
14940         case DRM_FORMAT_ARGB8888:
14941                 break;
14942         case DRM_FORMAT_XRGB1555:
14943                 if (INTEL_INFO(dev)->gen > 3) {
14944                         DRM_DEBUG("unsupported pixel format: %s\n",
14945                                   drm_get_format_name(mode_cmd->pixel_format));
14946                         return -EINVAL;
14947                 }
14948                 break;
14949         case DRM_FORMAT_ABGR8888:
14950                 if (!IS_VALLEYVIEW(dev) && !IS_CHERRYVIEW(dev) &&
14951                     INTEL_INFO(dev)->gen < 9) {
14952                         DRM_DEBUG("unsupported pixel format: %s\n",
14953                                   drm_get_format_name(mode_cmd->pixel_format));
14954                         return -EINVAL;
14955                 }
14956                 break;
14957         case DRM_FORMAT_XBGR8888:
14958         case DRM_FORMAT_XRGB2101010:
14959         case DRM_FORMAT_XBGR2101010:
14960                 if (INTEL_INFO(dev)->gen < 4) {
14961                         DRM_DEBUG("unsupported pixel format: %s\n",
14962                                   drm_get_format_name(mode_cmd->pixel_format));
14963                         return -EINVAL;
14964                 }
14965                 break;
14966         case DRM_FORMAT_ABGR2101010:
14967                 if (!IS_VALLEYVIEW(dev) && !IS_CHERRYVIEW(dev)) {
14968                         DRM_DEBUG("unsupported pixel format: %s\n",
14969                                   drm_get_format_name(mode_cmd->pixel_format));
14970                         return -EINVAL;
14971                 }
14972                 break;
14973         case DRM_FORMAT_YUYV:
14974         case DRM_FORMAT_UYVY:
14975         case DRM_FORMAT_YVYU:
14976         case DRM_FORMAT_VYUY:
14977                 if (INTEL_INFO(dev)->gen < 5) {
14978                         DRM_DEBUG("unsupported pixel format: %s\n",
14979                                   drm_get_format_name(mode_cmd->pixel_format));
14980                         return -EINVAL;
14981                 }
14982                 break;
14983         default:
14984                 DRM_DEBUG("unsupported pixel format: %s\n",
14985                           drm_get_format_name(mode_cmd->pixel_format));
14986                 return -EINVAL;
14987         }
14988
14989         /* FIXME need to adjust LINOFF/TILEOFF accordingly. */
14990         if (mode_cmd->offsets[0] != 0)
14991                 return -EINVAL;
14992
14993         aligned_height = intel_fb_align_height(dev, mode_cmd->height,
14994                                                mode_cmd->pixel_format,
14995                                                mode_cmd->modifier[0]);
14996         /* FIXME drm helper for size checks (especially planar formats)? */
14997         if (obj->base.size < aligned_height * mode_cmd->pitches[0])
14998                 return -EINVAL;
14999
15000         drm_helper_mode_fill_fb_struct(&intel_fb->base, mode_cmd);
15001         intel_fb->obj = obj;
15002
15003         intel_fill_fb_info(dev_priv, &intel_fb->base);
15004
15005         ret = drm_framebuffer_init(dev, &intel_fb->base, &intel_fb_funcs);
15006         if (ret) {
15007                 DRM_ERROR("framebuffer init failed %d\n", ret);
15008                 return ret;
15009         }
15010
15011         intel_fb->obj->framebuffer_references++;
15012
15013         return 0;
15014 }
15015
15016 static struct drm_framebuffer *
15017 intel_user_framebuffer_create(struct drm_device *dev,
15018                               struct drm_file *filp,
15019                               const struct drm_mode_fb_cmd2 *user_mode_cmd)
15020 {
15021         struct drm_framebuffer *fb;
15022         struct drm_i915_gem_object *obj;
15023         struct drm_mode_fb_cmd2 mode_cmd = *user_mode_cmd;
15024
15025         obj = to_intel_bo(drm_gem_object_lookup(filp, mode_cmd.handles[0]));
15026         if (&obj->base == NULL)
15027                 return ERR_PTR(-ENOENT);
15028
15029         fb = intel_framebuffer_create(dev, &mode_cmd, obj);
15030         if (IS_ERR(fb))
15031                 drm_gem_object_unreference_unlocked(&obj->base);
15032
15033         return fb;
15034 }
15035
15036 #ifndef CONFIG_DRM_FBDEV_EMULATION
15037 static inline void intel_fbdev_output_poll_changed(struct drm_device *dev)
15038 {
15039 }
15040 #endif
15041
15042 static const struct drm_mode_config_funcs intel_mode_funcs = {
15043         .fb_create = intel_user_framebuffer_create,
15044         .output_poll_changed = intel_fbdev_output_poll_changed,
15045         .atomic_check = intel_atomic_check,
15046         .atomic_commit = intel_atomic_commit,
15047         .atomic_state_alloc = intel_atomic_state_alloc,
15048         .atomic_state_clear = intel_atomic_state_clear,
15049 };
15050
15051 /**
15052  * intel_init_display_hooks - initialize the display modesetting hooks
15053  * @dev_priv: device private
15054  */
15055 void intel_init_display_hooks(struct drm_i915_private *dev_priv)
15056 {
15057         if (INTEL_INFO(dev_priv)->gen >= 9) {
15058                 dev_priv->display.get_pipe_config = haswell_get_pipe_config;
15059                 dev_priv->display.get_initial_plane_config =
15060                         skylake_get_initial_plane_config;
15061                 dev_priv->display.crtc_compute_clock =
15062                         haswell_crtc_compute_clock;
15063                 dev_priv->display.crtc_enable = haswell_crtc_enable;
15064                 dev_priv->display.crtc_disable = haswell_crtc_disable;
15065         } else if (HAS_DDI(dev_priv)) {
15066                 dev_priv->display.get_pipe_config = haswell_get_pipe_config;
15067                 dev_priv->display.get_initial_plane_config =
15068                         ironlake_get_initial_plane_config;
15069                 dev_priv->display.crtc_compute_clock =
15070                         haswell_crtc_compute_clock;
15071                 dev_priv->display.crtc_enable = haswell_crtc_enable;
15072                 dev_priv->display.crtc_disable = haswell_crtc_disable;
15073         } else if (HAS_PCH_SPLIT(dev_priv)) {
15074                 dev_priv->display.get_pipe_config = ironlake_get_pipe_config;
15075                 dev_priv->display.get_initial_plane_config =
15076                         ironlake_get_initial_plane_config;
15077                 dev_priv->display.crtc_compute_clock =
15078                         ironlake_crtc_compute_clock;
15079                 dev_priv->display.crtc_enable = ironlake_crtc_enable;
15080                 dev_priv->display.crtc_disable = ironlake_crtc_disable;
15081         } else if (IS_CHERRYVIEW(dev_priv)) {
15082                 dev_priv->display.get_pipe_config = i9xx_get_pipe_config;
15083                 dev_priv->display.get_initial_plane_config =
15084                         i9xx_get_initial_plane_config;
15085                 dev_priv->display.crtc_compute_clock = chv_crtc_compute_clock;
15086                 dev_priv->display.crtc_enable = valleyview_crtc_enable;
15087                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
15088         } else if (IS_VALLEYVIEW(dev_priv)) {
15089                 dev_priv->display.get_pipe_config = i9xx_get_pipe_config;
15090                 dev_priv->display.get_initial_plane_config =
15091                         i9xx_get_initial_plane_config;
15092                 dev_priv->display.crtc_compute_clock = vlv_crtc_compute_clock;
15093                 dev_priv->display.crtc_enable = valleyview_crtc_enable;
15094                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
15095         } else if (IS_G4X(dev_priv)) {
15096                 dev_priv->display.get_pipe_config = i9xx_get_pipe_config;
15097                 dev_priv->display.get_initial_plane_config =
15098                         i9xx_get_initial_plane_config;
15099                 dev_priv->display.crtc_compute_clock = g4x_crtc_compute_clock;
15100                 dev_priv->display.crtc_enable = i9xx_crtc_enable;
15101                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
15102         } else if (IS_PINEVIEW(dev_priv)) {
15103                 dev_priv->display.get_pipe_config = i9xx_get_pipe_config;
15104                 dev_priv->display.get_initial_plane_config =
15105                         i9xx_get_initial_plane_config;
15106                 dev_priv->display.crtc_compute_clock = pnv_crtc_compute_clock;
15107                 dev_priv->display.crtc_enable = i9xx_crtc_enable;
15108                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
15109         } else if (!IS_GEN2(dev_priv)) {
15110                 dev_priv->display.get_pipe_config = i9xx_get_pipe_config;
15111                 dev_priv->display.get_initial_plane_config =
15112                         i9xx_get_initial_plane_config;
15113                 dev_priv->display.crtc_compute_clock = i9xx_crtc_compute_clock;
15114                 dev_priv->display.crtc_enable = i9xx_crtc_enable;
15115                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
15116         } else {
15117                 dev_priv->display.get_pipe_config = i9xx_get_pipe_config;
15118                 dev_priv->display.get_initial_plane_config =
15119                         i9xx_get_initial_plane_config;
15120                 dev_priv->display.crtc_compute_clock = i8xx_crtc_compute_clock;
15121                 dev_priv->display.crtc_enable = i9xx_crtc_enable;
15122                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
15123         }
15124
15125         /* Returns the core display clock speed */
15126         if (IS_SKYLAKE(dev_priv) || IS_KABYLAKE(dev_priv))
15127                 dev_priv->display.get_display_clock_speed =
15128                         skylake_get_display_clock_speed;
15129         else if (IS_BROXTON(dev_priv))
15130                 dev_priv->display.get_display_clock_speed =
15131                         broxton_get_display_clock_speed;
15132         else if (IS_BROADWELL(dev_priv))
15133                 dev_priv->display.get_display_clock_speed =
15134                         broadwell_get_display_clock_speed;
15135         else if (IS_HASWELL(dev_priv))
15136                 dev_priv->display.get_display_clock_speed =
15137                         haswell_get_display_clock_speed;
15138         else if (IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv))
15139                 dev_priv->display.get_display_clock_speed =
15140                         valleyview_get_display_clock_speed;
15141         else if (IS_GEN5(dev_priv))
15142                 dev_priv->display.get_display_clock_speed =
15143                         ilk_get_display_clock_speed;
15144         else if (IS_I945G(dev_priv) || IS_BROADWATER(dev_priv) ||
15145                  IS_GEN6(dev_priv) || IS_IVYBRIDGE(dev_priv))
15146                 dev_priv->display.get_display_clock_speed =
15147                         i945_get_display_clock_speed;
15148         else if (IS_GM45(dev_priv))
15149                 dev_priv->display.get_display_clock_speed =
15150                         gm45_get_display_clock_speed;
15151         else if (IS_CRESTLINE(dev_priv))
15152                 dev_priv->display.get_display_clock_speed =
15153                         i965gm_get_display_clock_speed;
15154         else if (IS_PINEVIEW(dev_priv))
15155                 dev_priv->display.get_display_clock_speed =
15156                         pnv_get_display_clock_speed;
15157         else if (IS_G33(dev_priv) || IS_G4X(dev_priv))
15158                 dev_priv->display.get_display_clock_speed =
15159                         g33_get_display_clock_speed;
15160         else if (IS_I915G(dev_priv))
15161                 dev_priv->display.get_display_clock_speed =
15162                         i915_get_display_clock_speed;
15163         else if (IS_I945GM(dev_priv) || IS_845G(dev_priv))
15164                 dev_priv->display.get_display_clock_speed =
15165                         i9xx_misc_get_display_clock_speed;
15166         else if (IS_I915GM(dev_priv))
15167                 dev_priv->display.get_display_clock_speed =
15168                         i915gm_get_display_clock_speed;
15169         else if (IS_I865G(dev_priv))
15170                 dev_priv->display.get_display_clock_speed =
15171                         i865_get_display_clock_speed;
15172         else if (IS_I85X(dev_priv))
15173                 dev_priv->display.get_display_clock_speed =
15174                         i85x_get_display_clock_speed;
15175         else { /* 830 */
15176                 WARN(!IS_I830(dev_priv), "Unknown platform. Assuming 133 MHz CDCLK\n");
15177                 dev_priv->display.get_display_clock_speed =
15178                         i830_get_display_clock_speed;
15179         }
15180
15181         if (IS_GEN5(dev_priv)) {
15182                 dev_priv->display.fdi_link_train = ironlake_fdi_link_train;
15183         } else if (IS_GEN6(dev_priv)) {
15184                 dev_priv->display.fdi_link_train = gen6_fdi_link_train;
15185         } else if (IS_IVYBRIDGE(dev_priv)) {
15186                 /* FIXME: detect B0+ stepping and use auto training */
15187                 dev_priv->display.fdi_link_train = ivb_manual_fdi_link_train;
15188         } else if (IS_HASWELL(dev_priv) || IS_BROADWELL(dev_priv)) {
15189                 dev_priv->display.fdi_link_train = hsw_fdi_link_train;
15190         }
15191
15192         if (IS_BROADWELL(dev_priv)) {
15193                 dev_priv->display.modeset_commit_cdclk =
15194                         broadwell_modeset_commit_cdclk;
15195                 dev_priv->display.modeset_calc_cdclk =
15196                         broadwell_modeset_calc_cdclk;
15197         } else if (IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv)) {
15198                 dev_priv->display.modeset_commit_cdclk =
15199                         valleyview_modeset_commit_cdclk;
15200                 dev_priv->display.modeset_calc_cdclk =
15201                         valleyview_modeset_calc_cdclk;
15202         } else if (IS_BROXTON(dev_priv)) {
15203                 dev_priv->display.modeset_commit_cdclk =
15204                         broxton_modeset_commit_cdclk;
15205                 dev_priv->display.modeset_calc_cdclk =
15206                         broxton_modeset_calc_cdclk;
15207         } else if (IS_SKYLAKE(dev_priv) || IS_KABYLAKE(dev_priv)) {
15208                 dev_priv->display.modeset_commit_cdclk =
15209                         skl_modeset_commit_cdclk;
15210                 dev_priv->display.modeset_calc_cdclk =
15211                         skl_modeset_calc_cdclk;
15212         }
15213
15214         switch (INTEL_INFO(dev_priv)->gen) {
15215         case 2:
15216                 dev_priv->display.queue_flip = intel_gen2_queue_flip;
15217                 break;
15218
15219         case 3:
15220                 dev_priv->display.queue_flip = intel_gen3_queue_flip;
15221                 break;
15222
15223         case 4:
15224         case 5:
15225                 dev_priv->display.queue_flip = intel_gen4_queue_flip;
15226                 break;
15227
15228         case 6:
15229                 dev_priv->display.queue_flip = intel_gen6_queue_flip;
15230                 break;
15231         case 7:
15232         case 8: /* FIXME(BDW): Check that the gen8 RCS flip works. */
15233                 dev_priv->display.queue_flip = intel_gen7_queue_flip;
15234                 break;
15235         case 9:
15236                 /* Drop through - unsupported since execlist only. */
15237         default:
15238                 /* Default just returns -ENODEV to indicate unsupported */
15239                 dev_priv->display.queue_flip = intel_default_queue_flip;
15240         }
15241 }
15242
15243 /*
15244  * Some BIOSes insist on assuming the GPU's pipe A is enabled at suspend,
15245  * resume, or other times.  This quirk makes sure that's the case for
15246  * affected systems.
15247  */
15248 static void quirk_pipea_force(struct drm_device *dev)
15249 {
15250         struct drm_i915_private *dev_priv = dev->dev_private;
15251
15252         dev_priv->quirks |= QUIRK_PIPEA_FORCE;
15253         DRM_INFO("applying pipe a force quirk\n");
15254 }
15255
15256 static void quirk_pipeb_force(struct drm_device *dev)
15257 {
15258         struct drm_i915_private *dev_priv = dev->dev_private;
15259
15260         dev_priv->quirks |= QUIRK_PIPEB_FORCE;
15261         DRM_INFO("applying pipe b force quirk\n");
15262 }
15263
15264 /*
15265  * Some machines (Lenovo U160) do not work with SSC on LVDS for some reason
15266  */
15267 static void quirk_ssc_force_disable(struct drm_device *dev)
15268 {
15269         struct drm_i915_private *dev_priv = dev->dev_private;
15270         dev_priv->quirks |= QUIRK_LVDS_SSC_DISABLE;
15271         DRM_INFO("applying lvds SSC disable quirk\n");
15272 }
15273
15274 /*
15275  * A machine (e.g. Acer Aspire 5734Z) may need to invert the panel backlight
15276  * brightness value
15277  */
15278 static void quirk_invert_brightness(struct drm_device *dev)
15279 {
15280         struct drm_i915_private *dev_priv = dev->dev_private;
15281         dev_priv->quirks |= QUIRK_INVERT_BRIGHTNESS;
15282         DRM_INFO("applying inverted panel brightness quirk\n");
15283 }
15284
15285 /* Some VBT's incorrectly indicate no backlight is present */
15286 static void quirk_backlight_present(struct drm_device *dev)
15287 {
15288         struct drm_i915_private *dev_priv = dev->dev_private;
15289         dev_priv->quirks |= QUIRK_BACKLIGHT_PRESENT;
15290         DRM_INFO("applying backlight present quirk\n");
15291 }
15292
15293 struct intel_quirk {
15294         int device;
15295         int subsystem_vendor;
15296         int subsystem_device;
15297         void (*hook)(struct drm_device *dev);
15298 };
15299
15300 /* For systems that don't have a meaningful PCI subdevice/subvendor ID */
15301 struct intel_dmi_quirk {
15302         void (*hook)(struct drm_device *dev);
15303         const struct dmi_system_id (*dmi_id_list)[];
15304 };
15305
15306 static int intel_dmi_reverse_brightness(const struct dmi_system_id *id)
15307 {
15308         DRM_INFO("Backlight polarity reversed on %s\n", id->ident);
15309         return 1;
15310 }
15311
15312 static const struct intel_dmi_quirk intel_dmi_quirks[] = {
15313         {
15314                 .dmi_id_list = &(const struct dmi_system_id[]) {
15315                         {
15316                                 .callback = intel_dmi_reverse_brightness,
15317                                 .ident = "NCR Corporation",
15318                                 .matches = {DMI_MATCH(DMI_SYS_VENDOR, "NCR Corporation"),
15319                                             DMI_MATCH(DMI_PRODUCT_NAME, ""),
15320                                 },
15321                         },
15322                         { }  /* terminating entry */
15323                 },
15324                 .hook = quirk_invert_brightness,
15325         },
15326 };
15327
15328 static struct intel_quirk intel_quirks[] = {
15329         /* Toshiba Protege R-205, S-209 needs pipe A force quirk */
15330         { 0x2592, 0x1179, 0x0001, quirk_pipea_force },
15331
15332         /* ThinkPad T60 needs pipe A force quirk (bug #16494) */
15333         { 0x2782, 0x17aa, 0x201a, quirk_pipea_force },
15334
15335         /* 830 needs to leave pipe A & dpll A up */
15336         { 0x3577, PCI_ANY_ID, PCI_ANY_ID, quirk_pipea_force },
15337
15338         /* 830 needs to leave pipe B & dpll B up */
15339         { 0x3577, PCI_ANY_ID, PCI_ANY_ID, quirk_pipeb_force },
15340
15341         /* Lenovo U160 cannot use SSC on LVDS */
15342         { 0x0046, 0x17aa, 0x3920, quirk_ssc_force_disable },
15343
15344         /* Sony Vaio Y cannot use SSC on LVDS */
15345         { 0x0046, 0x104d, 0x9076, quirk_ssc_force_disable },
15346
15347         /* Acer Aspire 5734Z must invert backlight brightness */
15348         { 0x2a42, 0x1025, 0x0459, quirk_invert_brightness },
15349
15350         /* Acer/eMachines G725 */
15351         { 0x2a42, 0x1025, 0x0210, quirk_invert_brightness },
15352
15353         /* Acer/eMachines e725 */
15354         { 0x2a42, 0x1025, 0x0212, quirk_invert_brightness },
15355
15356         /* Acer/Packard Bell NCL20 */
15357         { 0x2a42, 0x1025, 0x034b, quirk_invert_brightness },
15358
15359         /* Acer Aspire 4736Z */
15360         { 0x2a42, 0x1025, 0x0260, quirk_invert_brightness },
15361
15362         /* Acer Aspire 5336 */
15363         { 0x2a42, 0x1025, 0x048a, quirk_invert_brightness },
15364
15365         /* Acer C720 and C720P Chromebooks (Celeron 2955U) have backlights */
15366         { 0x0a06, 0x1025, 0x0a11, quirk_backlight_present },
15367
15368         /* Acer C720 Chromebook (Core i3 4005U) */
15369         { 0x0a16, 0x1025, 0x0a11, quirk_backlight_present },
15370
15371         /* Apple Macbook 2,1 (Core 2 T7400) */
15372         { 0x27a2, 0x8086, 0x7270, quirk_backlight_present },
15373
15374         /* Apple Macbook 4,1 */
15375         { 0x2a02, 0x106b, 0x00a1, quirk_backlight_present },
15376
15377         /* Toshiba CB35 Chromebook (Celeron 2955U) */
15378         { 0x0a06, 0x1179, 0x0a88, quirk_backlight_present },
15379
15380         /* HP Chromebook 14 (Celeron 2955U) */
15381         { 0x0a06, 0x103c, 0x21ed, quirk_backlight_present },
15382
15383         /* Dell Chromebook 11 */
15384         { 0x0a06, 0x1028, 0x0a35, quirk_backlight_present },
15385
15386         /* Dell Chromebook 11 (2015 version) */
15387         { 0x0a16, 0x1028, 0x0a35, quirk_backlight_present },
15388 };
15389
15390 static void intel_init_quirks(struct drm_device *dev)
15391 {
15392         struct pci_dev *d = dev->pdev;
15393         int i;
15394
15395         for (i = 0; i < ARRAY_SIZE(intel_quirks); i++) {
15396                 struct intel_quirk *q = &intel_quirks[i];
15397
15398                 if (d->device == q->device &&
15399                     (d->subsystem_vendor == q->subsystem_vendor ||
15400                      q->subsystem_vendor == PCI_ANY_ID) &&
15401                     (d->subsystem_device == q->subsystem_device ||
15402                      q->subsystem_device == PCI_ANY_ID))
15403                         q->hook(dev);
15404         }
15405         for (i = 0; i < ARRAY_SIZE(intel_dmi_quirks); i++) {
15406                 if (dmi_check_system(*intel_dmi_quirks[i].dmi_id_list) != 0)
15407                         intel_dmi_quirks[i].hook(dev);
15408         }
15409 }
15410
15411 /* Disable the VGA plane that we never use */
15412 static void i915_disable_vga(struct drm_device *dev)
15413 {
15414         struct drm_i915_private *dev_priv = dev->dev_private;
15415         u8 sr1;
15416         i915_reg_t vga_reg = i915_vgacntrl_reg(dev);
15417
15418         /* WaEnableVGAAccessThroughIOPort:ctg,elk,ilk,snb,ivb,vlv,hsw */
15419         vga_get_uninterruptible(dev->pdev, VGA_RSRC_LEGACY_IO);
15420         outb(SR01, VGA_SR_INDEX);
15421         sr1 = inb(VGA_SR_DATA);
15422         outb(sr1 | 1<<5, VGA_SR_DATA);
15423         vga_put(dev->pdev, VGA_RSRC_LEGACY_IO);
15424         udelay(300);
15425
15426         I915_WRITE(vga_reg, VGA_DISP_DISABLE);
15427         POSTING_READ(vga_reg);
15428 }
15429
15430 void intel_modeset_init_hw(struct drm_device *dev)
15431 {
15432         struct drm_i915_private *dev_priv = dev->dev_private;
15433
15434         intel_update_cdclk(dev);
15435
15436         dev_priv->atomic_cdclk_freq = dev_priv->cdclk_freq;
15437
15438         intel_init_clock_gating(dev);
15439         intel_enable_gt_powersave(dev_priv);
15440 }
15441
15442 /*
15443  * Calculate what we think the watermarks should be for the state we've read
15444  * out of the hardware and then immediately program those watermarks so that
15445  * we ensure the hardware settings match our internal state.
15446  *
15447  * We can calculate what we think WM's should be by creating a duplicate of the
15448  * current state (which was constructed during hardware readout) and running it
15449  * through the atomic check code to calculate new watermark values in the
15450  * state object.
15451  */
15452 static void sanitize_watermarks(struct drm_device *dev)
15453 {
15454         struct drm_i915_private *dev_priv = to_i915(dev);
15455         struct drm_atomic_state *state;
15456         struct drm_crtc *crtc;
15457         struct drm_crtc_state *cstate;
15458         struct drm_modeset_acquire_ctx ctx;
15459         int ret;
15460         int i;
15461
15462         /* Only supported on platforms that use atomic watermark design */
15463         if (!dev_priv->display.optimize_watermarks)
15464                 return;
15465
15466         /*
15467          * We need to hold connection_mutex before calling duplicate_state so
15468          * that the connector loop is protected.
15469          */
15470         drm_modeset_acquire_init(&ctx, 0);
15471 retry:
15472         ret = drm_modeset_lock_all_ctx(dev, &ctx);
15473         if (ret == -EDEADLK) {
15474                 drm_modeset_backoff(&ctx);
15475                 goto retry;
15476         } else if (WARN_ON(ret)) {
15477                 goto fail;
15478         }
15479
15480         state = drm_atomic_helper_duplicate_state(dev, &ctx);
15481         if (WARN_ON(IS_ERR(state)))
15482                 goto fail;
15483
15484         /*
15485          * Hardware readout is the only time we don't want to calculate
15486          * intermediate watermarks (since we don't trust the current
15487          * watermarks).
15488          */
15489         to_intel_atomic_state(state)->skip_intermediate_wm = true;
15490
15491         ret = intel_atomic_check(dev, state);
15492         if (ret) {
15493                 /*
15494                  * If we fail here, it means that the hardware appears to be
15495                  * programmed in a way that shouldn't be possible, given our
15496                  * understanding of watermark requirements.  This might mean a
15497                  * mistake in the hardware readout code or a mistake in the
15498                  * watermark calculations for a given platform.  Raise a WARN
15499                  * so that this is noticeable.
15500                  *
15501                  * If this actually happens, we'll have to just leave the
15502                  * BIOS-programmed watermarks untouched and hope for the best.
15503                  */
15504                 WARN(true, "Could not determine valid watermarks for inherited state\n");
15505                 goto fail;
15506         }
15507
15508         /* Write calculated watermark values back */
15509         for_each_crtc_in_state(state, crtc, cstate, i) {
15510                 struct intel_crtc_state *cs = to_intel_crtc_state(cstate);
15511
15512                 cs->wm.need_postvbl_update = true;
15513                 dev_priv->display.optimize_watermarks(cs);
15514         }
15515
15516         drm_atomic_state_free(state);
15517 fail:
15518         drm_modeset_drop_locks(&ctx);
15519         drm_modeset_acquire_fini(&ctx);
15520 }
15521
15522 void intel_modeset_init(struct drm_device *dev)
15523 {
15524         struct drm_i915_private *dev_priv = to_i915(dev);
15525         struct i915_ggtt *ggtt = &dev_priv->ggtt;
15526         int sprite, ret;
15527         enum pipe pipe;
15528         struct intel_crtc *crtc;
15529
15530         drm_mode_config_init(dev);
15531
15532         dev->mode_config.min_width = 0;
15533         dev->mode_config.min_height = 0;
15534
15535         dev->mode_config.preferred_depth = 24;
15536         dev->mode_config.prefer_shadow = 1;
15537
15538         dev->mode_config.allow_fb_modifiers = true;
15539
15540         dev->mode_config.funcs = &intel_mode_funcs;
15541
15542         intel_init_quirks(dev);
15543
15544         intel_init_pm(dev);
15545
15546         if (INTEL_INFO(dev)->num_pipes == 0)
15547                 return;
15548
15549         /*
15550          * There may be no VBT; and if the BIOS enabled SSC we can
15551          * just keep using it to avoid unnecessary flicker.  Whereas if the
15552          * BIOS isn't using it, don't assume it will work even if the VBT
15553          * indicates as much.
15554          */
15555         if (HAS_PCH_IBX(dev) || HAS_PCH_CPT(dev)) {
15556                 bool bios_lvds_use_ssc = !!(I915_READ(PCH_DREF_CONTROL) &
15557                                             DREF_SSC1_ENABLE);
15558
15559                 if (dev_priv->vbt.lvds_use_ssc != bios_lvds_use_ssc) {
15560                         DRM_DEBUG_KMS("SSC %sabled by BIOS, overriding VBT which says %sabled\n",
15561                                      bios_lvds_use_ssc ? "en" : "dis",
15562                                      dev_priv->vbt.lvds_use_ssc ? "en" : "dis");
15563                         dev_priv->vbt.lvds_use_ssc = bios_lvds_use_ssc;
15564                 }
15565         }
15566
15567         if (IS_GEN2(dev)) {
15568                 dev->mode_config.max_width = 2048;
15569                 dev->mode_config.max_height = 2048;
15570         } else if (IS_GEN3(dev)) {
15571                 dev->mode_config.max_width = 4096;
15572                 dev->mode_config.max_height = 4096;
15573         } else {
15574                 dev->mode_config.max_width = 8192;
15575                 dev->mode_config.max_height = 8192;
15576         }
15577
15578         if (IS_845G(dev) || IS_I865G(dev)) {
15579                 dev->mode_config.cursor_width = IS_845G(dev) ? 64 : 512;
15580                 dev->mode_config.cursor_height = 1023;
15581         } else if (IS_GEN2(dev)) {
15582                 dev->mode_config.cursor_width = GEN2_CURSOR_WIDTH;
15583                 dev->mode_config.cursor_height = GEN2_CURSOR_HEIGHT;
15584         } else {
15585                 dev->mode_config.cursor_width = MAX_CURSOR_WIDTH;
15586                 dev->mode_config.cursor_height = MAX_CURSOR_HEIGHT;
15587         }
15588
15589         dev->mode_config.fb_base = ggtt->mappable_base;
15590
15591         DRM_DEBUG_KMS("%d display pipe%s available.\n",
15592                       INTEL_INFO(dev)->num_pipes,
15593                       INTEL_INFO(dev)->num_pipes > 1 ? "s" : "");
15594
15595         for_each_pipe(dev_priv, pipe) {
15596                 intel_crtc_init(dev, pipe);
15597                 for_each_sprite(dev_priv, pipe, sprite) {
15598                         ret = intel_plane_init(dev, pipe, sprite);
15599                         if (ret)
15600                                 DRM_DEBUG_KMS("pipe %c sprite %c init failed: %d\n",
15601                                               pipe_name(pipe), sprite_name(pipe, sprite), ret);
15602                 }
15603         }
15604
15605         intel_update_czclk(dev_priv);
15606         intel_update_cdclk(dev);
15607
15608         intel_shared_dpll_init(dev);
15609
15610         if (dev_priv->max_cdclk_freq == 0)
15611                 intel_update_max_cdclk(dev);
15612
15613         /* Just disable it once at startup */
15614         i915_disable_vga(dev);
15615         intel_setup_outputs(dev);
15616
15617         drm_modeset_lock_all(dev);
15618         intel_modeset_setup_hw_state(dev);
15619         drm_modeset_unlock_all(dev);
15620
15621         for_each_intel_crtc(dev, crtc) {
15622                 struct intel_initial_plane_config plane_config = {};
15623
15624                 if (!crtc->active)
15625                         continue;
15626
15627                 /*
15628                  * Note that reserving the BIOS fb up front prevents us
15629                  * from stuffing other stolen allocations like the ring
15630                  * on top.  This prevents some ugliness at boot time, and
15631                  * can even allow for smooth boot transitions if the BIOS
15632                  * fb is large enough for the active pipe configuration.
15633                  */
15634                 dev_priv->display.get_initial_plane_config(crtc,
15635                                                            &plane_config);
15636
15637                 /*
15638                  * If the fb is shared between multiple heads, we'll
15639                  * just get the first one.
15640                  */
15641                 intel_find_initial_plane_obj(crtc, &plane_config);
15642         }
15643
15644         /*
15645          * Make sure hardware watermarks really match the state we read out.
15646          * Note that we need to do this after reconstructing the BIOS fb's
15647          * since the watermark calculation done here will use pstate->fb.
15648          */
15649         sanitize_watermarks(dev);
15650 }
15651
15652 static void intel_enable_pipe_a(struct drm_device *dev)
15653 {
15654         struct intel_connector *connector;
15655         struct drm_connector *crt = NULL;
15656         struct intel_load_detect_pipe load_detect_temp;
15657         struct drm_modeset_acquire_ctx *ctx = dev->mode_config.acquire_ctx;
15658
15659         /* We can't just switch on the pipe A, we need to set things up with a
15660          * proper mode and output configuration. As a gross hack, enable pipe A
15661          * by enabling the load detect pipe once. */
15662         for_each_intel_connector(dev, connector) {
15663                 if (connector->encoder->type == INTEL_OUTPUT_ANALOG) {
15664                         crt = &connector->base;
15665                         break;
15666                 }
15667         }
15668
15669         if (!crt)
15670                 return;
15671
15672         if (intel_get_load_detect_pipe(crt, NULL, &load_detect_temp, ctx))
15673                 intel_release_load_detect_pipe(crt, &load_detect_temp, ctx);
15674 }
15675
15676 static bool
15677 intel_check_plane_mapping(struct intel_crtc *crtc)
15678 {
15679         struct drm_device *dev = crtc->base.dev;
15680         struct drm_i915_private *dev_priv = dev->dev_private;
15681         u32 val;
15682
15683         if (INTEL_INFO(dev)->num_pipes == 1)
15684                 return true;
15685
15686         val = I915_READ(DSPCNTR(!crtc->plane));
15687
15688         if ((val & DISPLAY_PLANE_ENABLE) &&
15689             (!!(val & DISPPLANE_SEL_PIPE_MASK) == crtc->pipe))
15690                 return false;
15691
15692         return true;
15693 }
15694
15695 static bool intel_crtc_has_encoders(struct intel_crtc *crtc)
15696 {
15697         struct drm_device *dev = crtc->base.dev;
15698         struct intel_encoder *encoder;
15699
15700         for_each_encoder_on_crtc(dev, &crtc->base, encoder)
15701                 return true;
15702
15703         return false;
15704 }
15705
15706 static bool intel_encoder_has_connectors(struct intel_encoder *encoder)
15707 {
15708         struct drm_device *dev = encoder->base.dev;
15709         struct intel_connector *connector;
15710
15711         for_each_connector_on_encoder(dev, &encoder->base, connector)
15712                 return true;
15713
15714         return false;
15715 }
15716
15717 static void intel_sanitize_crtc(struct intel_crtc *crtc)
15718 {
15719         struct drm_device *dev = crtc->base.dev;
15720         struct drm_i915_private *dev_priv = dev->dev_private;
15721         enum transcoder cpu_transcoder = crtc->config->cpu_transcoder;
15722
15723         /* Clear any frame start delays used for debugging left by the BIOS */
15724         if (!transcoder_is_dsi(cpu_transcoder)) {
15725                 i915_reg_t reg = PIPECONF(cpu_transcoder);
15726
15727                 I915_WRITE(reg,
15728                            I915_READ(reg) & ~PIPECONF_FRAME_START_DELAY_MASK);
15729         }
15730
15731         /* restore vblank interrupts to correct state */
15732         drm_crtc_vblank_reset(&crtc->base);
15733         if (crtc->active) {
15734                 struct intel_plane *plane;
15735
15736                 drm_crtc_vblank_on(&crtc->base);
15737
15738                 /* Disable everything but the primary plane */
15739                 for_each_intel_plane_on_crtc(dev, crtc, plane) {
15740                         if (plane->base.type == DRM_PLANE_TYPE_PRIMARY)
15741                                 continue;
15742
15743                         plane->disable_plane(&plane->base, &crtc->base);
15744                 }
15745         }
15746
15747         /* We need to sanitize the plane -> pipe mapping first because this will
15748          * disable the crtc (and hence change the state) if it is wrong. Note
15749          * that gen4+ has a fixed plane -> pipe mapping.  */
15750         if (INTEL_INFO(dev)->gen < 4 && !intel_check_plane_mapping(crtc)) {
15751                 bool plane;
15752
15753                 DRM_DEBUG_KMS("[CRTC:%d:%s] wrong plane connection detected!\n",
15754                               crtc->base.base.id, crtc->base.name);
15755
15756                 /* Pipe has the wrong plane attached and the plane is active.
15757                  * Temporarily change the plane mapping and disable everything
15758                  * ...  */
15759                 plane = crtc->plane;
15760                 to_intel_plane_state(crtc->base.primary->state)->visible = true;
15761                 crtc->plane = !plane;
15762                 intel_crtc_disable_noatomic(&crtc->base);
15763                 crtc->plane = plane;
15764         }
15765
15766         if (dev_priv->quirks & QUIRK_PIPEA_FORCE &&
15767             crtc->pipe == PIPE_A && !crtc->active) {
15768                 /* BIOS forgot to enable pipe A, this mostly happens after
15769                  * resume. Force-enable the pipe to fix this, the update_dpms
15770                  * call below we restore the pipe to the right state, but leave
15771                  * the required bits on. */
15772                 intel_enable_pipe_a(dev);
15773         }
15774
15775         /* Adjust the state of the output pipe according to whether we
15776          * have active connectors/encoders. */
15777         if (crtc->active && !intel_crtc_has_encoders(crtc))
15778                 intel_crtc_disable_noatomic(&crtc->base);
15779
15780         if (crtc->active || HAS_GMCH_DISPLAY(dev)) {
15781                 /*
15782                  * We start out with underrun reporting disabled to avoid races.
15783                  * For correct bookkeeping mark this on active crtcs.
15784                  *
15785                  * Also on gmch platforms we dont have any hardware bits to
15786                  * disable the underrun reporting. Which means we need to start
15787                  * out with underrun reporting disabled also on inactive pipes,
15788                  * since otherwise we'll complain about the garbage we read when
15789                  * e.g. coming up after runtime pm.
15790                  *
15791                  * No protection against concurrent access is required - at
15792                  * worst a fifo underrun happens which also sets this to false.
15793                  */
15794                 crtc->cpu_fifo_underrun_disabled = true;
15795                 crtc->pch_fifo_underrun_disabled = true;
15796         }
15797 }
15798
15799 static void intel_sanitize_encoder(struct intel_encoder *encoder)
15800 {
15801         struct intel_connector *connector;
15802         struct drm_device *dev = encoder->base.dev;
15803
15804         /* We need to check both for a crtc link (meaning that the
15805          * encoder is active and trying to read from a pipe) and the
15806          * pipe itself being active. */
15807         bool has_active_crtc = encoder->base.crtc &&
15808                 to_intel_crtc(encoder->base.crtc)->active;
15809
15810         if (intel_encoder_has_connectors(encoder) && !has_active_crtc) {
15811                 DRM_DEBUG_KMS("[ENCODER:%d:%s] has active connectors but no active pipe!\n",
15812                               encoder->base.base.id,
15813                               encoder->base.name);
15814
15815                 /* Connector is active, but has no active pipe. This is
15816                  * fallout from our resume register restoring. Disable
15817                  * the encoder manually again. */
15818                 if (encoder->base.crtc) {
15819                         DRM_DEBUG_KMS("[ENCODER:%d:%s] manually disabled\n",
15820                                       encoder->base.base.id,
15821                                       encoder->base.name);
15822                         encoder->disable(encoder);
15823                         if (encoder->post_disable)
15824                                 encoder->post_disable(encoder);
15825                 }
15826                 encoder->base.crtc = NULL;
15827
15828                 /* Inconsistent output/port/pipe state happens presumably due to
15829                  * a bug in one of the get_hw_state functions. Or someplace else
15830                  * in our code, like the register restore mess on resume. Clamp
15831                  * things to off as a safer default. */
15832                 for_each_intel_connector(dev, connector) {
15833                         if (connector->encoder != encoder)
15834                                 continue;
15835                         connector->base.dpms = DRM_MODE_DPMS_OFF;
15836                         connector->base.encoder = NULL;
15837                 }
15838         }
15839         /* Enabled encoders without active connectors will be fixed in
15840          * the crtc fixup. */
15841 }
15842
15843 void i915_redisable_vga_power_on(struct drm_device *dev)
15844 {
15845         struct drm_i915_private *dev_priv = dev->dev_private;
15846         i915_reg_t vga_reg = i915_vgacntrl_reg(dev);
15847
15848         if (!(I915_READ(vga_reg) & VGA_DISP_DISABLE)) {
15849                 DRM_DEBUG_KMS("Something enabled VGA plane, disabling it\n");
15850                 i915_disable_vga(dev);
15851         }
15852 }
15853
15854 void i915_redisable_vga(struct drm_device *dev)
15855 {
15856         struct drm_i915_private *dev_priv = dev->dev_private;
15857
15858         /* This function can be called both from intel_modeset_setup_hw_state or
15859          * at a very early point in our resume sequence, where the power well
15860          * structures are not yet restored. Since this function is at a very
15861          * paranoid "someone might have enabled VGA while we were not looking"
15862          * level, just check if the power well is enabled instead of trying to
15863          * follow the "don't touch the power well if we don't need it" policy
15864          * the rest of the driver uses. */
15865         if (!intel_display_power_get_if_enabled(dev_priv, POWER_DOMAIN_VGA))
15866                 return;
15867
15868         i915_redisable_vga_power_on(dev);
15869
15870         intel_display_power_put(dev_priv, POWER_DOMAIN_VGA);
15871 }
15872
15873 static bool primary_get_hw_state(struct intel_plane *plane)
15874 {
15875         struct drm_i915_private *dev_priv = to_i915(plane->base.dev);
15876
15877         return I915_READ(DSPCNTR(plane->plane)) & DISPLAY_PLANE_ENABLE;
15878 }
15879
15880 /* FIXME read out full plane state for all planes */
15881 static void readout_plane_state(struct intel_crtc *crtc)
15882 {
15883         struct drm_plane *primary = crtc->base.primary;
15884         struct intel_plane_state *plane_state =
15885                 to_intel_plane_state(primary->state);
15886
15887         plane_state->visible = crtc->active &&
15888                 primary_get_hw_state(to_intel_plane(primary));
15889
15890         if (plane_state->visible)
15891                 crtc->base.state->plane_mask |= 1 << drm_plane_index(primary);
15892 }
15893
15894 static void intel_modeset_readout_hw_state(struct drm_device *dev)
15895 {
15896         struct drm_i915_private *dev_priv = dev->dev_private;
15897         enum pipe pipe;
15898         struct intel_crtc *crtc;
15899         struct intel_encoder *encoder;
15900         struct intel_connector *connector;
15901         int i;
15902
15903         dev_priv->active_crtcs = 0;
15904
15905         for_each_intel_crtc(dev, crtc) {
15906                 struct intel_crtc_state *crtc_state = crtc->config;
15907                 int pixclk = 0;
15908
15909                 __drm_atomic_helper_crtc_destroy_state(&crtc_state->base);
15910                 memset(crtc_state, 0, sizeof(*crtc_state));
15911                 crtc_state->base.crtc = &crtc->base;
15912
15913                 crtc_state->base.active = crtc_state->base.enable =
15914                         dev_priv->display.get_pipe_config(crtc, crtc_state);
15915
15916                 crtc->base.enabled = crtc_state->base.enable;
15917                 crtc->active = crtc_state->base.active;
15918
15919                 if (crtc_state->base.active) {
15920                         dev_priv->active_crtcs |= 1 << crtc->pipe;
15921
15922                         if (INTEL_GEN(dev_priv) >= 9 || IS_BROADWELL(dev_priv))
15923                                 pixclk = ilk_pipe_pixel_rate(crtc_state);
15924                         else if (IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv))
15925                                 pixclk = crtc_state->base.adjusted_mode.crtc_clock;
15926                         else
15927                                 WARN_ON(dev_priv->display.modeset_calc_cdclk);
15928
15929                         /* pixel rate mustn't exceed 95% of cdclk with IPS on BDW */
15930                         if (IS_BROADWELL(dev_priv) && crtc_state->ips_enabled)
15931                                 pixclk = DIV_ROUND_UP(pixclk * 100, 95);
15932                 }
15933
15934                 dev_priv->min_pixclk[crtc->pipe] = pixclk;
15935
15936                 readout_plane_state(crtc);
15937
15938                 DRM_DEBUG_KMS("[CRTC:%d:%s] hw state readout: %s\n",
15939                               crtc->base.base.id, crtc->base.name,
15940                               crtc->active ? "enabled" : "disabled");
15941         }
15942
15943         for (i = 0; i < dev_priv->num_shared_dpll; i++) {
15944                 struct intel_shared_dpll *pll = &dev_priv->shared_dplls[i];
15945
15946                 pll->on = pll->funcs.get_hw_state(dev_priv, pll,
15947                                                   &pll->config.hw_state);
15948                 pll->config.crtc_mask = 0;
15949                 for_each_intel_crtc(dev, crtc) {
15950                         if (crtc->active && crtc->config->shared_dpll == pll)
15951                                 pll->config.crtc_mask |= 1 << crtc->pipe;
15952                 }
15953                 pll->active_mask = pll->config.crtc_mask;
15954
15955                 DRM_DEBUG_KMS("%s hw state readout: crtc_mask 0x%08x, on %i\n",
15956                               pll->name, pll->config.crtc_mask, pll->on);
15957         }
15958
15959         for_each_intel_encoder(dev, encoder) {
15960                 pipe = 0;
15961
15962                 if (encoder->get_hw_state(encoder, &pipe)) {
15963                         crtc = to_intel_crtc(dev_priv->pipe_to_crtc_mapping[pipe]);
15964                         encoder->base.crtc = &crtc->base;
15965                         encoder->get_config(encoder, crtc->config);
15966                 } else {
15967                         encoder->base.crtc = NULL;
15968                 }
15969
15970                 DRM_DEBUG_KMS("[ENCODER:%d:%s] hw state readout: %s, pipe %c\n",
15971                               encoder->base.base.id,
15972                               encoder->base.name,
15973                               encoder->base.crtc ? "enabled" : "disabled",
15974                               pipe_name(pipe));
15975         }
15976
15977         for_each_intel_connector(dev, connector) {
15978                 if (connector->get_hw_state(connector)) {
15979                         connector->base.dpms = DRM_MODE_DPMS_ON;
15980
15981                         encoder = connector->encoder;
15982                         connector->base.encoder = &encoder->base;
15983
15984                         if (encoder->base.crtc &&
15985                             encoder->base.crtc->state->active) {
15986                                 /*
15987                                  * This has to be done during hardware readout
15988                                  * because anything calling .crtc_disable may
15989                                  * rely on the connector_mask being accurate.
15990                                  */
15991                                 encoder->base.crtc->state->connector_mask |=
15992                                         1 << drm_connector_index(&connector->base);
15993                                 encoder->base.crtc->state->encoder_mask |=
15994                                         1 << drm_encoder_index(&encoder->base);
15995                         }
15996
15997                 } else {
15998                         connector->base.dpms = DRM_MODE_DPMS_OFF;
15999                         connector->base.encoder = NULL;
16000                 }
16001                 DRM_DEBUG_KMS("[CONNECTOR:%d:%s] hw state readout: %s\n",
16002                               connector->base.base.id,
16003                               connector->base.name,
16004                               connector->base.encoder ? "enabled" : "disabled");
16005         }
16006
16007         for_each_intel_crtc(dev, crtc) {
16008                 crtc->base.hwmode = crtc->config->base.adjusted_mode;
16009
16010                 memset(&crtc->base.mode, 0, sizeof(crtc->base.mode));
16011                 if (crtc->base.state->active) {
16012                         intel_mode_from_pipe_config(&crtc->base.mode, crtc->config);
16013                         intel_mode_from_pipe_config(&crtc->base.state->adjusted_mode, crtc->config);
16014                         WARN_ON(drm_atomic_set_mode_for_crtc(crtc->base.state, &crtc->base.mode));
16015
16016                         /*
16017                          * The initial mode needs to be set in order to keep
16018                          * the atomic core happy. It wants a valid mode if the
16019                          * crtc's enabled, so we do the above call.
16020                          *
16021                          * At this point some state updated by the connectors
16022                          * in their ->detect() callback has not run yet, so
16023                          * no recalculation can be done yet.
16024                          *
16025                          * Even if we could do a recalculation and modeset
16026                          * right now it would cause a double modeset if
16027                          * fbdev or userspace chooses a different initial mode.
16028                          *
16029                          * If that happens, someone indicated they wanted a
16030                          * mode change, which means it's safe to do a full
16031                          * recalculation.
16032                          */
16033                         crtc->base.state->mode.private_flags = I915_MODE_FLAG_INHERITED;
16034
16035                         drm_calc_timestamping_constants(&crtc->base, &crtc->base.hwmode);
16036                         update_scanline_offset(crtc);
16037                 }
16038
16039                 intel_pipe_config_sanity_check(dev_priv, crtc->config);
16040         }
16041 }
16042
16043 /* Scan out the current hw modeset state,
16044  * and sanitizes it to the current state
16045  */
16046 static void
16047 intel_modeset_setup_hw_state(struct drm_device *dev)
16048 {
16049         struct drm_i915_private *dev_priv = dev->dev_private;
16050         enum pipe pipe;
16051         struct intel_crtc *crtc;
16052         struct intel_encoder *encoder;
16053         int i;
16054
16055         intel_modeset_readout_hw_state(dev);
16056
16057         /* HW state is read out, now we need to sanitize this mess. */
16058         for_each_intel_encoder(dev, encoder) {
16059                 intel_sanitize_encoder(encoder);
16060         }
16061
16062         for_each_pipe(dev_priv, pipe) {
16063                 crtc = to_intel_crtc(dev_priv->pipe_to_crtc_mapping[pipe]);
16064                 intel_sanitize_crtc(crtc);
16065                 intel_dump_pipe_config(crtc, crtc->config,
16066                                        "[setup_hw_state]");
16067         }
16068
16069         intel_modeset_update_connector_atomic_state(dev);
16070
16071         for (i = 0; i < dev_priv->num_shared_dpll; i++) {
16072                 struct intel_shared_dpll *pll = &dev_priv->shared_dplls[i];
16073
16074                 if (!pll->on || pll->active_mask)
16075                         continue;
16076
16077                 DRM_DEBUG_KMS("%s enabled but not in use, disabling\n", pll->name);
16078
16079                 pll->funcs.disable(dev_priv, pll);
16080                 pll->on = false;
16081         }
16082
16083         if (IS_VALLEYVIEW(dev) || IS_CHERRYVIEW(dev))
16084                 vlv_wm_get_hw_state(dev);
16085         else if (IS_GEN9(dev))
16086                 skl_wm_get_hw_state(dev);
16087         else if (HAS_PCH_SPLIT(dev))
16088                 ilk_wm_get_hw_state(dev);
16089
16090         for_each_intel_crtc(dev, crtc) {
16091                 unsigned long put_domains;
16092
16093                 put_domains = modeset_get_crtc_power_domains(&crtc->base, crtc->config);
16094                 if (WARN_ON(put_domains))
16095                         modeset_put_power_domains(dev_priv, put_domains);
16096         }
16097         intel_display_set_init_power(dev_priv, false);
16098
16099         intel_fbc_init_pipe_state(dev_priv);
16100 }
16101
16102 void intel_display_resume(struct drm_device *dev)
16103 {
16104         struct drm_i915_private *dev_priv = to_i915(dev);
16105         struct drm_atomic_state *state = dev_priv->modeset_restore_state;
16106         struct drm_modeset_acquire_ctx ctx;
16107         int ret;
16108         bool setup = false;
16109
16110         dev_priv->modeset_restore_state = NULL;
16111
16112         /*
16113          * This is a cludge because with real atomic modeset mode_config.mutex
16114          * won't be taken. Unfortunately some probed state like
16115          * audio_codec_enable is still protected by mode_config.mutex, so lock
16116          * it here for now.
16117          */
16118         mutex_lock(&dev->mode_config.mutex);
16119         drm_modeset_acquire_init(&ctx, 0);
16120
16121 retry:
16122         ret = drm_modeset_lock_all_ctx(dev, &ctx);
16123
16124         if (ret == 0 && !setup) {
16125                 setup = true;
16126
16127                 intel_modeset_setup_hw_state(dev);
16128                 i915_redisable_vga(dev);
16129         }
16130
16131         if (ret == 0 && state) {
16132                 struct drm_crtc_state *crtc_state;
16133                 struct drm_crtc *crtc;
16134                 int i;
16135
16136                 state->acquire_ctx = &ctx;
16137
16138                 /* ignore any reset values/BIOS leftovers in the WM registers */
16139                 to_intel_atomic_state(state)->skip_intermediate_wm = true;
16140
16141                 for_each_crtc_in_state(state, crtc, crtc_state, i) {
16142                         /*
16143                          * Force recalculation even if we restore
16144                          * current state. With fast modeset this may not result
16145                          * in a modeset when the state is compatible.
16146                          */
16147                         crtc_state->mode_changed = true;
16148                 }
16149
16150                 ret = drm_atomic_commit(state);
16151         }
16152
16153         if (ret == -EDEADLK) {
16154                 drm_modeset_backoff(&ctx);
16155                 goto retry;
16156         }
16157
16158         drm_modeset_drop_locks(&ctx);
16159         drm_modeset_acquire_fini(&ctx);
16160         mutex_unlock(&dev->mode_config.mutex);
16161
16162         if (ret) {
16163                 DRM_ERROR("Restoring old state failed with %i\n", ret);
16164                 drm_atomic_state_free(state);
16165         }
16166 }
16167
16168 void intel_modeset_gem_init(struct drm_device *dev)
16169 {
16170         struct drm_i915_private *dev_priv = to_i915(dev);
16171         struct drm_crtc *c;
16172         struct drm_i915_gem_object *obj;
16173         int ret;
16174
16175         intel_init_gt_powersave(dev_priv);
16176
16177         intel_modeset_init_hw(dev);
16178
16179         intel_setup_overlay(dev_priv);
16180
16181         /*
16182          * Make sure any fbs we allocated at startup are properly
16183          * pinned & fenced.  When we do the allocation it's too early
16184          * for this.
16185          */
16186         for_each_crtc(dev, c) {
16187                 obj = intel_fb_obj(c->primary->fb);
16188                 if (obj == NULL)
16189                         continue;
16190
16191                 mutex_lock(&dev->struct_mutex);
16192                 ret = intel_pin_and_fence_fb_obj(c->primary->fb,
16193                                                  c->primary->state->rotation);
16194                 mutex_unlock(&dev->struct_mutex);
16195                 if (ret) {
16196                         DRM_ERROR("failed to pin boot fb on pipe %d\n",
16197                                   to_intel_crtc(c)->pipe);
16198                         drm_framebuffer_unreference(c->primary->fb);
16199                         c->primary->fb = NULL;
16200                         c->primary->crtc = c->primary->state->crtc = NULL;
16201                         update_state_fb(c->primary);
16202                         c->state->plane_mask &= ~(1 << drm_plane_index(c->primary));
16203                 }
16204         }
16205
16206         intel_backlight_register(dev);
16207 }
16208
16209 void intel_connector_unregister(struct intel_connector *intel_connector)
16210 {
16211         struct drm_connector *connector = &intel_connector->base;
16212
16213         intel_panel_destroy_backlight(connector);
16214         drm_connector_unregister(connector);
16215 }
16216
16217 void intel_modeset_cleanup(struct drm_device *dev)
16218 {
16219         struct drm_i915_private *dev_priv = dev->dev_private;
16220         struct intel_connector *connector;
16221
16222         intel_disable_gt_powersave(dev_priv);
16223
16224         intel_backlight_unregister(dev);
16225
16226         /*
16227          * Interrupts and polling as the first thing to avoid creating havoc.
16228          * Too much stuff here (turning of connectors, ...) would
16229          * experience fancy races otherwise.
16230          */
16231         intel_irq_uninstall(dev_priv);
16232
16233         /*
16234          * Due to the hpd irq storm handling the hotplug work can re-arm the
16235          * poll handlers. Hence disable polling after hpd handling is shut down.
16236          */
16237         drm_kms_helper_poll_fini(dev);
16238
16239         intel_unregister_dsm_handler();
16240
16241         intel_fbc_global_disable(dev_priv);
16242
16243         /* flush any delayed tasks or pending work */
16244         flush_scheduled_work();
16245
16246         /* destroy the backlight and sysfs files before encoders/connectors */
16247         for_each_intel_connector(dev, connector)
16248                 connector->unregister(connector);
16249
16250         drm_mode_config_cleanup(dev);
16251
16252         intel_cleanup_overlay(dev_priv);
16253
16254         intel_cleanup_gt_powersave(dev_priv);
16255
16256         intel_teardown_gmbus(dev);
16257 }
16258
16259 /*
16260  * Return which encoder is currently attached for connector.
16261  */
16262 struct drm_encoder *intel_best_encoder(struct drm_connector *connector)
16263 {
16264         return &intel_attached_encoder(connector)->base;
16265 }
16266
16267 void intel_connector_attach_encoder(struct intel_connector *connector,
16268                                     struct intel_encoder *encoder)
16269 {
16270         connector->encoder = encoder;
16271         drm_mode_connector_attach_encoder(&connector->base,
16272                                           &encoder->base);
16273 }
16274
16275 /*
16276  * set vga decode state - true == enable VGA decode
16277  */
16278 int intel_modeset_vga_set_state(struct drm_device *dev, bool state)
16279 {
16280         struct drm_i915_private *dev_priv = dev->dev_private;
16281         unsigned reg = INTEL_INFO(dev)->gen >= 6 ? SNB_GMCH_CTRL : INTEL_GMCH_CTRL;
16282         u16 gmch_ctrl;
16283
16284         if (pci_read_config_word(dev_priv->bridge_dev, reg, &gmch_ctrl)) {
16285                 DRM_ERROR("failed to read control word\n");
16286                 return -EIO;
16287         }
16288
16289         if (!!(gmch_ctrl & INTEL_GMCH_VGA_DISABLE) == !state)
16290                 return 0;
16291
16292         if (state)
16293                 gmch_ctrl &= ~INTEL_GMCH_VGA_DISABLE;
16294         else
16295                 gmch_ctrl |= INTEL_GMCH_VGA_DISABLE;
16296
16297         if (pci_write_config_word(dev_priv->bridge_dev, reg, gmch_ctrl)) {
16298                 DRM_ERROR("failed to write control word\n");
16299                 return -EIO;
16300         }
16301
16302         return 0;
16303 }
16304
16305 struct intel_display_error_state {
16306
16307         u32 power_well_driver;
16308
16309         int num_transcoders;
16310
16311         struct intel_cursor_error_state {
16312                 u32 control;
16313                 u32 position;
16314                 u32 base;
16315                 u32 size;
16316         } cursor[I915_MAX_PIPES];
16317
16318         struct intel_pipe_error_state {
16319                 bool power_domain_on;
16320                 u32 source;
16321                 u32 stat;
16322         } pipe[I915_MAX_PIPES];
16323
16324         struct intel_plane_error_state {
16325                 u32 control;
16326                 u32 stride;
16327                 u32 size;
16328                 u32 pos;
16329                 u32 addr;
16330                 u32 surface;
16331                 u32 tile_offset;
16332         } plane[I915_MAX_PIPES];
16333
16334         struct intel_transcoder_error_state {
16335                 bool power_domain_on;
16336                 enum transcoder cpu_transcoder;
16337
16338                 u32 conf;
16339
16340                 u32 htotal;
16341                 u32 hblank;
16342                 u32 hsync;
16343                 u32 vtotal;
16344                 u32 vblank;
16345                 u32 vsync;
16346         } transcoder[4];
16347 };
16348
16349 struct intel_display_error_state *
16350 intel_display_capture_error_state(struct drm_i915_private *dev_priv)
16351 {
16352         struct intel_display_error_state *error;
16353         int transcoders[] = {
16354                 TRANSCODER_A,
16355                 TRANSCODER_B,
16356                 TRANSCODER_C,
16357                 TRANSCODER_EDP,
16358         };
16359         int i;
16360
16361         if (INTEL_INFO(dev_priv)->num_pipes == 0)
16362                 return NULL;
16363
16364         error = kzalloc(sizeof(*error), GFP_ATOMIC);
16365         if (error == NULL)
16366                 return NULL;
16367
16368         if (IS_HASWELL(dev_priv) || IS_BROADWELL(dev_priv))
16369                 error->power_well_driver = I915_READ(HSW_PWR_WELL_DRIVER);
16370
16371         for_each_pipe(dev_priv, i) {
16372                 error->pipe[i].power_domain_on =
16373                         __intel_display_power_is_enabled(dev_priv,
16374                                                          POWER_DOMAIN_PIPE(i));
16375                 if (!error->pipe[i].power_domain_on)
16376                         continue;
16377
16378                 error->cursor[i].control = I915_READ(CURCNTR(i));
16379                 error->cursor[i].position = I915_READ(CURPOS(i));
16380                 error->cursor[i].base = I915_READ(CURBASE(i));
16381
16382                 error->plane[i].control = I915_READ(DSPCNTR(i));
16383                 error->plane[i].stride = I915_READ(DSPSTRIDE(i));
16384                 if (INTEL_GEN(dev_priv) <= 3) {
16385                         error->plane[i].size = I915_READ(DSPSIZE(i));
16386                         error->plane[i].pos = I915_READ(DSPPOS(i));
16387                 }
16388                 if (INTEL_GEN(dev_priv) <= 7 && !IS_HASWELL(dev_priv))
16389                         error->plane[i].addr = I915_READ(DSPADDR(i));
16390                 if (INTEL_GEN(dev_priv) >= 4) {
16391                         error->plane[i].surface = I915_READ(DSPSURF(i));
16392                         error->plane[i].tile_offset = I915_READ(DSPTILEOFF(i));
16393                 }
16394
16395                 error->pipe[i].source = I915_READ(PIPESRC(i));
16396
16397                 if (HAS_GMCH_DISPLAY(dev_priv))
16398                         error->pipe[i].stat = I915_READ(PIPESTAT(i));
16399         }
16400
16401         /* Note: this does not include DSI transcoders. */
16402         error->num_transcoders = INTEL_INFO(dev_priv)->num_pipes;
16403         if (HAS_DDI(dev_priv))
16404                 error->num_transcoders++; /* Account for eDP. */
16405
16406         for (i = 0; i < error->num_transcoders; i++) {
16407                 enum transcoder cpu_transcoder = transcoders[i];
16408
16409                 error->transcoder[i].power_domain_on =
16410                         __intel_display_power_is_enabled(dev_priv,
16411                                 POWER_DOMAIN_TRANSCODER(cpu_transcoder));
16412                 if (!error->transcoder[i].power_domain_on)
16413                         continue;
16414
16415                 error->transcoder[i].cpu_transcoder = cpu_transcoder;
16416
16417                 error->transcoder[i].conf = I915_READ(PIPECONF(cpu_transcoder));
16418                 error->transcoder[i].htotal = I915_READ(HTOTAL(cpu_transcoder));
16419                 error->transcoder[i].hblank = I915_READ(HBLANK(cpu_transcoder));
16420                 error->transcoder[i].hsync = I915_READ(HSYNC(cpu_transcoder));
16421                 error->transcoder[i].vtotal = I915_READ(VTOTAL(cpu_transcoder));
16422                 error->transcoder[i].vblank = I915_READ(VBLANK(cpu_transcoder));
16423                 error->transcoder[i].vsync = I915_READ(VSYNC(cpu_transcoder));
16424         }
16425
16426         return error;
16427 }
16428
16429 #define err_printf(e, ...) i915_error_printf(e, __VA_ARGS__)
16430
16431 void
16432 intel_display_print_error_state(struct drm_i915_error_state_buf *m,
16433                                 struct drm_device *dev,
16434                                 struct intel_display_error_state *error)
16435 {
16436         struct drm_i915_private *dev_priv = dev->dev_private;
16437         int i;
16438
16439         if (!error)
16440                 return;
16441
16442         err_printf(m, "Num Pipes: %d\n", INTEL_INFO(dev)->num_pipes);
16443         if (IS_HASWELL(dev) || IS_BROADWELL(dev))
16444                 err_printf(m, "PWR_WELL_CTL2: %08x\n",
16445                            error->power_well_driver);
16446         for_each_pipe(dev_priv, i) {
16447                 err_printf(m, "Pipe [%d]:\n", i);
16448                 err_printf(m, "  Power: %s\n",
16449                            onoff(error->pipe[i].power_domain_on));
16450                 err_printf(m, "  SRC: %08x\n", error->pipe[i].source);
16451                 err_printf(m, "  STAT: %08x\n", error->pipe[i].stat);
16452
16453                 err_printf(m, "Plane [%d]:\n", i);
16454                 err_printf(m, "  CNTR: %08x\n", error->plane[i].control);
16455                 err_printf(m, "  STRIDE: %08x\n", error->plane[i].stride);
16456                 if (INTEL_INFO(dev)->gen <= 3) {
16457                         err_printf(m, "  SIZE: %08x\n", error->plane[i].size);
16458                         err_printf(m, "  POS: %08x\n", error->plane[i].pos);
16459                 }
16460                 if (INTEL_INFO(dev)->gen <= 7 && !IS_HASWELL(dev))
16461                         err_printf(m, "  ADDR: %08x\n", error->plane[i].addr);
16462                 if (INTEL_INFO(dev)->gen >= 4) {
16463                         err_printf(m, "  SURF: %08x\n", error->plane[i].surface);
16464                         err_printf(m, "  TILEOFF: %08x\n", error->plane[i].tile_offset);
16465                 }
16466
16467                 err_printf(m, "Cursor [%d]:\n", i);
16468                 err_printf(m, "  CNTR: %08x\n", error->cursor[i].control);
16469                 err_printf(m, "  POS: %08x\n", error->cursor[i].position);
16470                 err_printf(m, "  BASE: %08x\n", error->cursor[i].base);
16471         }
16472
16473         for (i = 0; i < error->num_transcoders; i++) {
16474                 err_printf(m, "CPU transcoder: %s\n",
16475                            transcoder_name(error->transcoder[i].cpu_transcoder));
16476                 err_printf(m, "  Power: %s\n",
16477                            onoff(error->transcoder[i].power_domain_on));
16478                 err_printf(m, "  CONF: %08x\n", error->transcoder[i].conf);
16479                 err_printf(m, "  HTOTAL: %08x\n", error->transcoder[i].htotal);
16480                 err_printf(m, "  HBLANK: %08x\n", error->transcoder[i].hblank);
16481                 err_printf(m, "  HSYNC: %08x\n", error->transcoder[i].hsync);
16482                 err_printf(m, "  VTOTAL: %08x\n", error->transcoder[i].vtotal);
16483                 err_printf(m, "  VBLANK: %08x\n", error->transcoder[i].vblank);
16484                 err_printf(m, "  VSYNC: %08x\n", error->transcoder[i].vsync);
16485         }
16486 }