Merge tag 'ccn/fixes-for-4.8-v2' of git://git.linaro.org/people/pawel.moll/linux...
[cascardo/linux.git] / drivers / gpu / drm / i915 / intel_display.c
1 /*
2  * Copyright © 2006-2007 Intel Corporation
3  *
4  * Permission is hereby granted, free of charge, to any person obtaining a
5  * copy of this software and associated documentation files (the "Software"),
6  * to deal in the Software without restriction, including without limitation
7  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
8  * and/or sell copies of the Software, and to permit persons to whom the
9  * Software is furnished to do so, subject to the following conditions:
10  *
11  * The above copyright notice and this permission notice (including the next
12  * paragraph) shall be included in all copies or substantial portions of the
13  * Software.
14  *
15  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
18  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
20  * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
21  * DEALINGS IN THE SOFTWARE.
22  *
23  * Authors:
24  *      Eric Anholt <eric@anholt.net>
25  */
26
27 #include <linux/dmi.h>
28 #include <linux/module.h>
29 #include <linux/input.h>
30 #include <linux/i2c.h>
31 #include <linux/kernel.h>
32 #include <linux/slab.h>
33 #include <linux/vgaarb.h>
34 #include <drm/drm_edid.h>
35 #include <drm/drmP.h>
36 #include "intel_drv.h"
37 #include <drm/i915_drm.h>
38 #include "i915_drv.h"
39 #include "i915_gem_dmabuf.h"
40 #include "intel_dsi.h"
41 #include "i915_trace.h"
42 #include <drm/drm_atomic.h>
43 #include <drm/drm_atomic_helper.h>
44 #include <drm/drm_dp_helper.h>
45 #include <drm/drm_crtc_helper.h>
46 #include <drm/drm_plane_helper.h>
47 #include <drm/drm_rect.h>
48 #include <linux/dma_remapping.h>
49 #include <linux/reservation.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 bxt_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  * Platform specific helpers to calculate the port PLL loopback- (clock.m),
535  * and post-divider (clock.p) values, pre- (clock.vco) and post-divided fast
536  * (clock.dot) clock rates. This fast dot clock is fed to the port's IO logic.
537  * The helpers' return value is the rate of the clock that is fed to the
538  * display engine's pipe which can be the above fast dot clock rate or a
539  * divided-down version of it.
540  */
541 /* m1 is reserved as 0 in Pineview, n is a ring counter */
542 static int pnv_calc_dpll_params(int refclk, struct dpll *clock)
543 {
544         clock->m = clock->m2 + 2;
545         clock->p = clock->p1 * clock->p2;
546         if (WARN_ON(clock->n == 0 || clock->p == 0))
547                 return 0;
548         clock->vco = DIV_ROUND_CLOSEST(refclk * clock->m, clock->n);
549         clock->dot = DIV_ROUND_CLOSEST(clock->vco, clock->p);
550
551         return clock->dot;
552 }
553
554 static uint32_t i9xx_dpll_compute_m(struct dpll *dpll)
555 {
556         return 5 * (dpll->m1 + 2) + (dpll->m2 + 2);
557 }
558
559 static int i9xx_calc_dpll_params(int refclk, struct dpll *clock)
560 {
561         clock->m = i9xx_dpll_compute_m(clock);
562         clock->p = clock->p1 * clock->p2;
563         if (WARN_ON(clock->n + 2 == 0 || clock->p == 0))
564                 return 0;
565         clock->vco = DIV_ROUND_CLOSEST(refclk * clock->m, clock->n + 2);
566         clock->dot = DIV_ROUND_CLOSEST(clock->vco, clock->p);
567
568         return clock->dot;
569 }
570
571 static int vlv_calc_dpll_params(int refclk, struct dpll *clock)
572 {
573         clock->m = clock->m1 * clock->m2;
574         clock->p = clock->p1 * clock->p2;
575         if (WARN_ON(clock->n == 0 || clock->p == 0))
576                 return 0;
577         clock->vco = DIV_ROUND_CLOSEST(refclk * clock->m, clock->n);
578         clock->dot = DIV_ROUND_CLOSEST(clock->vco, clock->p);
579
580         return clock->dot / 5;
581 }
582
583 int chv_calc_dpll_params(int refclk, struct dpll *clock)
584 {
585         clock->m = clock->m1 * clock->m2;
586         clock->p = clock->p1 * clock->p2;
587         if (WARN_ON(clock->n == 0 || clock->p == 0))
588                 return 0;
589         clock->vco = DIV_ROUND_CLOSEST_ULL((uint64_t)refclk * clock->m,
590                         clock->n << 22);
591         clock->dot = DIV_ROUND_CLOSEST(clock->vco, clock->p);
592
593         return clock->dot / 5;
594 }
595
596 #define INTELPllInvalid(s)   do { /* DRM_DEBUG(s); */ return false; } while (0)
597 /**
598  * Returns whether the given set of divisors are valid for a given refclk with
599  * the given connectors.
600  */
601
602 static bool intel_PLL_is_valid(struct drm_device *dev,
603                                const struct intel_limit *limit,
604                                const struct dpll *clock)
605 {
606         if (clock->n   < limit->n.min   || limit->n.max   < clock->n)
607                 INTELPllInvalid("n out of range\n");
608         if (clock->p1  < limit->p1.min  || limit->p1.max  < clock->p1)
609                 INTELPllInvalid("p1 out of range\n");
610         if (clock->m2  < limit->m2.min  || limit->m2.max  < clock->m2)
611                 INTELPllInvalid("m2 out of range\n");
612         if (clock->m1  < limit->m1.min  || limit->m1.max  < clock->m1)
613                 INTELPllInvalid("m1 out of range\n");
614
615         if (!IS_PINEVIEW(dev) && !IS_VALLEYVIEW(dev) &&
616             !IS_CHERRYVIEW(dev) && !IS_BROXTON(dev))
617                 if (clock->m1 <= clock->m2)
618                         INTELPllInvalid("m1 <= m2\n");
619
620         if (!IS_VALLEYVIEW(dev) && !IS_CHERRYVIEW(dev) && !IS_BROXTON(dev)) {
621                 if (clock->p < limit->p.min || limit->p.max < clock->p)
622                         INTELPllInvalid("p out of range\n");
623                 if (clock->m < limit->m.min || limit->m.max < clock->m)
624                         INTELPllInvalid("m out of range\n");
625         }
626
627         if (clock->vco < limit->vco.min || limit->vco.max < clock->vco)
628                 INTELPllInvalid("vco out of range\n");
629         /* XXX: We may need to be checking "Dot clock" depending on the multiplier,
630          * connector, etc., rather than just a single range.
631          */
632         if (clock->dot < limit->dot.min || limit->dot.max < clock->dot)
633                 INTELPllInvalid("dot out of range\n");
634
635         return true;
636 }
637
638 static int
639 i9xx_select_p2_div(const struct intel_limit *limit,
640                    const struct intel_crtc_state *crtc_state,
641                    int target)
642 {
643         struct drm_device *dev = crtc_state->base.crtc->dev;
644
645         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS)) {
646                 /*
647                  * For LVDS just rely on its current settings for dual-channel.
648                  * We haven't figured out how to reliably set up different
649                  * single/dual channel state, if we even can.
650                  */
651                 if (intel_is_dual_link_lvds(dev))
652                         return limit->p2.p2_fast;
653                 else
654                         return limit->p2.p2_slow;
655         } else {
656                 if (target < limit->p2.dot_limit)
657                         return limit->p2.p2_slow;
658                 else
659                         return limit->p2.p2_fast;
660         }
661 }
662
663 /*
664  * Returns a set of divisors for the desired target clock with the given
665  * refclk, or FALSE.  The returned values represent the clock equation:
666  * reflck * (5 * (m1 + 2) + (m2 + 2)) / (n + 2) / p1 / p2.
667  *
668  * Target and reference clocks are specified in kHz.
669  *
670  * If match_clock is provided, then best_clock P divider must match the P
671  * divider from @match_clock used for LVDS downclocking.
672  */
673 static bool
674 i9xx_find_best_dpll(const struct intel_limit *limit,
675                     struct intel_crtc_state *crtc_state,
676                     int target, int refclk, struct dpll *match_clock,
677                     struct dpll *best_clock)
678 {
679         struct drm_device *dev = crtc_state->base.crtc->dev;
680         struct dpll clock;
681         int err = target;
682
683         memset(best_clock, 0, sizeof(*best_clock));
684
685         clock.p2 = i9xx_select_p2_div(limit, crtc_state, target);
686
687         for (clock.m1 = limit->m1.min; clock.m1 <= limit->m1.max;
688              clock.m1++) {
689                 for (clock.m2 = limit->m2.min;
690                      clock.m2 <= limit->m2.max; clock.m2++) {
691                         if (clock.m2 >= clock.m1)
692                                 break;
693                         for (clock.n = limit->n.min;
694                              clock.n <= limit->n.max; clock.n++) {
695                                 for (clock.p1 = limit->p1.min;
696                                         clock.p1 <= limit->p1.max; clock.p1++) {
697                                         int this_err;
698
699                                         i9xx_calc_dpll_params(refclk, &clock);
700                                         if (!intel_PLL_is_valid(dev, limit,
701                                                                 &clock))
702                                                 continue;
703                                         if (match_clock &&
704                                             clock.p != match_clock->p)
705                                                 continue;
706
707                                         this_err = abs(clock.dot - target);
708                                         if (this_err < err) {
709                                                 *best_clock = clock;
710                                                 err = this_err;
711                                         }
712                                 }
713                         }
714                 }
715         }
716
717         return (err != target);
718 }
719
720 /*
721  * Returns a set of divisors for the desired target clock with the given
722  * refclk, or FALSE.  The returned values represent the clock equation:
723  * reflck * (5 * (m1 + 2) + (m2 + 2)) / (n + 2) / p1 / p2.
724  *
725  * Target and reference clocks are specified in kHz.
726  *
727  * If match_clock is provided, then best_clock P divider must match the P
728  * divider from @match_clock used for LVDS downclocking.
729  */
730 static bool
731 pnv_find_best_dpll(const struct intel_limit *limit,
732                    struct intel_crtc_state *crtc_state,
733                    int target, int refclk, struct dpll *match_clock,
734                    struct dpll *best_clock)
735 {
736         struct drm_device *dev = crtc_state->base.crtc->dev;
737         struct dpll clock;
738         int err = target;
739
740         memset(best_clock, 0, sizeof(*best_clock));
741
742         clock.p2 = i9xx_select_p2_div(limit, crtc_state, target);
743
744         for (clock.m1 = limit->m1.min; clock.m1 <= limit->m1.max;
745              clock.m1++) {
746                 for (clock.m2 = limit->m2.min;
747                      clock.m2 <= limit->m2.max; clock.m2++) {
748                         for (clock.n = limit->n.min;
749                              clock.n <= limit->n.max; clock.n++) {
750                                 for (clock.p1 = limit->p1.min;
751                                         clock.p1 <= limit->p1.max; clock.p1++) {
752                                         int this_err;
753
754                                         pnv_calc_dpll_params(refclk, &clock);
755                                         if (!intel_PLL_is_valid(dev, limit,
756                                                                 &clock))
757                                                 continue;
758                                         if (match_clock &&
759                                             clock.p != match_clock->p)
760                                                 continue;
761
762                                         this_err = abs(clock.dot - target);
763                                         if (this_err < err) {
764                                                 *best_clock = clock;
765                                                 err = this_err;
766                                         }
767                                 }
768                         }
769                 }
770         }
771
772         return (err != target);
773 }
774
775 /*
776  * Returns a set of divisors for the desired target clock with the given
777  * refclk, or FALSE.  The returned values represent the clock equation:
778  * reflck * (5 * (m1 + 2) + (m2 + 2)) / (n + 2) / p1 / p2.
779  *
780  * Target and reference clocks are specified in kHz.
781  *
782  * If match_clock is provided, then best_clock P divider must match the P
783  * divider from @match_clock used for LVDS downclocking.
784  */
785 static bool
786 g4x_find_best_dpll(const struct intel_limit *limit,
787                    struct intel_crtc_state *crtc_state,
788                    int target, int refclk, struct dpll *match_clock,
789                    struct dpll *best_clock)
790 {
791         struct drm_device *dev = crtc_state->base.crtc->dev;
792         struct dpll clock;
793         int max_n;
794         bool found = false;
795         /* approximately equals target * 0.00585 */
796         int err_most = (target >> 8) + (target >> 9);
797
798         memset(best_clock, 0, sizeof(*best_clock));
799
800         clock.p2 = i9xx_select_p2_div(limit, crtc_state, target);
801
802         max_n = limit->n.max;
803         /* based on hardware requirement, prefer smaller n to precision */
804         for (clock.n = limit->n.min; clock.n <= max_n; clock.n++) {
805                 /* based on hardware requirement, prefere larger m1,m2 */
806                 for (clock.m1 = limit->m1.max;
807                      clock.m1 >= limit->m1.min; clock.m1--) {
808                         for (clock.m2 = limit->m2.max;
809                              clock.m2 >= limit->m2.min; clock.m2--) {
810                                 for (clock.p1 = limit->p1.max;
811                                      clock.p1 >= limit->p1.min; clock.p1--) {
812                                         int this_err;
813
814                                         i9xx_calc_dpll_params(refclk, &clock);
815                                         if (!intel_PLL_is_valid(dev, limit,
816                                                                 &clock))
817                                                 continue;
818
819                                         this_err = abs(clock.dot - target);
820                                         if (this_err < err_most) {
821                                                 *best_clock = clock;
822                                                 err_most = this_err;
823                                                 max_n = clock.n;
824                                                 found = true;
825                                         }
826                                 }
827                         }
828                 }
829         }
830         return found;
831 }
832
833 /*
834  * Check if the calculated PLL configuration is more optimal compared to the
835  * best configuration and error found so far. Return the calculated error.
836  */
837 static bool vlv_PLL_is_optimal(struct drm_device *dev, int target_freq,
838                                const struct dpll *calculated_clock,
839                                const struct dpll *best_clock,
840                                unsigned int best_error_ppm,
841                                unsigned int *error_ppm)
842 {
843         /*
844          * For CHV ignore the error and consider only the P value.
845          * Prefer a bigger P value based on HW requirements.
846          */
847         if (IS_CHERRYVIEW(dev)) {
848                 *error_ppm = 0;
849
850                 return calculated_clock->p > best_clock->p;
851         }
852
853         if (WARN_ON_ONCE(!target_freq))
854                 return false;
855
856         *error_ppm = div_u64(1000000ULL *
857                                 abs(target_freq - calculated_clock->dot),
858                              target_freq);
859         /*
860          * Prefer a better P value over a better (smaller) error if the error
861          * is small. Ensure this preference for future configurations too by
862          * setting the error to 0.
863          */
864         if (*error_ppm < 100 && calculated_clock->p > best_clock->p) {
865                 *error_ppm = 0;
866
867                 return true;
868         }
869
870         return *error_ppm + 10 < best_error_ppm;
871 }
872
873 /*
874  * Returns a set of divisors for the desired target clock with the given
875  * refclk, or FALSE.  The returned values represent the clock equation:
876  * reflck * (5 * (m1 + 2) + (m2 + 2)) / (n + 2) / p1 / p2.
877  */
878 static bool
879 vlv_find_best_dpll(const struct intel_limit *limit,
880                    struct intel_crtc_state *crtc_state,
881                    int target, int refclk, struct dpll *match_clock,
882                    struct dpll *best_clock)
883 {
884         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
885         struct drm_device *dev = crtc->base.dev;
886         struct dpll clock;
887         unsigned int bestppm = 1000000;
888         /* min update 19.2 MHz */
889         int max_n = min(limit->n.max, refclk / 19200);
890         bool found = false;
891
892         target *= 5; /* fast clock */
893
894         memset(best_clock, 0, sizeof(*best_clock));
895
896         /* based on hardware requirement, prefer smaller n to precision */
897         for (clock.n = limit->n.min; clock.n <= max_n; clock.n++) {
898                 for (clock.p1 = limit->p1.max; clock.p1 >= limit->p1.min; clock.p1--) {
899                         for (clock.p2 = limit->p2.p2_fast; clock.p2 >= limit->p2.p2_slow;
900                              clock.p2 -= clock.p2 > 10 ? 2 : 1) {
901                                 clock.p = clock.p1 * clock.p2;
902                                 /* based on hardware requirement, prefer bigger m1,m2 values */
903                                 for (clock.m1 = limit->m1.min; clock.m1 <= limit->m1.max; clock.m1++) {
904                                         unsigned int ppm;
905
906                                         clock.m2 = DIV_ROUND_CLOSEST(target * clock.p * clock.n,
907                                                                      refclk * clock.m1);
908
909                                         vlv_calc_dpll_params(refclk, &clock);
910
911                                         if (!intel_PLL_is_valid(dev, limit,
912                                                                 &clock))
913                                                 continue;
914
915                                         if (!vlv_PLL_is_optimal(dev, target,
916                                                                 &clock,
917                                                                 best_clock,
918                                                                 bestppm, &ppm))
919                                                 continue;
920
921                                         *best_clock = clock;
922                                         bestppm = ppm;
923                                         found = true;
924                                 }
925                         }
926                 }
927         }
928
929         return found;
930 }
931
932 /*
933  * Returns a set of divisors for the desired target clock with the given
934  * refclk, or FALSE.  The returned values represent the clock equation:
935  * reflck * (5 * (m1 + 2) + (m2 + 2)) / (n + 2) / p1 / p2.
936  */
937 static bool
938 chv_find_best_dpll(const struct intel_limit *limit,
939                    struct intel_crtc_state *crtc_state,
940                    int target, int refclk, struct dpll *match_clock,
941                    struct dpll *best_clock)
942 {
943         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
944         struct drm_device *dev = crtc->base.dev;
945         unsigned int best_error_ppm;
946         struct dpll clock;
947         uint64_t m2;
948         int found = false;
949
950         memset(best_clock, 0, sizeof(*best_clock));
951         best_error_ppm = 1000000;
952
953         /*
954          * Based on hardware doc, the n always set to 1, and m1 always
955          * set to 2.  If requires to support 200Mhz refclk, we need to
956          * revisit this because n may not 1 anymore.
957          */
958         clock.n = 1, clock.m1 = 2;
959         target *= 5;    /* fast clock */
960
961         for (clock.p1 = limit->p1.max; clock.p1 >= limit->p1.min; clock.p1--) {
962                 for (clock.p2 = limit->p2.p2_fast;
963                                 clock.p2 >= limit->p2.p2_slow;
964                                 clock.p2 -= clock.p2 > 10 ? 2 : 1) {
965                         unsigned int error_ppm;
966
967                         clock.p = clock.p1 * clock.p2;
968
969                         m2 = DIV_ROUND_CLOSEST_ULL(((uint64_t)target * clock.p *
970                                         clock.n) << 22, refclk * clock.m1);
971
972                         if (m2 > INT_MAX/clock.m1)
973                                 continue;
974
975                         clock.m2 = m2;
976
977                         chv_calc_dpll_params(refclk, &clock);
978
979                         if (!intel_PLL_is_valid(dev, limit, &clock))
980                                 continue;
981
982                         if (!vlv_PLL_is_optimal(dev, target, &clock, best_clock,
983                                                 best_error_ppm, &error_ppm))
984                                 continue;
985
986                         *best_clock = clock;
987                         best_error_ppm = error_ppm;
988                         found = true;
989                 }
990         }
991
992         return found;
993 }
994
995 bool bxt_find_best_dpll(struct intel_crtc_state *crtc_state, int target_clock,
996                         struct dpll *best_clock)
997 {
998         int refclk = 100000;
999         const struct intel_limit *limit = &intel_limits_bxt;
1000
1001         return chv_find_best_dpll(limit, crtc_state,
1002                                   target_clock, refclk, NULL, best_clock);
1003 }
1004
1005 bool intel_crtc_active(struct drm_crtc *crtc)
1006 {
1007         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
1008
1009         /* Be paranoid as we can arrive here with only partial
1010          * state retrieved from the hardware during setup.
1011          *
1012          * We can ditch the adjusted_mode.crtc_clock check as soon
1013          * as Haswell has gained clock readout/fastboot support.
1014          *
1015          * We can ditch the crtc->primary->fb check as soon as we can
1016          * properly reconstruct framebuffers.
1017          *
1018          * FIXME: The intel_crtc->active here should be switched to
1019          * crtc->state->active once we have proper CRTC states wired up
1020          * for atomic.
1021          */
1022         return intel_crtc->active && crtc->primary->state->fb &&
1023                 intel_crtc->config->base.adjusted_mode.crtc_clock;
1024 }
1025
1026 enum transcoder intel_pipe_to_cpu_transcoder(struct drm_i915_private *dev_priv,
1027                                              enum pipe pipe)
1028 {
1029         struct drm_crtc *crtc = dev_priv->pipe_to_crtc_mapping[pipe];
1030         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
1031
1032         return intel_crtc->config->cpu_transcoder;
1033 }
1034
1035 static bool pipe_dsl_stopped(struct drm_device *dev, enum pipe pipe)
1036 {
1037         struct drm_i915_private *dev_priv = to_i915(dev);
1038         i915_reg_t reg = PIPEDSL(pipe);
1039         u32 line1, line2;
1040         u32 line_mask;
1041
1042         if (IS_GEN2(dev))
1043                 line_mask = DSL_LINEMASK_GEN2;
1044         else
1045                 line_mask = DSL_LINEMASK_GEN3;
1046
1047         line1 = I915_READ(reg) & line_mask;
1048         msleep(5);
1049         line2 = I915_READ(reg) & line_mask;
1050
1051         return line1 == line2;
1052 }
1053
1054 /*
1055  * intel_wait_for_pipe_off - wait for pipe to turn off
1056  * @crtc: crtc whose pipe to wait for
1057  *
1058  * After disabling a pipe, we can't wait for vblank in the usual way,
1059  * spinning on the vblank interrupt status bit, since we won't actually
1060  * see an interrupt when the pipe is disabled.
1061  *
1062  * On Gen4 and above:
1063  *   wait for the pipe register state bit to turn off
1064  *
1065  * Otherwise:
1066  *   wait for the display line value to settle (it usually
1067  *   ends up stopping at the start of the next frame).
1068  *
1069  */
1070 static void intel_wait_for_pipe_off(struct intel_crtc *crtc)
1071 {
1072         struct drm_device *dev = crtc->base.dev;
1073         struct drm_i915_private *dev_priv = to_i915(dev);
1074         enum transcoder cpu_transcoder = crtc->config->cpu_transcoder;
1075         enum pipe pipe = crtc->pipe;
1076
1077         if (INTEL_INFO(dev)->gen >= 4) {
1078                 i915_reg_t reg = PIPECONF(cpu_transcoder);
1079
1080                 /* Wait for the Pipe State to go off */
1081                 if (intel_wait_for_register(dev_priv,
1082                                             reg, I965_PIPECONF_ACTIVE, 0,
1083                                             100))
1084                         WARN(1, "pipe_off wait timed out\n");
1085         } else {
1086                 /* Wait for the display line to settle */
1087                 if (wait_for(pipe_dsl_stopped(dev, pipe), 100))
1088                         WARN(1, "pipe_off wait timed out\n");
1089         }
1090 }
1091
1092 /* Only for pre-ILK configs */
1093 void assert_pll(struct drm_i915_private *dev_priv,
1094                 enum pipe pipe, bool state)
1095 {
1096         u32 val;
1097         bool cur_state;
1098
1099         val = I915_READ(DPLL(pipe));
1100         cur_state = !!(val & DPLL_VCO_ENABLE);
1101         I915_STATE_WARN(cur_state != state,
1102              "PLL state assertion failure (expected %s, current %s)\n",
1103                         onoff(state), onoff(cur_state));
1104 }
1105
1106 /* XXX: the dsi pll is shared between MIPI DSI ports */
1107 void assert_dsi_pll(struct drm_i915_private *dev_priv, bool state)
1108 {
1109         u32 val;
1110         bool cur_state;
1111
1112         mutex_lock(&dev_priv->sb_lock);
1113         val = vlv_cck_read(dev_priv, CCK_REG_DSI_PLL_CONTROL);
1114         mutex_unlock(&dev_priv->sb_lock);
1115
1116         cur_state = val & DSI_PLL_VCO_EN;
1117         I915_STATE_WARN(cur_state != state,
1118              "DSI PLL state assertion failure (expected %s, current %s)\n",
1119                         onoff(state), onoff(cur_state));
1120 }
1121
1122 static void assert_fdi_tx(struct drm_i915_private *dev_priv,
1123                           enum pipe pipe, bool state)
1124 {
1125         bool cur_state;
1126         enum transcoder cpu_transcoder = intel_pipe_to_cpu_transcoder(dev_priv,
1127                                                                       pipe);
1128
1129         if (HAS_DDI(dev_priv)) {
1130                 /* DDI does not have a specific FDI_TX register */
1131                 u32 val = I915_READ(TRANS_DDI_FUNC_CTL(cpu_transcoder));
1132                 cur_state = !!(val & TRANS_DDI_FUNC_ENABLE);
1133         } else {
1134                 u32 val = I915_READ(FDI_TX_CTL(pipe));
1135                 cur_state = !!(val & FDI_TX_ENABLE);
1136         }
1137         I915_STATE_WARN(cur_state != state,
1138              "FDI TX state assertion failure (expected %s, current %s)\n",
1139                         onoff(state), onoff(cur_state));
1140 }
1141 #define assert_fdi_tx_enabled(d, p) assert_fdi_tx(d, p, true)
1142 #define assert_fdi_tx_disabled(d, p) assert_fdi_tx(d, p, false)
1143
1144 static void assert_fdi_rx(struct drm_i915_private *dev_priv,
1145                           enum pipe pipe, bool state)
1146 {
1147         u32 val;
1148         bool cur_state;
1149
1150         val = I915_READ(FDI_RX_CTL(pipe));
1151         cur_state = !!(val & FDI_RX_ENABLE);
1152         I915_STATE_WARN(cur_state != state,
1153              "FDI RX state assertion failure (expected %s, current %s)\n",
1154                         onoff(state), onoff(cur_state));
1155 }
1156 #define assert_fdi_rx_enabled(d, p) assert_fdi_rx(d, p, true)
1157 #define assert_fdi_rx_disabled(d, p) assert_fdi_rx(d, p, false)
1158
1159 static void assert_fdi_tx_pll_enabled(struct drm_i915_private *dev_priv,
1160                                       enum pipe pipe)
1161 {
1162         u32 val;
1163
1164         /* ILK FDI PLL is always enabled */
1165         if (IS_GEN5(dev_priv))
1166                 return;
1167
1168         /* On Haswell, DDI ports are responsible for the FDI PLL setup */
1169         if (HAS_DDI(dev_priv))
1170                 return;
1171
1172         val = I915_READ(FDI_TX_CTL(pipe));
1173         I915_STATE_WARN(!(val & FDI_TX_PLL_ENABLE), "FDI TX PLL assertion failure, should be active but is disabled\n");
1174 }
1175
1176 void assert_fdi_rx_pll(struct drm_i915_private *dev_priv,
1177                        enum pipe pipe, bool state)
1178 {
1179         u32 val;
1180         bool cur_state;
1181
1182         val = I915_READ(FDI_RX_CTL(pipe));
1183         cur_state = !!(val & FDI_RX_PLL_ENABLE);
1184         I915_STATE_WARN(cur_state != state,
1185              "FDI RX PLL assertion failure (expected %s, current %s)\n",
1186                         onoff(state), onoff(cur_state));
1187 }
1188
1189 void assert_panel_unlocked(struct drm_i915_private *dev_priv,
1190                            enum pipe pipe)
1191 {
1192         struct drm_device *dev = &dev_priv->drm;
1193         i915_reg_t pp_reg;
1194         u32 val;
1195         enum pipe panel_pipe = PIPE_A;
1196         bool locked = true;
1197
1198         if (WARN_ON(HAS_DDI(dev)))
1199                 return;
1200
1201         if (HAS_PCH_SPLIT(dev)) {
1202                 u32 port_sel;
1203
1204                 pp_reg = PCH_PP_CONTROL;
1205                 port_sel = I915_READ(PCH_PP_ON_DELAYS) & PANEL_PORT_SELECT_MASK;
1206
1207                 if (port_sel == PANEL_PORT_SELECT_LVDS &&
1208                     I915_READ(PCH_LVDS) & LVDS_PIPEB_SELECT)
1209                         panel_pipe = PIPE_B;
1210                 /* XXX: else fix for eDP */
1211         } else if (IS_VALLEYVIEW(dev) || IS_CHERRYVIEW(dev)) {
1212                 /* presumably write lock depends on pipe, not port select */
1213                 pp_reg = VLV_PIPE_PP_CONTROL(pipe);
1214                 panel_pipe = pipe;
1215         } else {
1216                 pp_reg = PP_CONTROL;
1217                 if (I915_READ(LVDS) & LVDS_PIPEB_SELECT)
1218                         panel_pipe = PIPE_B;
1219         }
1220
1221         val = I915_READ(pp_reg);
1222         if (!(val & PANEL_POWER_ON) ||
1223             ((val & PANEL_UNLOCK_MASK) == PANEL_UNLOCK_REGS))
1224                 locked = false;
1225
1226         I915_STATE_WARN(panel_pipe == pipe && locked,
1227              "panel assertion failure, pipe %c regs locked\n",
1228              pipe_name(pipe));
1229 }
1230
1231 static void assert_cursor(struct drm_i915_private *dev_priv,
1232                           enum pipe pipe, bool state)
1233 {
1234         struct drm_device *dev = &dev_priv->drm;
1235         bool cur_state;
1236
1237         if (IS_845G(dev) || IS_I865G(dev))
1238                 cur_state = I915_READ(CURCNTR(PIPE_A)) & CURSOR_ENABLE;
1239         else
1240                 cur_state = I915_READ(CURCNTR(pipe)) & CURSOR_MODE;
1241
1242         I915_STATE_WARN(cur_state != state,
1243              "cursor on pipe %c assertion failure (expected %s, current %s)\n",
1244                         pipe_name(pipe), onoff(state), onoff(cur_state));
1245 }
1246 #define assert_cursor_enabled(d, p) assert_cursor(d, p, true)
1247 #define assert_cursor_disabled(d, p) assert_cursor(d, p, false)
1248
1249 void assert_pipe(struct drm_i915_private *dev_priv,
1250                  enum pipe pipe, bool state)
1251 {
1252         bool cur_state;
1253         enum transcoder cpu_transcoder = intel_pipe_to_cpu_transcoder(dev_priv,
1254                                                                       pipe);
1255         enum intel_display_power_domain power_domain;
1256
1257         /* if we need the pipe quirk it must be always on */
1258         if ((pipe == PIPE_A && dev_priv->quirks & QUIRK_PIPEA_FORCE) ||
1259             (pipe == PIPE_B && dev_priv->quirks & QUIRK_PIPEB_FORCE))
1260                 state = true;
1261
1262         power_domain = POWER_DOMAIN_TRANSCODER(cpu_transcoder);
1263         if (intel_display_power_get_if_enabled(dev_priv, power_domain)) {
1264                 u32 val = I915_READ(PIPECONF(cpu_transcoder));
1265                 cur_state = !!(val & PIPECONF_ENABLE);
1266
1267                 intel_display_power_put(dev_priv, power_domain);
1268         } else {
1269                 cur_state = false;
1270         }
1271
1272         I915_STATE_WARN(cur_state != state,
1273              "pipe %c assertion failure (expected %s, current %s)\n",
1274                         pipe_name(pipe), onoff(state), onoff(cur_state));
1275 }
1276
1277 static void assert_plane(struct drm_i915_private *dev_priv,
1278                          enum plane plane, bool state)
1279 {
1280         u32 val;
1281         bool cur_state;
1282
1283         val = I915_READ(DSPCNTR(plane));
1284         cur_state = !!(val & DISPLAY_PLANE_ENABLE);
1285         I915_STATE_WARN(cur_state != state,
1286              "plane %c assertion failure (expected %s, current %s)\n",
1287                         plane_name(plane), onoff(state), onoff(cur_state));
1288 }
1289
1290 #define assert_plane_enabled(d, p) assert_plane(d, p, true)
1291 #define assert_plane_disabled(d, p) assert_plane(d, p, false)
1292
1293 static void assert_planes_disabled(struct drm_i915_private *dev_priv,
1294                                    enum pipe pipe)
1295 {
1296         struct drm_device *dev = &dev_priv->drm;
1297         int i;
1298
1299         /* Primary planes are fixed to pipes on gen4+ */
1300         if (INTEL_INFO(dev)->gen >= 4) {
1301                 u32 val = I915_READ(DSPCNTR(pipe));
1302                 I915_STATE_WARN(val & DISPLAY_PLANE_ENABLE,
1303                      "plane %c assertion failure, should be disabled but not\n",
1304                      plane_name(pipe));
1305                 return;
1306         }
1307
1308         /* Need to check both planes against the pipe */
1309         for_each_pipe(dev_priv, i) {
1310                 u32 val = I915_READ(DSPCNTR(i));
1311                 enum pipe cur_pipe = (val & DISPPLANE_SEL_PIPE_MASK) >>
1312                         DISPPLANE_SEL_PIPE_SHIFT;
1313                 I915_STATE_WARN((val & DISPLAY_PLANE_ENABLE) && pipe == cur_pipe,
1314                      "plane %c assertion failure, should be off on pipe %c but is still active\n",
1315                      plane_name(i), pipe_name(pipe));
1316         }
1317 }
1318
1319 static void assert_sprites_disabled(struct drm_i915_private *dev_priv,
1320                                     enum pipe pipe)
1321 {
1322         struct drm_device *dev = &dev_priv->drm;
1323         int sprite;
1324
1325         if (INTEL_INFO(dev)->gen >= 9) {
1326                 for_each_sprite(dev_priv, pipe, sprite) {
1327                         u32 val = I915_READ(PLANE_CTL(pipe, sprite));
1328                         I915_STATE_WARN(val & PLANE_CTL_ENABLE,
1329                              "plane %d assertion failure, should be off on pipe %c but is still active\n",
1330                              sprite, pipe_name(pipe));
1331                 }
1332         } else if (IS_VALLEYVIEW(dev) || IS_CHERRYVIEW(dev)) {
1333                 for_each_sprite(dev_priv, pipe, sprite) {
1334                         u32 val = I915_READ(SPCNTR(pipe, sprite));
1335                         I915_STATE_WARN(val & SP_ENABLE,
1336                              "sprite %c assertion failure, should be off on pipe %c but is still active\n",
1337                              sprite_name(pipe, sprite), pipe_name(pipe));
1338                 }
1339         } else if (INTEL_INFO(dev)->gen >= 7) {
1340                 u32 val = I915_READ(SPRCTL(pipe));
1341                 I915_STATE_WARN(val & SPRITE_ENABLE,
1342                      "sprite %c assertion failure, should be off on pipe %c but is still active\n",
1343                      plane_name(pipe), pipe_name(pipe));
1344         } else if (INTEL_INFO(dev)->gen >= 5) {
1345                 u32 val = I915_READ(DVSCNTR(pipe));
1346                 I915_STATE_WARN(val & DVS_ENABLE,
1347                      "sprite %c assertion failure, should be off on pipe %c but is still active\n",
1348                      plane_name(pipe), pipe_name(pipe));
1349         }
1350 }
1351
1352 static void assert_vblank_disabled(struct drm_crtc *crtc)
1353 {
1354         if (I915_STATE_WARN_ON(drm_crtc_vblank_get(crtc) == 0))
1355                 drm_crtc_vblank_put(crtc);
1356 }
1357
1358 void assert_pch_transcoder_disabled(struct drm_i915_private *dev_priv,
1359                                     enum pipe pipe)
1360 {
1361         u32 val;
1362         bool enabled;
1363
1364         val = I915_READ(PCH_TRANSCONF(pipe));
1365         enabled = !!(val & TRANS_ENABLE);
1366         I915_STATE_WARN(enabled,
1367              "transcoder assertion failed, should be off on pipe %c but is still active\n",
1368              pipe_name(pipe));
1369 }
1370
1371 static bool dp_pipe_enabled(struct drm_i915_private *dev_priv,
1372                             enum pipe pipe, u32 port_sel, u32 val)
1373 {
1374         if ((val & DP_PORT_EN) == 0)
1375                 return false;
1376
1377         if (HAS_PCH_CPT(dev_priv)) {
1378                 u32 trans_dp_ctl = I915_READ(TRANS_DP_CTL(pipe));
1379                 if ((trans_dp_ctl & TRANS_DP_PORT_SEL_MASK) != port_sel)
1380                         return false;
1381         } else if (IS_CHERRYVIEW(dev_priv)) {
1382                 if ((val & DP_PIPE_MASK_CHV) != DP_PIPE_SELECT_CHV(pipe))
1383                         return false;
1384         } else {
1385                 if ((val & DP_PIPE_MASK) != (pipe << 30))
1386                         return false;
1387         }
1388         return true;
1389 }
1390
1391 static bool hdmi_pipe_enabled(struct drm_i915_private *dev_priv,
1392                               enum pipe pipe, u32 val)
1393 {
1394         if ((val & SDVO_ENABLE) == 0)
1395                 return false;
1396
1397         if (HAS_PCH_CPT(dev_priv)) {
1398                 if ((val & SDVO_PIPE_SEL_MASK_CPT) != SDVO_PIPE_SEL_CPT(pipe))
1399                         return false;
1400         } else if (IS_CHERRYVIEW(dev_priv)) {
1401                 if ((val & SDVO_PIPE_SEL_MASK_CHV) != SDVO_PIPE_SEL_CHV(pipe))
1402                         return false;
1403         } else {
1404                 if ((val & SDVO_PIPE_SEL_MASK) != SDVO_PIPE_SEL(pipe))
1405                         return false;
1406         }
1407         return true;
1408 }
1409
1410 static bool lvds_pipe_enabled(struct drm_i915_private *dev_priv,
1411                               enum pipe pipe, u32 val)
1412 {
1413         if ((val & LVDS_PORT_EN) == 0)
1414                 return false;
1415
1416         if (HAS_PCH_CPT(dev_priv)) {
1417                 if ((val & PORT_TRANS_SEL_MASK) != PORT_TRANS_SEL_CPT(pipe))
1418                         return false;
1419         } else {
1420                 if ((val & LVDS_PIPE_MASK) != LVDS_PIPE(pipe))
1421                         return false;
1422         }
1423         return true;
1424 }
1425
1426 static bool adpa_pipe_enabled(struct drm_i915_private *dev_priv,
1427                               enum pipe pipe, u32 val)
1428 {
1429         if ((val & ADPA_DAC_ENABLE) == 0)
1430                 return false;
1431         if (HAS_PCH_CPT(dev_priv)) {
1432                 if ((val & PORT_TRANS_SEL_MASK) != PORT_TRANS_SEL_CPT(pipe))
1433                         return false;
1434         } else {
1435                 if ((val & ADPA_PIPE_SELECT_MASK) != ADPA_PIPE_SELECT(pipe))
1436                         return false;
1437         }
1438         return true;
1439 }
1440
1441 static void assert_pch_dp_disabled(struct drm_i915_private *dev_priv,
1442                                    enum pipe pipe, i915_reg_t reg,
1443                                    u32 port_sel)
1444 {
1445         u32 val = I915_READ(reg);
1446         I915_STATE_WARN(dp_pipe_enabled(dev_priv, pipe, port_sel, val),
1447              "PCH DP (0x%08x) enabled on transcoder %c, should be disabled\n",
1448              i915_mmio_reg_offset(reg), pipe_name(pipe));
1449
1450         I915_STATE_WARN(HAS_PCH_IBX(dev_priv) && (val & DP_PORT_EN) == 0
1451              && (val & DP_PIPEB_SELECT),
1452              "IBX PCH dp port still using transcoder B\n");
1453 }
1454
1455 static void assert_pch_hdmi_disabled(struct drm_i915_private *dev_priv,
1456                                      enum pipe pipe, i915_reg_t reg)
1457 {
1458         u32 val = I915_READ(reg);
1459         I915_STATE_WARN(hdmi_pipe_enabled(dev_priv, pipe, val),
1460              "PCH HDMI (0x%08x) enabled on transcoder %c, should be disabled\n",
1461              i915_mmio_reg_offset(reg), pipe_name(pipe));
1462
1463         I915_STATE_WARN(HAS_PCH_IBX(dev_priv) && (val & SDVO_ENABLE) == 0
1464              && (val & SDVO_PIPE_B_SELECT),
1465              "IBX PCH hdmi port still using transcoder B\n");
1466 }
1467
1468 static void assert_pch_ports_disabled(struct drm_i915_private *dev_priv,
1469                                       enum pipe pipe)
1470 {
1471         u32 val;
1472
1473         assert_pch_dp_disabled(dev_priv, pipe, PCH_DP_B, TRANS_DP_PORT_SEL_B);
1474         assert_pch_dp_disabled(dev_priv, pipe, PCH_DP_C, TRANS_DP_PORT_SEL_C);
1475         assert_pch_dp_disabled(dev_priv, pipe, PCH_DP_D, TRANS_DP_PORT_SEL_D);
1476
1477         val = I915_READ(PCH_ADPA);
1478         I915_STATE_WARN(adpa_pipe_enabled(dev_priv, pipe, val),
1479              "PCH VGA enabled on transcoder %c, should be disabled\n",
1480              pipe_name(pipe));
1481
1482         val = I915_READ(PCH_LVDS);
1483         I915_STATE_WARN(lvds_pipe_enabled(dev_priv, pipe, val),
1484              "PCH LVDS enabled on transcoder %c, should be disabled\n",
1485              pipe_name(pipe));
1486
1487         assert_pch_hdmi_disabled(dev_priv, pipe, PCH_HDMIB);
1488         assert_pch_hdmi_disabled(dev_priv, pipe, PCH_HDMIC);
1489         assert_pch_hdmi_disabled(dev_priv, pipe, PCH_HDMID);
1490 }
1491
1492 static void _vlv_enable_pll(struct intel_crtc *crtc,
1493                             const struct intel_crtc_state *pipe_config)
1494 {
1495         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
1496         enum pipe pipe = crtc->pipe;
1497
1498         I915_WRITE(DPLL(pipe), pipe_config->dpll_hw_state.dpll);
1499         POSTING_READ(DPLL(pipe));
1500         udelay(150);
1501
1502         if (intel_wait_for_register(dev_priv,
1503                                     DPLL(pipe),
1504                                     DPLL_LOCK_VLV,
1505                                     DPLL_LOCK_VLV,
1506                                     1))
1507                 DRM_ERROR("DPLL %d failed to lock\n", pipe);
1508 }
1509
1510 static void vlv_enable_pll(struct intel_crtc *crtc,
1511                            const struct intel_crtc_state *pipe_config)
1512 {
1513         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
1514         enum pipe pipe = crtc->pipe;
1515
1516         assert_pipe_disabled(dev_priv, pipe);
1517
1518         /* PLL is protected by panel, make sure we can write it */
1519         assert_panel_unlocked(dev_priv, pipe);
1520
1521         if (pipe_config->dpll_hw_state.dpll & DPLL_VCO_ENABLE)
1522                 _vlv_enable_pll(crtc, pipe_config);
1523
1524         I915_WRITE(DPLL_MD(pipe), pipe_config->dpll_hw_state.dpll_md);
1525         POSTING_READ(DPLL_MD(pipe));
1526 }
1527
1528
1529 static void _chv_enable_pll(struct intel_crtc *crtc,
1530                             const struct intel_crtc_state *pipe_config)
1531 {
1532         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
1533         enum pipe pipe = crtc->pipe;
1534         enum dpio_channel port = vlv_pipe_to_channel(pipe);
1535         u32 tmp;
1536
1537         mutex_lock(&dev_priv->sb_lock);
1538
1539         /* Enable back the 10bit clock to display controller */
1540         tmp = vlv_dpio_read(dev_priv, pipe, CHV_CMN_DW14(port));
1541         tmp |= DPIO_DCLKP_EN;
1542         vlv_dpio_write(dev_priv, pipe, CHV_CMN_DW14(port), tmp);
1543
1544         mutex_unlock(&dev_priv->sb_lock);
1545
1546         /*
1547          * Need to wait > 100ns between dclkp clock enable bit and PLL enable.
1548          */
1549         udelay(1);
1550
1551         /* Enable PLL */
1552         I915_WRITE(DPLL(pipe), pipe_config->dpll_hw_state.dpll);
1553
1554         /* Check PLL is locked */
1555         if (intel_wait_for_register(dev_priv,
1556                                     DPLL(pipe), DPLL_LOCK_VLV, DPLL_LOCK_VLV,
1557                                     1))
1558                 DRM_ERROR("PLL %d failed to lock\n", pipe);
1559 }
1560
1561 static void chv_enable_pll(struct intel_crtc *crtc,
1562                            const struct intel_crtc_state *pipe_config)
1563 {
1564         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
1565         enum pipe pipe = crtc->pipe;
1566
1567         assert_pipe_disabled(dev_priv, pipe);
1568
1569         /* PLL is protected by panel, make sure we can write it */
1570         assert_panel_unlocked(dev_priv, pipe);
1571
1572         if (pipe_config->dpll_hw_state.dpll & DPLL_VCO_ENABLE)
1573                 _chv_enable_pll(crtc, pipe_config);
1574
1575         if (pipe != PIPE_A) {
1576                 /*
1577                  * WaPixelRepeatModeFixForC0:chv
1578                  *
1579                  * DPLLCMD is AWOL. Use chicken bits to propagate
1580                  * the value from DPLLBMD to either pipe B or C.
1581                  */
1582                 I915_WRITE(CBR4_VLV, pipe == PIPE_B ? CBR_DPLLBMD_PIPE_B : CBR_DPLLBMD_PIPE_C);
1583                 I915_WRITE(DPLL_MD(PIPE_B), pipe_config->dpll_hw_state.dpll_md);
1584                 I915_WRITE(CBR4_VLV, 0);
1585                 dev_priv->chv_dpll_md[pipe] = pipe_config->dpll_hw_state.dpll_md;
1586
1587                 /*
1588                  * DPLLB VGA mode also seems to cause problems.
1589                  * We should always have it disabled.
1590                  */
1591                 WARN_ON((I915_READ(DPLL(PIPE_B)) & DPLL_VGA_MODE_DIS) == 0);
1592         } else {
1593                 I915_WRITE(DPLL_MD(pipe), pipe_config->dpll_hw_state.dpll_md);
1594                 POSTING_READ(DPLL_MD(pipe));
1595         }
1596 }
1597
1598 static int intel_num_dvo_pipes(struct drm_device *dev)
1599 {
1600         struct intel_crtc *crtc;
1601         int count = 0;
1602
1603         for_each_intel_crtc(dev, crtc) {
1604                 count += crtc->base.state->active &&
1605                         intel_crtc_has_type(crtc->config, INTEL_OUTPUT_DVO);
1606         }
1607
1608         return count;
1609 }
1610
1611 static void i9xx_enable_pll(struct intel_crtc *crtc)
1612 {
1613         struct drm_device *dev = crtc->base.dev;
1614         struct drm_i915_private *dev_priv = to_i915(dev);
1615         i915_reg_t reg = DPLL(crtc->pipe);
1616         u32 dpll = crtc->config->dpll_hw_state.dpll;
1617
1618         assert_pipe_disabled(dev_priv, crtc->pipe);
1619
1620         /* PLL is protected by panel, make sure we can write it */
1621         if (IS_MOBILE(dev) && !IS_I830(dev))
1622                 assert_panel_unlocked(dev_priv, crtc->pipe);
1623
1624         /* Enable DVO 2x clock on both PLLs if necessary */
1625         if (IS_I830(dev) && intel_num_dvo_pipes(dev) > 0) {
1626                 /*
1627                  * It appears to be important that we don't enable this
1628                  * for the current pipe before otherwise configuring the
1629                  * PLL. No idea how this should be handled if multiple
1630                  * DVO outputs are enabled simultaneosly.
1631                  */
1632                 dpll |= DPLL_DVO_2X_MODE;
1633                 I915_WRITE(DPLL(!crtc->pipe),
1634                            I915_READ(DPLL(!crtc->pipe)) | DPLL_DVO_2X_MODE);
1635         }
1636
1637         /*
1638          * Apparently we need to have VGA mode enabled prior to changing
1639          * the P1/P2 dividers. Otherwise the DPLL will keep using the old
1640          * dividers, even though the register value does change.
1641          */
1642         I915_WRITE(reg, 0);
1643
1644         I915_WRITE(reg, dpll);
1645
1646         /* Wait for the clocks to stabilize. */
1647         POSTING_READ(reg);
1648         udelay(150);
1649
1650         if (INTEL_INFO(dev)->gen >= 4) {
1651                 I915_WRITE(DPLL_MD(crtc->pipe),
1652                            crtc->config->dpll_hw_state.dpll_md);
1653         } else {
1654                 /* The pixel multiplier can only be updated once the
1655                  * DPLL is enabled and the clocks are stable.
1656                  *
1657                  * So write it again.
1658                  */
1659                 I915_WRITE(reg, dpll);
1660         }
1661
1662         /* We do this three times for luck */
1663         I915_WRITE(reg, dpll);
1664         POSTING_READ(reg);
1665         udelay(150); /* wait for warmup */
1666         I915_WRITE(reg, dpll);
1667         POSTING_READ(reg);
1668         udelay(150); /* wait for warmup */
1669         I915_WRITE(reg, dpll);
1670         POSTING_READ(reg);
1671         udelay(150); /* wait for warmup */
1672 }
1673
1674 /**
1675  * i9xx_disable_pll - disable a PLL
1676  * @dev_priv: i915 private structure
1677  * @pipe: pipe PLL to disable
1678  *
1679  * Disable the PLL for @pipe, making sure the pipe is off first.
1680  *
1681  * Note!  This is for pre-ILK only.
1682  */
1683 static void i9xx_disable_pll(struct intel_crtc *crtc)
1684 {
1685         struct drm_device *dev = crtc->base.dev;
1686         struct drm_i915_private *dev_priv = to_i915(dev);
1687         enum pipe pipe = crtc->pipe;
1688
1689         /* Disable DVO 2x clock on both PLLs if necessary */
1690         if (IS_I830(dev) &&
1691             intel_crtc_has_type(crtc->config, INTEL_OUTPUT_DVO) &&
1692             !intel_num_dvo_pipes(dev)) {
1693                 I915_WRITE(DPLL(PIPE_B),
1694                            I915_READ(DPLL(PIPE_B)) & ~DPLL_DVO_2X_MODE);
1695                 I915_WRITE(DPLL(PIPE_A),
1696                            I915_READ(DPLL(PIPE_A)) & ~DPLL_DVO_2X_MODE);
1697         }
1698
1699         /* Don't disable pipe or pipe PLLs if needed */
1700         if ((pipe == PIPE_A && dev_priv->quirks & QUIRK_PIPEA_FORCE) ||
1701             (pipe == PIPE_B && dev_priv->quirks & QUIRK_PIPEB_FORCE))
1702                 return;
1703
1704         /* Make sure the pipe isn't still relying on us */
1705         assert_pipe_disabled(dev_priv, pipe);
1706
1707         I915_WRITE(DPLL(pipe), DPLL_VGA_MODE_DIS);
1708         POSTING_READ(DPLL(pipe));
1709 }
1710
1711 static void vlv_disable_pll(struct drm_i915_private *dev_priv, enum pipe pipe)
1712 {
1713         u32 val;
1714
1715         /* Make sure the pipe isn't still relying on us */
1716         assert_pipe_disabled(dev_priv, pipe);
1717
1718         val = DPLL_INTEGRATED_REF_CLK_VLV |
1719                 DPLL_REF_CLK_ENABLE_VLV | DPLL_VGA_MODE_DIS;
1720         if (pipe != PIPE_A)
1721                 val |= DPLL_INTEGRATED_CRI_CLK_VLV;
1722
1723         I915_WRITE(DPLL(pipe), val);
1724         POSTING_READ(DPLL(pipe));
1725 }
1726
1727 static void chv_disable_pll(struct drm_i915_private *dev_priv, enum pipe pipe)
1728 {
1729         enum dpio_channel port = vlv_pipe_to_channel(pipe);
1730         u32 val;
1731
1732         /* Make sure the pipe isn't still relying on us */
1733         assert_pipe_disabled(dev_priv, pipe);
1734
1735         val = DPLL_SSC_REF_CLK_CHV |
1736                 DPLL_REF_CLK_ENABLE_VLV | DPLL_VGA_MODE_DIS;
1737         if (pipe != PIPE_A)
1738                 val |= DPLL_INTEGRATED_CRI_CLK_VLV;
1739
1740         I915_WRITE(DPLL(pipe), val);
1741         POSTING_READ(DPLL(pipe));
1742
1743         mutex_lock(&dev_priv->sb_lock);
1744
1745         /* Disable 10bit clock to display controller */
1746         val = vlv_dpio_read(dev_priv, pipe, CHV_CMN_DW14(port));
1747         val &= ~DPIO_DCLKP_EN;
1748         vlv_dpio_write(dev_priv, pipe, CHV_CMN_DW14(port), val);
1749
1750         mutex_unlock(&dev_priv->sb_lock);
1751 }
1752
1753 void vlv_wait_port_ready(struct drm_i915_private *dev_priv,
1754                          struct intel_digital_port *dport,
1755                          unsigned int expected_mask)
1756 {
1757         u32 port_mask;
1758         i915_reg_t dpll_reg;
1759
1760         switch (dport->port) {
1761         case PORT_B:
1762                 port_mask = DPLL_PORTB_READY_MASK;
1763                 dpll_reg = DPLL(0);
1764                 break;
1765         case PORT_C:
1766                 port_mask = DPLL_PORTC_READY_MASK;
1767                 dpll_reg = DPLL(0);
1768                 expected_mask <<= 4;
1769                 break;
1770         case PORT_D:
1771                 port_mask = DPLL_PORTD_READY_MASK;
1772                 dpll_reg = DPIO_PHY_STATUS;
1773                 break;
1774         default:
1775                 BUG();
1776         }
1777
1778         if (intel_wait_for_register(dev_priv,
1779                                     dpll_reg, port_mask, expected_mask,
1780                                     1000))
1781                 WARN(1, "timed out waiting for port %c ready: got 0x%x, expected 0x%x\n",
1782                      port_name(dport->port), I915_READ(dpll_reg) & port_mask, expected_mask);
1783 }
1784
1785 static void ironlake_enable_pch_transcoder(struct drm_i915_private *dev_priv,
1786                                            enum pipe pipe)
1787 {
1788         struct drm_device *dev = &dev_priv->drm;
1789         struct drm_crtc *crtc = dev_priv->pipe_to_crtc_mapping[pipe];
1790         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
1791         i915_reg_t reg;
1792         uint32_t val, pipeconf_val;
1793
1794         /* Make sure PCH DPLL is enabled */
1795         assert_shared_dpll_enabled(dev_priv, intel_crtc->config->shared_dpll);
1796
1797         /* FDI must be feeding us bits for PCH ports */
1798         assert_fdi_tx_enabled(dev_priv, pipe);
1799         assert_fdi_rx_enabled(dev_priv, pipe);
1800
1801         if (HAS_PCH_CPT(dev)) {
1802                 /* Workaround: Set the timing override bit before enabling the
1803                  * pch transcoder. */
1804                 reg = TRANS_CHICKEN2(pipe);
1805                 val = I915_READ(reg);
1806                 val |= TRANS_CHICKEN2_TIMING_OVERRIDE;
1807                 I915_WRITE(reg, val);
1808         }
1809
1810         reg = PCH_TRANSCONF(pipe);
1811         val = I915_READ(reg);
1812         pipeconf_val = I915_READ(PIPECONF(pipe));
1813
1814         if (HAS_PCH_IBX(dev_priv)) {
1815                 /*
1816                  * Make the BPC in transcoder be consistent with
1817                  * that in pipeconf reg. For HDMI we must use 8bpc
1818                  * here for both 8bpc and 12bpc.
1819                  */
1820                 val &= ~PIPECONF_BPC_MASK;
1821                 if (intel_crtc_has_type(intel_crtc->config, INTEL_OUTPUT_HDMI))
1822                         val |= PIPECONF_8BPC;
1823                 else
1824                         val |= pipeconf_val & PIPECONF_BPC_MASK;
1825         }
1826
1827         val &= ~TRANS_INTERLACE_MASK;
1828         if ((pipeconf_val & PIPECONF_INTERLACE_MASK) == PIPECONF_INTERLACED_ILK)
1829                 if (HAS_PCH_IBX(dev_priv) &&
1830                     intel_crtc_has_type(intel_crtc->config, INTEL_OUTPUT_SDVO))
1831                         val |= TRANS_LEGACY_INTERLACED_ILK;
1832                 else
1833                         val |= TRANS_INTERLACED;
1834         else
1835                 val |= TRANS_PROGRESSIVE;
1836
1837         I915_WRITE(reg, val | TRANS_ENABLE);
1838         if (intel_wait_for_register(dev_priv,
1839                                     reg, TRANS_STATE_ENABLE, TRANS_STATE_ENABLE,
1840                                     100))
1841                 DRM_ERROR("failed to enable transcoder %c\n", pipe_name(pipe));
1842 }
1843
1844 static void lpt_enable_pch_transcoder(struct drm_i915_private *dev_priv,
1845                                       enum transcoder cpu_transcoder)
1846 {
1847         u32 val, pipeconf_val;
1848
1849         /* FDI must be feeding us bits for PCH ports */
1850         assert_fdi_tx_enabled(dev_priv, (enum pipe) cpu_transcoder);
1851         assert_fdi_rx_enabled(dev_priv, TRANSCODER_A);
1852
1853         /* Workaround: set timing override bit. */
1854         val = I915_READ(TRANS_CHICKEN2(PIPE_A));
1855         val |= TRANS_CHICKEN2_TIMING_OVERRIDE;
1856         I915_WRITE(TRANS_CHICKEN2(PIPE_A), val);
1857
1858         val = TRANS_ENABLE;
1859         pipeconf_val = I915_READ(PIPECONF(cpu_transcoder));
1860
1861         if ((pipeconf_val & PIPECONF_INTERLACE_MASK_HSW) ==
1862             PIPECONF_INTERLACED_ILK)
1863                 val |= TRANS_INTERLACED;
1864         else
1865                 val |= TRANS_PROGRESSIVE;
1866
1867         I915_WRITE(LPT_TRANSCONF, val);
1868         if (intel_wait_for_register(dev_priv,
1869                                     LPT_TRANSCONF,
1870                                     TRANS_STATE_ENABLE,
1871                                     TRANS_STATE_ENABLE,
1872                                     100))
1873                 DRM_ERROR("Failed to enable PCH transcoder\n");
1874 }
1875
1876 static void ironlake_disable_pch_transcoder(struct drm_i915_private *dev_priv,
1877                                             enum pipe pipe)
1878 {
1879         struct drm_device *dev = &dev_priv->drm;
1880         i915_reg_t reg;
1881         uint32_t val;
1882
1883         /* FDI relies on the transcoder */
1884         assert_fdi_tx_disabled(dev_priv, pipe);
1885         assert_fdi_rx_disabled(dev_priv, pipe);
1886
1887         /* Ports must be off as well */
1888         assert_pch_ports_disabled(dev_priv, pipe);
1889
1890         reg = PCH_TRANSCONF(pipe);
1891         val = I915_READ(reg);
1892         val &= ~TRANS_ENABLE;
1893         I915_WRITE(reg, val);
1894         /* wait for PCH transcoder off, transcoder state */
1895         if (intel_wait_for_register(dev_priv,
1896                                     reg, TRANS_STATE_ENABLE, 0,
1897                                     50))
1898                 DRM_ERROR("failed to disable transcoder %c\n", pipe_name(pipe));
1899
1900         if (HAS_PCH_CPT(dev)) {
1901                 /* Workaround: Clear the timing override chicken bit again. */
1902                 reg = TRANS_CHICKEN2(pipe);
1903                 val = I915_READ(reg);
1904                 val &= ~TRANS_CHICKEN2_TIMING_OVERRIDE;
1905                 I915_WRITE(reg, val);
1906         }
1907 }
1908
1909 static void lpt_disable_pch_transcoder(struct drm_i915_private *dev_priv)
1910 {
1911         u32 val;
1912
1913         val = I915_READ(LPT_TRANSCONF);
1914         val &= ~TRANS_ENABLE;
1915         I915_WRITE(LPT_TRANSCONF, val);
1916         /* wait for PCH transcoder off, transcoder state */
1917         if (intel_wait_for_register(dev_priv,
1918                                     LPT_TRANSCONF, TRANS_STATE_ENABLE, 0,
1919                                     50))
1920                 DRM_ERROR("Failed to disable PCH transcoder\n");
1921
1922         /* Workaround: clear timing override bit. */
1923         val = I915_READ(TRANS_CHICKEN2(PIPE_A));
1924         val &= ~TRANS_CHICKEN2_TIMING_OVERRIDE;
1925         I915_WRITE(TRANS_CHICKEN2(PIPE_A), val);
1926 }
1927
1928 /**
1929  * intel_enable_pipe - enable a pipe, asserting requirements
1930  * @crtc: crtc responsible for the pipe
1931  *
1932  * Enable @crtc's pipe, making sure that various hardware specific requirements
1933  * are met, if applicable, e.g. PLL enabled, LVDS pairs enabled, etc.
1934  */
1935 static void intel_enable_pipe(struct intel_crtc *crtc)
1936 {
1937         struct drm_device *dev = crtc->base.dev;
1938         struct drm_i915_private *dev_priv = to_i915(dev);
1939         enum pipe pipe = crtc->pipe;
1940         enum transcoder cpu_transcoder = crtc->config->cpu_transcoder;
1941         enum pipe pch_transcoder;
1942         i915_reg_t reg;
1943         u32 val;
1944
1945         DRM_DEBUG_KMS("enabling pipe %c\n", pipe_name(pipe));
1946
1947         assert_planes_disabled(dev_priv, pipe);
1948         assert_cursor_disabled(dev_priv, pipe);
1949         assert_sprites_disabled(dev_priv, pipe);
1950
1951         if (HAS_PCH_LPT(dev_priv))
1952                 pch_transcoder = TRANSCODER_A;
1953         else
1954                 pch_transcoder = pipe;
1955
1956         /*
1957          * A pipe without a PLL won't actually be able to drive bits from
1958          * a plane.  On ILK+ the pipe PLLs are integrated, so we don't
1959          * need the check.
1960          */
1961         if (HAS_GMCH_DISPLAY(dev_priv))
1962                 if (intel_crtc_has_type(crtc->config, INTEL_OUTPUT_DSI))
1963                         assert_dsi_pll_enabled(dev_priv);
1964                 else
1965                         assert_pll_enabled(dev_priv, pipe);
1966         else {
1967                 if (crtc->config->has_pch_encoder) {
1968                         /* if driving the PCH, we need FDI enabled */
1969                         assert_fdi_rx_pll_enabled(dev_priv, pch_transcoder);
1970                         assert_fdi_tx_pll_enabled(dev_priv,
1971                                                   (enum pipe) cpu_transcoder);
1972                 }
1973                 /* FIXME: assert CPU port conditions for SNB+ */
1974         }
1975
1976         reg = PIPECONF(cpu_transcoder);
1977         val = I915_READ(reg);
1978         if (val & PIPECONF_ENABLE) {
1979                 WARN_ON(!((pipe == PIPE_A && dev_priv->quirks & QUIRK_PIPEA_FORCE) ||
1980                           (pipe == PIPE_B && dev_priv->quirks & QUIRK_PIPEB_FORCE)));
1981                 return;
1982         }
1983
1984         I915_WRITE(reg, val | PIPECONF_ENABLE);
1985         POSTING_READ(reg);
1986
1987         /*
1988          * Until the pipe starts DSL will read as 0, which would cause
1989          * an apparent vblank timestamp jump, which messes up also the
1990          * frame count when it's derived from the timestamps. So let's
1991          * wait for the pipe to start properly before we call
1992          * drm_crtc_vblank_on()
1993          */
1994         if (dev->max_vblank_count == 0 &&
1995             wait_for(intel_get_crtc_scanline(crtc) != crtc->scanline_offset, 50))
1996                 DRM_ERROR("pipe %c didn't start\n", pipe_name(pipe));
1997 }
1998
1999 /**
2000  * intel_disable_pipe - disable a pipe, asserting requirements
2001  * @crtc: crtc whose pipes is to be disabled
2002  *
2003  * Disable the pipe of @crtc, making sure that various hardware
2004  * specific requirements are met, if applicable, e.g. plane
2005  * disabled, panel fitter off, etc.
2006  *
2007  * Will wait until the pipe has shut down before returning.
2008  */
2009 static void intel_disable_pipe(struct intel_crtc *crtc)
2010 {
2011         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
2012         enum transcoder cpu_transcoder = crtc->config->cpu_transcoder;
2013         enum pipe pipe = crtc->pipe;
2014         i915_reg_t reg;
2015         u32 val;
2016
2017         DRM_DEBUG_KMS("disabling pipe %c\n", pipe_name(pipe));
2018
2019         /*
2020          * Make sure planes won't keep trying to pump pixels to us,
2021          * or we might hang the display.
2022          */
2023         assert_planes_disabled(dev_priv, pipe);
2024         assert_cursor_disabled(dev_priv, pipe);
2025         assert_sprites_disabled(dev_priv, pipe);
2026
2027         reg = PIPECONF(cpu_transcoder);
2028         val = I915_READ(reg);
2029         if ((val & PIPECONF_ENABLE) == 0)
2030                 return;
2031
2032         /*
2033          * Double wide has implications for planes
2034          * so best keep it disabled when not needed.
2035          */
2036         if (crtc->config->double_wide)
2037                 val &= ~PIPECONF_DOUBLE_WIDE;
2038
2039         /* Don't disable pipe or pipe PLLs if needed */
2040         if (!(pipe == PIPE_A && dev_priv->quirks & QUIRK_PIPEA_FORCE) &&
2041             !(pipe == PIPE_B && dev_priv->quirks & QUIRK_PIPEB_FORCE))
2042                 val &= ~PIPECONF_ENABLE;
2043
2044         I915_WRITE(reg, val);
2045         if ((val & PIPECONF_ENABLE) == 0)
2046                 intel_wait_for_pipe_off(crtc);
2047 }
2048
2049 static unsigned int intel_tile_size(const struct drm_i915_private *dev_priv)
2050 {
2051         return IS_GEN2(dev_priv) ? 2048 : 4096;
2052 }
2053
2054 static unsigned int intel_tile_width_bytes(const struct drm_i915_private *dev_priv,
2055                                            uint64_t fb_modifier, unsigned int cpp)
2056 {
2057         switch (fb_modifier) {
2058         case DRM_FORMAT_MOD_NONE:
2059                 return cpp;
2060         case I915_FORMAT_MOD_X_TILED:
2061                 if (IS_GEN2(dev_priv))
2062                         return 128;
2063                 else
2064                         return 512;
2065         case I915_FORMAT_MOD_Y_TILED:
2066                 if (IS_GEN2(dev_priv) || HAS_128_BYTE_Y_TILING(dev_priv))
2067                         return 128;
2068                 else
2069                         return 512;
2070         case I915_FORMAT_MOD_Yf_TILED:
2071                 switch (cpp) {
2072                 case 1:
2073                         return 64;
2074                 case 2:
2075                 case 4:
2076                         return 128;
2077                 case 8:
2078                 case 16:
2079                         return 256;
2080                 default:
2081                         MISSING_CASE(cpp);
2082                         return cpp;
2083                 }
2084                 break;
2085         default:
2086                 MISSING_CASE(fb_modifier);
2087                 return cpp;
2088         }
2089 }
2090
2091 unsigned int intel_tile_height(const struct drm_i915_private *dev_priv,
2092                                uint64_t fb_modifier, unsigned int cpp)
2093 {
2094         if (fb_modifier == DRM_FORMAT_MOD_NONE)
2095                 return 1;
2096         else
2097                 return intel_tile_size(dev_priv) /
2098                         intel_tile_width_bytes(dev_priv, fb_modifier, cpp);
2099 }
2100
2101 /* Return the tile dimensions in pixel units */
2102 static void intel_tile_dims(const struct drm_i915_private *dev_priv,
2103                             unsigned int *tile_width,
2104                             unsigned int *tile_height,
2105                             uint64_t fb_modifier,
2106                             unsigned int cpp)
2107 {
2108         unsigned int tile_width_bytes =
2109                 intel_tile_width_bytes(dev_priv, fb_modifier, cpp);
2110
2111         *tile_width = tile_width_bytes / cpp;
2112         *tile_height = intel_tile_size(dev_priv) / tile_width_bytes;
2113 }
2114
2115 unsigned int
2116 intel_fb_align_height(struct drm_device *dev, unsigned int height,
2117                       uint32_t pixel_format, uint64_t fb_modifier)
2118 {
2119         unsigned int cpp = drm_format_plane_cpp(pixel_format, 0);
2120         unsigned int tile_height = intel_tile_height(to_i915(dev), fb_modifier, cpp);
2121
2122         return ALIGN(height, tile_height);
2123 }
2124
2125 unsigned int intel_rotation_info_size(const struct intel_rotation_info *rot_info)
2126 {
2127         unsigned int size = 0;
2128         int i;
2129
2130         for (i = 0 ; i < ARRAY_SIZE(rot_info->plane); i++)
2131                 size += rot_info->plane[i].width * rot_info->plane[i].height;
2132
2133         return size;
2134 }
2135
2136 static void
2137 intel_fill_fb_ggtt_view(struct i915_ggtt_view *view,
2138                         const struct drm_framebuffer *fb,
2139                         unsigned int rotation)
2140 {
2141         if (intel_rotation_90_or_270(rotation)) {
2142                 *view = i915_ggtt_view_rotated;
2143                 view->params.rotated = to_intel_framebuffer(fb)->rot_info;
2144         } else {
2145                 *view = i915_ggtt_view_normal;
2146         }
2147 }
2148
2149 static void
2150 intel_fill_fb_info(struct drm_i915_private *dev_priv,
2151                    struct drm_framebuffer *fb)
2152 {
2153         struct intel_rotation_info *info = &to_intel_framebuffer(fb)->rot_info;
2154         unsigned int tile_size, tile_width, tile_height, cpp;
2155
2156         tile_size = intel_tile_size(dev_priv);
2157
2158         cpp = drm_format_plane_cpp(fb->pixel_format, 0);
2159         intel_tile_dims(dev_priv, &tile_width, &tile_height,
2160                         fb->modifier[0], cpp);
2161
2162         info->plane[0].width = DIV_ROUND_UP(fb->pitches[0], tile_width * cpp);
2163         info->plane[0].height = DIV_ROUND_UP(fb->height, tile_height);
2164
2165         if (info->pixel_format == DRM_FORMAT_NV12) {
2166                 cpp = drm_format_plane_cpp(fb->pixel_format, 1);
2167                 intel_tile_dims(dev_priv, &tile_width, &tile_height,
2168                                 fb->modifier[1], cpp);
2169
2170                 info->uv_offset = fb->offsets[1];
2171                 info->plane[1].width = DIV_ROUND_UP(fb->pitches[1], tile_width * cpp);
2172                 info->plane[1].height = DIV_ROUND_UP(fb->height / 2, tile_height);
2173         }
2174 }
2175
2176 static unsigned int intel_linear_alignment(const struct drm_i915_private *dev_priv)
2177 {
2178         if (INTEL_INFO(dev_priv)->gen >= 9)
2179                 return 256 * 1024;
2180         else if (IS_BROADWATER(dev_priv) || IS_CRESTLINE(dev_priv) ||
2181                  IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv))
2182                 return 128 * 1024;
2183         else if (INTEL_INFO(dev_priv)->gen >= 4)
2184                 return 4 * 1024;
2185         else
2186                 return 0;
2187 }
2188
2189 static unsigned int intel_surf_alignment(const struct drm_i915_private *dev_priv,
2190                                          uint64_t fb_modifier)
2191 {
2192         switch (fb_modifier) {
2193         case DRM_FORMAT_MOD_NONE:
2194                 return intel_linear_alignment(dev_priv);
2195         case I915_FORMAT_MOD_X_TILED:
2196                 if (INTEL_INFO(dev_priv)->gen >= 9)
2197                         return 256 * 1024;
2198                 return 0;
2199         case I915_FORMAT_MOD_Y_TILED:
2200         case I915_FORMAT_MOD_Yf_TILED:
2201                 return 1 * 1024 * 1024;
2202         default:
2203                 MISSING_CASE(fb_modifier);
2204                 return 0;
2205         }
2206 }
2207
2208 int
2209 intel_pin_and_fence_fb_obj(struct drm_framebuffer *fb,
2210                            unsigned int rotation)
2211 {
2212         struct drm_device *dev = fb->dev;
2213         struct drm_i915_private *dev_priv = to_i915(dev);
2214         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
2215         struct i915_ggtt_view view;
2216         u32 alignment;
2217         int ret;
2218
2219         WARN_ON(!mutex_is_locked(&dev->struct_mutex));
2220
2221         alignment = intel_surf_alignment(dev_priv, fb->modifier[0]);
2222
2223         intel_fill_fb_ggtt_view(&view, fb, rotation);
2224
2225         /* Note that the w/a also requires 64 PTE of padding following the
2226          * bo. We currently fill all unused PTE with the shadow page and so
2227          * we should always have valid PTE following the scanout preventing
2228          * the VT-d warning.
2229          */
2230         if (intel_scanout_needs_vtd_wa(dev_priv) && alignment < 256 * 1024)
2231                 alignment = 256 * 1024;
2232
2233         /*
2234          * Global gtt pte registers are special registers which actually forward
2235          * writes to a chunk of system memory. Which means that there is no risk
2236          * that the register values disappear as soon as we call
2237          * intel_runtime_pm_put(), so it is correct to wrap only the
2238          * pin/unpin/fence and not more.
2239          */
2240         intel_runtime_pm_get(dev_priv);
2241
2242         ret = i915_gem_object_pin_to_display_plane(obj, alignment,
2243                                                    &view);
2244         if (ret)
2245                 goto err_pm;
2246
2247         /* Install a fence for tiled scan-out. Pre-i965 always needs a
2248          * fence, whereas 965+ only requires a fence if using
2249          * framebuffer compression.  For simplicity, we always install
2250          * a fence as the cost is not that onerous.
2251          */
2252         if (view.type == I915_GGTT_VIEW_NORMAL) {
2253                 ret = i915_gem_object_get_fence(obj);
2254                 if (ret == -EDEADLK) {
2255                         /*
2256                          * -EDEADLK means there are no free fences
2257                          * no pending flips.
2258                          *
2259                          * This is propagated to atomic, but it uses
2260                          * -EDEADLK to force a locking recovery, so
2261                          * change the returned error to -EBUSY.
2262                          */
2263                         ret = -EBUSY;
2264                         goto err_unpin;
2265                 } else if (ret)
2266                         goto err_unpin;
2267
2268                 i915_gem_object_pin_fence(obj);
2269         }
2270
2271         intel_runtime_pm_put(dev_priv);
2272         return 0;
2273
2274 err_unpin:
2275         i915_gem_object_unpin_from_display_plane(obj, &view);
2276 err_pm:
2277         intel_runtime_pm_put(dev_priv);
2278         return ret;
2279 }
2280
2281 void intel_unpin_fb_obj(struct drm_framebuffer *fb, unsigned int rotation)
2282 {
2283         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
2284         struct i915_ggtt_view view;
2285
2286         WARN_ON(!mutex_is_locked(&obj->base.dev->struct_mutex));
2287
2288         intel_fill_fb_ggtt_view(&view, fb, rotation);
2289
2290         if (view.type == I915_GGTT_VIEW_NORMAL)
2291                 i915_gem_object_unpin_fence(obj);
2292
2293         i915_gem_object_unpin_from_display_plane(obj, &view);
2294 }
2295
2296 /*
2297  * Adjust the tile offset by moving the difference into
2298  * the x/y offsets.
2299  *
2300  * Input tile dimensions and pitch must already be
2301  * rotated to match x and y, and in pixel units.
2302  */
2303 static u32 intel_adjust_tile_offset(int *x, int *y,
2304                                     unsigned int tile_width,
2305                                     unsigned int tile_height,
2306                                     unsigned int tile_size,
2307                                     unsigned int pitch_tiles,
2308                                     u32 old_offset,
2309                                     u32 new_offset)
2310 {
2311         unsigned int tiles;
2312
2313         WARN_ON(old_offset & (tile_size - 1));
2314         WARN_ON(new_offset & (tile_size - 1));
2315         WARN_ON(new_offset > old_offset);
2316
2317         tiles = (old_offset - new_offset) / tile_size;
2318
2319         *y += tiles / pitch_tiles * tile_height;
2320         *x += tiles % pitch_tiles * tile_width;
2321
2322         return new_offset;
2323 }
2324
2325 /*
2326  * Computes the linear offset to the base tile and adjusts
2327  * x, y. bytes per pixel is assumed to be a power-of-two.
2328  *
2329  * In the 90/270 rotated case, x and y are assumed
2330  * to be already rotated to match the rotated GTT view, and
2331  * pitch is the tile_height aligned framebuffer height.
2332  */
2333 u32 intel_compute_tile_offset(int *x, int *y,
2334                               const struct drm_framebuffer *fb, int plane,
2335                               unsigned int pitch,
2336                               unsigned int rotation)
2337 {
2338         const struct drm_i915_private *dev_priv = to_i915(fb->dev);
2339         uint64_t fb_modifier = fb->modifier[plane];
2340         unsigned int cpp = drm_format_plane_cpp(fb->pixel_format, plane);
2341         u32 offset, offset_aligned, alignment;
2342
2343         alignment = intel_surf_alignment(dev_priv, fb_modifier);
2344         if (alignment)
2345                 alignment--;
2346
2347         if (fb_modifier != DRM_FORMAT_MOD_NONE) {
2348                 unsigned int tile_size, tile_width, tile_height;
2349                 unsigned int tile_rows, tiles, pitch_tiles;
2350
2351                 tile_size = intel_tile_size(dev_priv);
2352                 intel_tile_dims(dev_priv, &tile_width, &tile_height,
2353                                 fb_modifier, cpp);
2354
2355                 if (intel_rotation_90_or_270(rotation)) {
2356                         pitch_tiles = pitch / tile_height;
2357                         swap(tile_width, tile_height);
2358                 } else {
2359                         pitch_tiles = pitch / (tile_width * cpp);
2360                 }
2361
2362                 tile_rows = *y / tile_height;
2363                 *y %= tile_height;
2364
2365                 tiles = *x / tile_width;
2366                 *x %= tile_width;
2367
2368                 offset = (tile_rows * pitch_tiles + tiles) * tile_size;
2369                 offset_aligned = offset & ~alignment;
2370
2371                 intel_adjust_tile_offset(x, y, tile_width, tile_height,
2372                                          tile_size, pitch_tiles,
2373                                          offset, offset_aligned);
2374         } else {
2375                 offset = *y * pitch + *x * cpp;
2376                 offset_aligned = offset & ~alignment;
2377
2378                 *y = (offset & alignment) / pitch;
2379                 *x = ((offset & alignment) - *y * pitch) / cpp;
2380         }
2381
2382         return offset_aligned;
2383 }
2384
2385 static int i9xx_format_to_fourcc(int format)
2386 {
2387         switch (format) {
2388         case DISPPLANE_8BPP:
2389                 return DRM_FORMAT_C8;
2390         case DISPPLANE_BGRX555:
2391                 return DRM_FORMAT_XRGB1555;
2392         case DISPPLANE_BGRX565:
2393                 return DRM_FORMAT_RGB565;
2394         default:
2395         case DISPPLANE_BGRX888:
2396                 return DRM_FORMAT_XRGB8888;
2397         case DISPPLANE_RGBX888:
2398                 return DRM_FORMAT_XBGR8888;
2399         case DISPPLANE_BGRX101010:
2400                 return DRM_FORMAT_XRGB2101010;
2401         case DISPPLANE_RGBX101010:
2402                 return DRM_FORMAT_XBGR2101010;
2403         }
2404 }
2405
2406 static int skl_format_to_fourcc(int format, bool rgb_order, bool alpha)
2407 {
2408         switch (format) {
2409         case PLANE_CTL_FORMAT_RGB_565:
2410                 return DRM_FORMAT_RGB565;
2411         default:
2412         case PLANE_CTL_FORMAT_XRGB_8888:
2413                 if (rgb_order) {
2414                         if (alpha)
2415                                 return DRM_FORMAT_ABGR8888;
2416                         else
2417                                 return DRM_FORMAT_XBGR8888;
2418                 } else {
2419                         if (alpha)
2420                                 return DRM_FORMAT_ARGB8888;
2421                         else
2422                                 return DRM_FORMAT_XRGB8888;
2423                 }
2424         case PLANE_CTL_FORMAT_XRGB_2101010:
2425                 if (rgb_order)
2426                         return DRM_FORMAT_XBGR2101010;
2427                 else
2428                         return DRM_FORMAT_XRGB2101010;
2429         }
2430 }
2431
2432 static bool
2433 intel_alloc_initial_plane_obj(struct intel_crtc *crtc,
2434                               struct intel_initial_plane_config *plane_config)
2435 {
2436         struct drm_device *dev = crtc->base.dev;
2437         struct drm_i915_private *dev_priv = to_i915(dev);
2438         struct i915_ggtt *ggtt = &dev_priv->ggtt;
2439         struct drm_i915_gem_object *obj = NULL;
2440         struct drm_mode_fb_cmd2 mode_cmd = { 0 };
2441         struct drm_framebuffer *fb = &plane_config->fb->base;
2442         u32 base_aligned = round_down(plane_config->base, PAGE_SIZE);
2443         u32 size_aligned = round_up(plane_config->base + plane_config->size,
2444                                     PAGE_SIZE);
2445
2446         size_aligned -= base_aligned;
2447
2448         if (plane_config->size == 0)
2449                 return false;
2450
2451         /* If the FB is too big, just don't use it since fbdev is not very
2452          * important and we should probably use that space with FBC or other
2453          * features. */
2454         if (size_aligned * 2 > ggtt->stolen_usable_size)
2455                 return false;
2456
2457         mutex_lock(&dev->struct_mutex);
2458
2459         obj = i915_gem_object_create_stolen_for_preallocated(dev,
2460                                                              base_aligned,
2461                                                              base_aligned,
2462                                                              size_aligned);
2463         if (!obj) {
2464                 mutex_unlock(&dev->struct_mutex);
2465                 return false;
2466         }
2467
2468         obj->tiling_mode = plane_config->tiling;
2469         if (obj->tiling_mode == I915_TILING_X)
2470                 obj->stride = fb->pitches[0];
2471
2472         mode_cmd.pixel_format = fb->pixel_format;
2473         mode_cmd.width = fb->width;
2474         mode_cmd.height = fb->height;
2475         mode_cmd.pitches[0] = fb->pitches[0];
2476         mode_cmd.modifier[0] = fb->modifier[0];
2477         mode_cmd.flags = DRM_MODE_FB_MODIFIERS;
2478
2479         if (intel_framebuffer_init(dev, to_intel_framebuffer(fb),
2480                                    &mode_cmd, obj)) {
2481                 DRM_DEBUG_KMS("intel fb init failed\n");
2482                 goto out_unref_obj;
2483         }
2484
2485         mutex_unlock(&dev->struct_mutex);
2486
2487         DRM_DEBUG_KMS("initial plane fb obj %p\n", obj);
2488         return true;
2489
2490 out_unref_obj:
2491         drm_gem_object_unreference(&obj->base);
2492         mutex_unlock(&dev->struct_mutex);
2493         return false;
2494 }
2495
2496 /* Update plane->state->fb to match plane->fb after driver-internal updates */
2497 static void
2498 update_state_fb(struct drm_plane *plane)
2499 {
2500         if (plane->fb == plane->state->fb)
2501                 return;
2502
2503         if (plane->state->fb)
2504                 drm_framebuffer_unreference(plane->state->fb);
2505         plane->state->fb = plane->fb;
2506         if (plane->state->fb)
2507                 drm_framebuffer_reference(plane->state->fb);
2508 }
2509
2510 static void
2511 intel_find_initial_plane_obj(struct intel_crtc *intel_crtc,
2512                              struct intel_initial_plane_config *plane_config)
2513 {
2514         struct drm_device *dev = intel_crtc->base.dev;
2515         struct drm_i915_private *dev_priv = to_i915(dev);
2516         struct drm_crtc *c;
2517         struct intel_crtc *i;
2518         struct drm_i915_gem_object *obj;
2519         struct drm_plane *primary = intel_crtc->base.primary;
2520         struct drm_plane_state *plane_state = primary->state;
2521         struct drm_crtc_state *crtc_state = intel_crtc->base.state;
2522         struct intel_plane *intel_plane = to_intel_plane(primary);
2523         struct intel_plane_state *intel_state =
2524                 to_intel_plane_state(plane_state);
2525         struct drm_framebuffer *fb;
2526
2527         if (!plane_config->fb)
2528                 return;
2529
2530         if (intel_alloc_initial_plane_obj(intel_crtc, plane_config)) {
2531                 fb = &plane_config->fb->base;
2532                 goto valid_fb;
2533         }
2534
2535         kfree(plane_config->fb);
2536
2537         /*
2538          * Failed to alloc the obj, check to see if we should share
2539          * an fb with another CRTC instead
2540          */
2541         for_each_crtc(dev, c) {
2542                 i = to_intel_crtc(c);
2543
2544                 if (c == &intel_crtc->base)
2545                         continue;
2546
2547                 if (!i->active)
2548                         continue;
2549
2550                 fb = c->primary->fb;
2551                 if (!fb)
2552                         continue;
2553
2554                 obj = intel_fb_obj(fb);
2555                 if (i915_gem_obj_ggtt_offset(obj) == plane_config->base) {
2556                         drm_framebuffer_reference(fb);
2557                         goto valid_fb;
2558                 }
2559         }
2560
2561         /*
2562          * We've failed to reconstruct the BIOS FB.  Current display state
2563          * indicates that the primary plane is visible, but has a NULL FB,
2564          * which will lead to problems later if we don't fix it up.  The
2565          * simplest solution is to just disable the primary plane now and
2566          * pretend the BIOS never had it enabled.
2567          */
2568         to_intel_plane_state(plane_state)->visible = false;
2569         crtc_state->plane_mask &= ~(1 << drm_plane_index(primary));
2570         intel_pre_disable_primary_noatomic(&intel_crtc->base);
2571         intel_plane->disable_plane(primary, &intel_crtc->base);
2572
2573         return;
2574
2575 valid_fb:
2576         plane_state->src_x = 0;
2577         plane_state->src_y = 0;
2578         plane_state->src_w = fb->width << 16;
2579         plane_state->src_h = fb->height << 16;
2580
2581         plane_state->crtc_x = 0;
2582         plane_state->crtc_y = 0;
2583         plane_state->crtc_w = fb->width;
2584         plane_state->crtc_h = fb->height;
2585
2586         intel_state->src.x1 = plane_state->src_x;
2587         intel_state->src.y1 = plane_state->src_y;
2588         intel_state->src.x2 = plane_state->src_x + plane_state->src_w;
2589         intel_state->src.y2 = plane_state->src_y + plane_state->src_h;
2590         intel_state->dst.x1 = plane_state->crtc_x;
2591         intel_state->dst.y1 = plane_state->crtc_y;
2592         intel_state->dst.x2 = plane_state->crtc_x + plane_state->crtc_w;
2593         intel_state->dst.y2 = plane_state->crtc_y + plane_state->crtc_h;
2594
2595         obj = intel_fb_obj(fb);
2596         if (obj->tiling_mode != I915_TILING_NONE)
2597                 dev_priv->preserve_bios_swizzle = true;
2598
2599         drm_framebuffer_reference(fb);
2600         primary->fb = primary->state->fb = fb;
2601         primary->crtc = primary->state->crtc = &intel_crtc->base;
2602         intel_crtc->base.state->plane_mask |= (1 << drm_plane_index(primary));
2603         obj->frontbuffer_bits |= to_intel_plane(primary)->frontbuffer_bit;
2604 }
2605
2606 static void i9xx_update_primary_plane(struct drm_plane *primary,
2607                                       const struct intel_crtc_state *crtc_state,
2608                                       const struct intel_plane_state *plane_state)
2609 {
2610         struct drm_device *dev = primary->dev;
2611         struct drm_i915_private *dev_priv = to_i915(dev);
2612         struct intel_crtc *intel_crtc = to_intel_crtc(crtc_state->base.crtc);
2613         struct drm_framebuffer *fb = plane_state->base.fb;
2614         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
2615         int plane = intel_crtc->plane;
2616         u32 linear_offset;
2617         u32 dspcntr;
2618         i915_reg_t reg = DSPCNTR(plane);
2619         unsigned int rotation = plane_state->base.rotation;
2620         int cpp = drm_format_plane_cpp(fb->pixel_format, 0);
2621         int x = plane_state->src.x1 >> 16;
2622         int y = plane_state->src.y1 >> 16;
2623
2624         dspcntr = DISPPLANE_GAMMA_ENABLE;
2625
2626         dspcntr |= DISPLAY_PLANE_ENABLE;
2627
2628         if (INTEL_INFO(dev)->gen < 4) {
2629                 if (intel_crtc->pipe == PIPE_B)
2630                         dspcntr |= DISPPLANE_SEL_PIPE_B;
2631
2632                 /* pipesrc and dspsize control the size that is scaled from,
2633                  * which should always be the user's requested size.
2634                  */
2635                 I915_WRITE(DSPSIZE(plane),
2636                            ((crtc_state->pipe_src_h - 1) << 16) |
2637                            (crtc_state->pipe_src_w - 1));
2638                 I915_WRITE(DSPPOS(plane), 0);
2639         } else if (IS_CHERRYVIEW(dev) && plane == PLANE_B) {
2640                 I915_WRITE(PRIMSIZE(plane),
2641                            ((crtc_state->pipe_src_h - 1) << 16) |
2642                            (crtc_state->pipe_src_w - 1));
2643                 I915_WRITE(PRIMPOS(plane), 0);
2644                 I915_WRITE(PRIMCNSTALPHA(plane), 0);
2645         }
2646
2647         switch (fb->pixel_format) {
2648         case DRM_FORMAT_C8:
2649                 dspcntr |= DISPPLANE_8BPP;
2650                 break;
2651         case DRM_FORMAT_XRGB1555:
2652                 dspcntr |= DISPPLANE_BGRX555;
2653                 break;
2654         case DRM_FORMAT_RGB565:
2655                 dspcntr |= DISPPLANE_BGRX565;
2656                 break;
2657         case DRM_FORMAT_XRGB8888:
2658                 dspcntr |= DISPPLANE_BGRX888;
2659                 break;
2660         case DRM_FORMAT_XBGR8888:
2661                 dspcntr |= DISPPLANE_RGBX888;
2662                 break;
2663         case DRM_FORMAT_XRGB2101010:
2664                 dspcntr |= DISPPLANE_BGRX101010;
2665                 break;
2666         case DRM_FORMAT_XBGR2101010:
2667                 dspcntr |= DISPPLANE_RGBX101010;
2668                 break;
2669         default:
2670                 BUG();
2671         }
2672
2673         if (INTEL_INFO(dev)->gen >= 4 &&
2674             obj->tiling_mode != I915_TILING_NONE)
2675                 dspcntr |= DISPPLANE_TILED;
2676
2677         if (IS_G4X(dev))
2678                 dspcntr |= DISPPLANE_TRICKLE_FEED_DISABLE;
2679
2680         linear_offset = y * fb->pitches[0] + x * cpp;
2681
2682         if (INTEL_INFO(dev)->gen >= 4) {
2683                 intel_crtc->dspaddr_offset =
2684                         intel_compute_tile_offset(&x, &y, fb, 0,
2685                                                   fb->pitches[0], rotation);
2686                 linear_offset -= intel_crtc->dspaddr_offset;
2687         } else {
2688                 intel_crtc->dspaddr_offset = linear_offset;
2689         }
2690
2691         if (rotation == BIT(DRM_ROTATE_180)) {
2692                 dspcntr |= DISPPLANE_ROTATE_180;
2693
2694                 x += (crtc_state->pipe_src_w - 1);
2695                 y += (crtc_state->pipe_src_h - 1);
2696
2697                 /* Finding the last pixel of the last line of the display
2698                 data and adding to linear_offset*/
2699                 linear_offset +=
2700                         (crtc_state->pipe_src_h - 1) * fb->pitches[0] +
2701                         (crtc_state->pipe_src_w - 1) * cpp;
2702         }
2703
2704         intel_crtc->adjusted_x = x;
2705         intel_crtc->adjusted_y = y;
2706
2707         I915_WRITE(reg, dspcntr);
2708
2709         I915_WRITE(DSPSTRIDE(plane), fb->pitches[0]);
2710         if (INTEL_INFO(dev)->gen >= 4) {
2711                 I915_WRITE(DSPSURF(plane),
2712                            i915_gem_obj_ggtt_offset(obj) + intel_crtc->dspaddr_offset);
2713                 I915_WRITE(DSPTILEOFF(plane), (y << 16) | x);
2714                 I915_WRITE(DSPLINOFF(plane), linear_offset);
2715         } else
2716                 I915_WRITE(DSPADDR(plane), i915_gem_obj_ggtt_offset(obj) + linear_offset);
2717         POSTING_READ(reg);
2718 }
2719
2720 static void i9xx_disable_primary_plane(struct drm_plane *primary,
2721                                        struct drm_crtc *crtc)
2722 {
2723         struct drm_device *dev = crtc->dev;
2724         struct drm_i915_private *dev_priv = to_i915(dev);
2725         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
2726         int plane = intel_crtc->plane;
2727
2728         I915_WRITE(DSPCNTR(plane), 0);
2729         if (INTEL_INFO(dev_priv)->gen >= 4)
2730                 I915_WRITE(DSPSURF(plane), 0);
2731         else
2732                 I915_WRITE(DSPADDR(plane), 0);
2733         POSTING_READ(DSPCNTR(plane));
2734 }
2735
2736 static void ironlake_update_primary_plane(struct drm_plane *primary,
2737                                           const struct intel_crtc_state *crtc_state,
2738                                           const struct intel_plane_state *plane_state)
2739 {
2740         struct drm_device *dev = primary->dev;
2741         struct drm_i915_private *dev_priv = to_i915(dev);
2742         struct intel_crtc *intel_crtc = to_intel_crtc(crtc_state->base.crtc);
2743         struct drm_framebuffer *fb = plane_state->base.fb;
2744         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
2745         int plane = intel_crtc->plane;
2746         u32 linear_offset;
2747         u32 dspcntr;
2748         i915_reg_t reg = DSPCNTR(plane);
2749         unsigned int rotation = plane_state->base.rotation;
2750         int cpp = drm_format_plane_cpp(fb->pixel_format, 0);
2751         int x = plane_state->src.x1 >> 16;
2752         int y = plane_state->src.y1 >> 16;
2753
2754         dspcntr = DISPPLANE_GAMMA_ENABLE;
2755         dspcntr |= DISPLAY_PLANE_ENABLE;
2756
2757         if (IS_HASWELL(dev) || IS_BROADWELL(dev))
2758                 dspcntr |= DISPPLANE_PIPE_CSC_ENABLE;
2759
2760         switch (fb->pixel_format) {
2761         case DRM_FORMAT_C8:
2762                 dspcntr |= DISPPLANE_8BPP;
2763                 break;
2764         case DRM_FORMAT_RGB565:
2765                 dspcntr |= DISPPLANE_BGRX565;
2766                 break;
2767         case DRM_FORMAT_XRGB8888:
2768                 dspcntr |= DISPPLANE_BGRX888;
2769                 break;
2770         case DRM_FORMAT_XBGR8888:
2771                 dspcntr |= DISPPLANE_RGBX888;
2772                 break;
2773         case DRM_FORMAT_XRGB2101010:
2774                 dspcntr |= DISPPLANE_BGRX101010;
2775                 break;
2776         case DRM_FORMAT_XBGR2101010:
2777                 dspcntr |= DISPPLANE_RGBX101010;
2778                 break;
2779         default:
2780                 BUG();
2781         }
2782
2783         if (obj->tiling_mode != I915_TILING_NONE)
2784                 dspcntr |= DISPPLANE_TILED;
2785
2786         if (!IS_HASWELL(dev) && !IS_BROADWELL(dev))
2787                 dspcntr |= DISPPLANE_TRICKLE_FEED_DISABLE;
2788
2789         linear_offset = y * fb->pitches[0] + x * cpp;
2790         intel_crtc->dspaddr_offset =
2791                 intel_compute_tile_offset(&x, &y, fb, 0,
2792                                           fb->pitches[0], rotation);
2793         linear_offset -= intel_crtc->dspaddr_offset;
2794         if (rotation == BIT(DRM_ROTATE_180)) {
2795                 dspcntr |= DISPPLANE_ROTATE_180;
2796
2797                 if (!IS_HASWELL(dev) && !IS_BROADWELL(dev)) {
2798                         x += (crtc_state->pipe_src_w - 1);
2799                         y += (crtc_state->pipe_src_h - 1);
2800
2801                         /* Finding the last pixel of the last line of the display
2802                         data and adding to linear_offset*/
2803                         linear_offset +=
2804                                 (crtc_state->pipe_src_h - 1) * fb->pitches[0] +
2805                                 (crtc_state->pipe_src_w - 1) * cpp;
2806                 }
2807         }
2808
2809         intel_crtc->adjusted_x = x;
2810         intel_crtc->adjusted_y = y;
2811
2812         I915_WRITE(reg, dspcntr);
2813
2814         I915_WRITE(DSPSTRIDE(plane), fb->pitches[0]);
2815         I915_WRITE(DSPSURF(plane),
2816                    i915_gem_obj_ggtt_offset(obj) + intel_crtc->dspaddr_offset);
2817         if (IS_HASWELL(dev) || IS_BROADWELL(dev)) {
2818                 I915_WRITE(DSPOFFSET(plane), (y << 16) | x);
2819         } else {
2820                 I915_WRITE(DSPTILEOFF(plane), (y << 16) | x);
2821                 I915_WRITE(DSPLINOFF(plane), linear_offset);
2822         }
2823         POSTING_READ(reg);
2824 }
2825
2826 u32 intel_fb_stride_alignment(const struct drm_i915_private *dev_priv,
2827                               uint64_t fb_modifier, uint32_t pixel_format)
2828 {
2829         if (fb_modifier == DRM_FORMAT_MOD_NONE) {
2830                 return 64;
2831         } else {
2832                 int cpp = drm_format_plane_cpp(pixel_format, 0);
2833
2834                 return intel_tile_width_bytes(dev_priv, fb_modifier, cpp);
2835         }
2836 }
2837
2838 u32 intel_plane_obj_offset(struct intel_plane *intel_plane,
2839                            struct drm_i915_gem_object *obj,
2840                            unsigned int plane)
2841 {
2842         struct i915_ggtt_view view;
2843         struct i915_vma *vma;
2844         u64 offset;
2845
2846         intel_fill_fb_ggtt_view(&view, intel_plane->base.state->fb,
2847                                 intel_plane->base.state->rotation);
2848
2849         vma = i915_gem_obj_to_ggtt_view(obj, &view);
2850         if (WARN(!vma, "ggtt vma for display object not found! (view=%u)\n",
2851                 view.type))
2852                 return -1;
2853
2854         offset = vma->node.start;
2855
2856         if (plane == 1) {
2857                 offset += vma->ggtt_view.params.rotated.uv_start_page *
2858                           PAGE_SIZE;
2859         }
2860
2861         WARN_ON(upper_32_bits(offset));
2862
2863         return lower_32_bits(offset);
2864 }
2865
2866 static void skl_detach_scaler(struct intel_crtc *intel_crtc, int id)
2867 {
2868         struct drm_device *dev = intel_crtc->base.dev;
2869         struct drm_i915_private *dev_priv = to_i915(dev);
2870
2871         I915_WRITE(SKL_PS_CTRL(intel_crtc->pipe, id), 0);
2872         I915_WRITE(SKL_PS_WIN_POS(intel_crtc->pipe, id), 0);
2873         I915_WRITE(SKL_PS_WIN_SZ(intel_crtc->pipe, id), 0);
2874 }
2875
2876 /*
2877  * This function detaches (aka. unbinds) unused scalers in hardware
2878  */
2879 static void skl_detach_scalers(struct intel_crtc *intel_crtc)
2880 {
2881         struct intel_crtc_scaler_state *scaler_state;
2882         int i;
2883
2884         scaler_state = &intel_crtc->config->scaler_state;
2885
2886         /* loop through and disable scalers that aren't in use */
2887         for (i = 0; i < intel_crtc->num_scalers; i++) {
2888                 if (!scaler_state->scalers[i].in_use)
2889                         skl_detach_scaler(intel_crtc, i);
2890         }
2891 }
2892
2893 u32 skl_plane_ctl_format(uint32_t pixel_format)
2894 {
2895         switch (pixel_format) {
2896         case DRM_FORMAT_C8:
2897                 return PLANE_CTL_FORMAT_INDEXED;
2898         case DRM_FORMAT_RGB565:
2899                 return PLANE_CTL_FORMAT_RGB_565;
2900         case DRM_FORMAT_XBGR8888:
2901                 return PLANE_CTL_FORMAT_XRGB_8888 | PLANE_CTL_ORDER_RGBX;
2902         case DRM_FORMAT_XRGB8888:
2903                 return PLANE_CTL_FORMAT_XRGB_8888;
2904         /*
2905          * XXX: For ARBG/ABGR formats we default to expecting scanout buffers
2906          * to be already pre-multiplied. We need to add a knob (or a different
2907          * DRM_FORMAT) for user-space to configure that.
2908          */
2909         case DRM_FORMAT_ABGR8888:
2910                 return PLANE_CTL_FORMAT_XRGB_8888 | PLANE_CTL_ORDER_RGBX |
2911                         PLANE_CTL_ALPHA_SW_PREMULTIPLY;
2912         case DRM_FORMAT_ARGB8888:
2913                 return PLANE_CTL_FORMAT_XRGB_8888 |
2914                         PLANE_CTL_ALPHA_SW_PREMULTIPLY;
2915         case DRM_FORMAT_XRGB2101010:
2916                 return PLANE_CTL_FORMAT_XRGB_2101010;
2917         case DRM_FORMAT_XBGR2101010:
2918                 return PLANE_CTL_ORDER_RGBX | PLANE_CTL_FORMAT_XRGB_2101010;
2919         case DRM_FORMAT_YUYV:
2920                 return PLANE_CTL_FORMAT_YUV422 | PLANE_CTL_YUV422_YUYV;
2921         case DRM_FORMAT_YVYU:
2922                 return PLANE_CTL_FORMAT_YUV422 | PLANE_CTL_YUV422_YVYU;
2923         case DRM_FORMAT_UYVY:
2924                 return PLANE_CTL_FORMAT_YUV422 | PLANE_CTL_YUV422_UYVY;
2925         case DRM_FORMAT_VYUY:
2926                 return PLANE_CTL_FORMAT_YUV422 | PLANE_CTL_YUV422_VYUY;
2927         default:
2928                 MISSING_CASE(pixel_format);
2929         }
2930
2931         return 0;
2932 }
2933
2934 u32 skl_plane_ctl_tiling(uint64_t fb_modifier)
2935 {
2936         switch (fb_modifier) {
2937         case DRM_FORMAT_MOD_NONE:
2938                 break;
2939         case I915_FORMAT_MOD_X_TILED:
2940                 return PLANE_CTL_TILED_X;
2941         case I915_FORMAT_MOD_Y_TILED:
2942                 return PLANE_CTL_TILED_Y;
2943         case I915_FORMAT_MOD_Yf_TILED:
2944                 return PLANE_CTL_TILED_YF;
2945         default:
2946                 MISSING_CASE(fb_modifier);
2947         }
2948
2949         return 0;
2950 }
2951
2952 u32 skl_plane_ctl_rotation(unsigned int rotation)
2953 {
2954         switch (rotation) {
2955         case BIT(DRM_ROTATE_0):
2956                 break;
2957         /*
2958          * DRM_ROTATE_ is counter clockwise to stay compatible with Xrandr
2959          * while i915 HW rotation is clockwise, thats why this swapping.
2960          */
2961         case BIT(DRM_ROTATE_90):
2962                 return PLANE_CTL_ROTATE_270;
2963         case BIT(DRM_ROTATE_180):
2964                 return PLANE_CTL_ROTATE_180;
2965         case BIT(DRM_ROTATE_270):
2966                 return PLANE_CTL_ROTATE_90;
2967         default:
2968                 MISSING_CASE(rotation);
2969         }
2970
2971         return 0;
2972 }
2973
2974 static void skylake_update_primary_plane(struct drm_plane *plane,
2975                                          const struct intel_crtc_state *crtc_state,
2976                                          const struct intel_plane_state *plane_state)
2977 {
2978         struct drm_device *dev = plane->dev;
2979         struct drm_i915_private *dev_priv = to_i915(dev);
2980         struct intel_crtc *intel_crtc = to_intel_crtc(crtc_state->base.crtc);
2981         struct drm_framebuffer *fb = plane_state->base.fb;
2982         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
2983         int pipe = intel_crtc->pipe;
2984         u32 plane_ctl, stride_div, stride;
2985         u32 tile_height, plane_offset, plane_size;
2986         unsigned int rotation = plane_state->base.rotation;
2987         int x_offset, y_offset;
2988         u32 surf_addr;
2989         int scaler_id = plane_state->scaler_id;
2990         int src_x = plane_state->src.x1 >> 16;
2991         int src_y = plane_state->src.y1 >> 16;
2992         int src_w = drm_rect_width(&plane_state->src) >> 16;
2993         int src_h = drm_rect_height(&plane_state->src) >> 16;
2994         int dst_x = plane_state->dst.x1;
2995         int dst_y = plane_state->dst.y1;
2996         int dst_w = drm_rect_width(&plane_state->dst);
2997         int dst_h = drm_rect_height(&plane_state->dst);
2998
2999         plane_ctl = PLANE_CTL_ENABLE |
3000                     PLANE_CTL_PIPE_GAMMA_ENABLE |
3001                     PLANE_CTL_PIPE_CSC_ENABLE;
3002
3003         plane_ctl |= skl_plane_ctl_format(fb->pixel_format);
3004         plane_ctl |= skl_plane_ctl_tiling(fb->modifier[0]);
3005         plane_ctl |= PLANE_CTL_PLANE_GAMMA_DISABLE;
3006         plane_ctl |= skl_plane_ctl_rotation(rotation);
3007
3008         stride_div = intel_fb_stride_alignment(dev_priv, fb->modifier[0],
3009                                                fb->pixel_format);
3010         surf_addr = intel_plane_obj_offset(to_intel_plane(plane), obj, 0);
3011
3012         WARN_ON(drm_rect_width(&plane_state->src) == 0);
3013
3014         if (intel_rotation_90_or_270(rotation)) {
3015                 int cpp = drm_format_plane_cpp(fb->pixel_format, 0);
3016
3017                 /* stride = Surface height in tiles */
3018                 tile_height = intel_tile_height(dev_priv, fb->modifier[0], cpp);
3019                 stride = DIV_ROUND_UP(fb->height, tile_height);
3020                 x_offset = stride * tile_height - src_y - src_h;
3021                 y_offset = src_x;
3022                 plane_size = (src_w - 1) << 16 | (src_h - 1);
3023         } else {
3024                 stride = fb->pitches[0] / stride_div;
3025                 x_offset = src_x;
3026                 y_offset = src_y;
3027                 plane_size = (src_h - 1) << 16 | (src_w - 1);
3028         }
3029         plane_offset = y_offset << 16 | x_offset;
3030
3031         intel_crtc->adjusted_x = x_offset;
3032         intel_crtc->adjusted_y = y_offset;
3033
3034         I915_WRITE(PLANE_CTL(pipe, 0), plane_ctl);
3035         I915_WRITE(PLANE_OFFSET(pipe, 0), plane_offset);
3036         I915_WRITE(PLANE_SIZE(pipe, 0), plane_size);
3037         I915_WRITE(PLANE_STRIDE(pipe, 0), stride);
3038
3039         if (scaler_id >= 0) {
3040                 uint32_t ps_ctrl = 0;
3041
3042                 WARN_ON(!dst_w || !dst_h);
3043                 ps_ctrl = PS_SCALER_EN | PS_PLANE_SEL(0) |
3044                         crtc_state->scaler_state.scalers[scaler_id].mode;
3045                 I915_WRITE(SKL_PS_CTRL(pipe, scaler_id), ps_ctrl);
3046                 I915_WRITE(SKL_PS_PWR_GATE(pipe, scaler_id), 0);
3047                 I915_WRITE(SKL_PS_WIN_POS(pipe, scaler_id), (dst_x << 16) | dst_y);
3048                 I915_WRITE(SKL_PS_WIN_SZ(pipe, scaler_id), (dst_w << 16) | dst_h);
3049                 I915_WRITE(PLANE_POS(pipe, 0), 0);
3050         } else {
3051                 I915_WRITE(PLANE_POS(pipe, 0), (dst_y << 16) | dst_x);
3052         }
3053
3054         I915_WRITE(PLANE_SURF(pipe, 0), surf_addr);
3055
3056         POSTING_READ(PLANE_SURF(pipe, 0));
3057 }
3058
3059 static void skylake_disable_primary_plane(struct drm_plane *primary,
3060                                           struct drm_crtc *crtc)
3061 {
3062         struct drm_device *dev = crtc->dev;
3063         struct drm_i915_private *dev_priv = to_i915(dev);
3064         int pipe = to_intel_crtc(crtc)->pipe;
3065
3066         I915_WRITE(PLANE_CTL(pipe, 0), 0);
3067         I915_WRITE(PLANE_SURF(pipe, 0), 0);
3068         POSTING_READ(PLANE_SURF(pipe, 0));
3069 }
3070
3071 /* Assume fb object is pinned & idle & fenced and just update base pointers */
3072 static int
3073 intel_pipe_set_base_atomic(struct drm_crtc *crtc, struct drm_framebuffer *fb,
3074                            int x, int y, enum mode_set_atomic state)
3075 {
3076         /* Support for kgdboc is disabled, this needs a major rework. */
3077         DRM_ERROR("legacy panic handler not supported any more.\n");
3078
3079         return -ENODEV;
3080 }
3081
3082 static void intel_complete_page_flips(struct drm_i915_private *dev_priv)
3083 {
3084         struct intel_crtc *crtc;
3085
3086         for_each_intel_crtc(&dev_priv->drm, crtc)
3087                 intel_finish_page_flip_cs(dev_priv, crtc->pipe);
3088 }
3089
3090 static void intel_update_primary_planes(struct drm_device *dev)
3091 {
3092         struct drm_crtc *crtc;
3093
3094         for_each_crtc(dev, crtc) {
3095                 struct intel_plane *plane = to_intel_plane(crtc->primary);
3096                 struct intel_plane_state *plane_state =
3097                         to_intel_plane_state(plane->base.state);
3098
3099                 if (plane_state->visible)
3100                         plane->update_plane(&plane->base,
3101                                             to_intel_crtc_state(crtc->state),
3102                                             plane_state);
3103         }
3104 }
3105
3106 static int
3107 __intel_display_resume(struct drm_device *dev,
3108                        struct drm_atomic_state *state)
3109 {
3110         struct drm_crtc_state *crtc_state;
3111         struct drm_crtc *crtc;
3112         int i, ret;
3113
3114         intel_modeset_setup_hw_state(dev);
3115         i915_redisable_vga(dev);
3116
3117         if (!state)
3118                 return 0;
3119
3120         for_each_crtc_in_state(state, crtc, crtc_state, i) {
3121                 /*
3122                  * Force recalculation even if we restore
3123                  * current state. With fast modeset this may not result
3124                  * in a modeset when the state is compatible.
3125                  */
3126                 crtc_state->mode_changed = true;
3127         }
3128
3129         /* ignore any reset values/BIOS leftovers in the WM registers */
3130         to_intel_atomic_state(state)->skip_intermediate_wm = true;
3131
3132         ret = drm_atomic_commit(state);
3133
3134         WARN_ON(ret == -EDEADLK);
3135         return ret;
3136 }
3137
3138 void intel_prepare_reset(struct drm_i915_private *dev_priv)
3139 {
3140         struct drm_device *dev = &dev_priv->drm;
3141         struct drm_modeset_acquire_ctx *ctx = &dev_priv->reset_ctx;
3142         struct drm_atomic_state *state;
3143         int ret;
3144
3145         /* no reset support for gen2 */
3146         if (IS_GEN2(dev_priv))
3147                 return;
3148
3149         /*
3150          * Need mode_config.mutex so that we don't
3151          * trample ongoing ->detect() and whatnot.
3152          */
3153         mutex_lock(&dev->mode_config.mutex);
3154         drm_modeset_acquire_init(ctx, 0);
3155         while (1) {
3156                 ret = drm_modeset_lock_all_ctx(dev, ctx);
3157                 if (ret != -EDEADLK)
3158                         break;
3159
3160                 drm_modeset_backoff(ctx);
3161         }
3162
3163         /* reset doesn't touch the display, but flips might get nuked anyway, */
3164         if (INTEL_GEN(dev_priv) >= 5 || IS_G4X(dev_priv))
3165                 return;
3166
3167         /*
3168          * Disabling the crtcs gracefully seems nicer. Also the
3169          * g33 docs say we should at least disable all the planes.
3170          */
3171         state = drm_atomic_helper_duplicate_state(dev, ctx);
3172         if (IS_ERR(state)) {
3173                 ret = PTR_ERR(state);
3174                 state = NULL;
3175                 DRM_ERROR("Duplicating state failed with %i\n", ret);
3176                 goto err;
3177         }
3178
3179         ret = drm_atomic_helper_disable_all(dev, ctx);
3180         if (ret) {
3181                 DRM_ERROR("Suspending crtc's failed with %i\n", ret);
3182                 goto err;
3183         }
3184
3185         dev_priv->modeset_restore_state = state;
3186         state->acquire_ctx = ctx;
3187         return;
3188
3189 err:
3190         drm_atomic_state_free(state);
3191 }
3192
3193 void intel_finish_reset(struct drm_i915_private *dev_priv)
3194 {
3195         struct drm_device *dev = &dev_priv->drm;
3196         struct drm_modeset_acquire_ctx *ctx = &dev_priv->reset_ctx;
3197         struct drm_atomic_state *state = dev_priv->modeset_restore_state;
3198         int ret;
3199
3200         /*
3201          * Flips in the rings will be nuked by the reset,
3202          * so complete all pending flips so that user space
3203          * will get its events and not get stuck.
3204          */
3205         intel_complete_page_flips(dev_priv);
3206
3207         /* no reset support for gen2 */
3208         if (IS_GEN2(dev_priv))
3209                 return;
3210
3211         dev_priv->modeset_restore_state = NULL;
3212
3213         /* reset doesn't touch the display */
3214         if (INTEL_GEN(dev_priv) >= 5 || IS_G4X(dev_priv)) {
3215                 /*
3216                  * Flips in the rings have been nuked by the reset,
3217                  * so update the base address of all primary
3218                  * planes to the the last fb to make sure we're
3219                  * showing the correct fb after a reset.
3220                  *
3221                  * FIXME: Atomic will make this obsolete since we won't schedule
3222                  * CS-based flips (which might get lost in gpu resets) any more.
3223                  */
3224                 intel_update_primary_planes(dev);
3225         } else {
3226                 /*
3227                  * The display has been reset as well,
3228                  * so need a full re-initialization.
3229                  */
3230                 intel_runtime_pm_disable_interrupts(dev_priv);
3231                 intel_runtime_pm_enable_interrupts(dev_priv);
3232
3233                 intel_modeset_init_hw(dev);
3234
3235                 spin_lock_irq(&dev_priv->irq_lock);
3236                 if (dev_priv->display.hpd_irq_setup)
3237                         dev_priv->display.hpd_irq_setup(dev_priv);
3238                 spin_unlock_irq(&dev_priv->irq_lock);
3239
3240                 ret = __intel_display_resume(dev, state);
3241                 if (ret)
3242                         DRM_ERROR("Restoring old state failed with %i\n", ret);
3243
3244                 intel_hpd_init(dev_priv);
3245         }
3246
3247         drm_modeset_drop_locks(ctx);
3248         drm_modeset_acquire_fini(ctx);
3249         mutex_unlock(&dev->mode_config.mutex);
3250 }
3251
3252 static bool intel_crtc_has_pending_flip(struct drm_crtc *crtc)
3253 {
3254         struct drm_device *dev = crtc->dev;
3255         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
3256         unsigned reset_counter;
3257         bool pending;
3258
3259         reset_counter = i915_reset_counter(&to_i915(dev)->gpu_error);
3260         if (intel_crtc->reset_counter != reset_counter)
3261                 return false;
3262
3263         spin_lock_irq(&dev->event_lock);
3264         pending = to_intel_crtc(crtc)->flip_work != NULL;
3265         spin_unlock_irq(&dev->event_lock);
3266
3267         return pending;
3268 }
3269
3270 static void intel_update_pipe_config(struct intel_crtc *crtc,
3271                                      struct intel_crtc_state *old_crtc_state)
3272 {
3273         struct drm_device *dev = crtc->base.dev;
3274         struct drm_i915_private *dev_priv = to_i915(dev);
3275         struct intel_crtc_state *pipe_config =
3276                 to_intel_crtc_state(crtc->base.state);
3277
3278         /* drm_atomic_helper_update_legacy_modeset_state might not be called. */
3279         crtc->base.mode = crtc->base.state->mode;
3280
3281         DRM_DEBUG_KMS("Updating pipe size %ix%i -> %ix%i\n",
3282                       old_crtc_state->pipe_src_w, old_crtc_state->pipe_src_h,
3283                       pipe_config->pipe_src_w, pipe_config->pipe_src_h);
3284
3285         /*
3286          * Update pipe size and adjust fitter if needed: the reason for this is
3287          * that in compute_mode_changes we check the native mode (not the pfit
3288          * mode) to see if we can flip rather than do a full mode set. In the
3289          * fastboot case, we'll flip, but if we don't update the pipesrc and
3290          * pfit state, we'll end up with a big fb scanned out into the wrong
3291          * sized surface.
3292          */
3293
3294         I915_WRITE(PIPESRC(crtc->pipe),
3295                    ((pipe_config->pipe_src_w - 1) << 16) |
3296                    (pipe_config->pipe_src_h - 1));
3297
3298         /* on skylake this is done by detaching scalers */
3299         if (INTEL_INFO(dev)->gen >= 9) {
3300                 skl_detach_scalers(crtc);
3301
3302                 if (pipe_config->pch_pfit.enabled)
3303                         skylake_pfit_enable(crtc);
3304         } else if (HAS_PCH_SPLIT(dev)) {
3305                 if (pipe_config->pch_pfit.enabled)
3306                         ironlake_pfit_enable(crtc);
3307                 else if (old_crtc_state->pch_pfit.enabled)
3308                         ironlake_pfit_disable(crtc, true);
3309         }
3310 }
3311
3312 static void intel_fdi_normal_train(struct drm_crtc *crtc)
3313 {
3314         struct drm_device *dev = crtc->dev;
3315         struct drm_i915_private *dev_priv = to_i915(dev);
3316         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
3317         int pipe = intel_crtc->pipe;
3318         i915_reg_t reg;
3319         u32 temp;
3320
3321         /* enable normal train */
3322         reg = FDI_TX_CTL(pipe);
3323         temp = I915_READ(reg);
3324         if (IS_IVYBRIDGE(dev)) {
3325                 temp &= ~FDI_LINK_TRAIN_NONE_IVB;
3326                 temp |= FDI_LINK_TRAIN_NONE_IVB | FDI_TX_ENHANCE_FRAME_ENABLE;
3327         } else {
3328                 temp &= ~FDI_LINK_TRAIN_NONE;
3329                 temp |= FDI_LINK_TRAIN_NONE | FDI_TX_ENHANCE_FRAME_ENABLE;
3330         }
3331         I915_WRITE(reg, temp);
3332
3333         reg = FDI_RX_CTL(pipe);
3334         temp = I915_READ(reg);
3335         if (HAS_PCH_CPT(dev)) {
3336                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
3337                 temp |= FDI_LINK_TRAIN_NORMAL_CPT;
3338         } else {
3339                 temp &= ~FDI_LINK_TRAIN_NONE;
3340                 temp |= FDI_LINK_TRAIN_NONE;
3341         }
3342         I915_WRITE(reg, temp | FDI_RX_ENHANCE_FRAME_ENABLE);
3343
3344         /* wait one idle pattern time */
3345         POSTING_READ(reg);
3346         udelay(1000);
3347
3348         /* IVB wants error correction enabled */
3349         if (IS_IVYBRIDGE(dev))
3350                 I915_WRITE(reg, I915_READ(reg) | FDI_FS_ERRC_ENABLE |
3351                            FDI_FE_ERRC_ENABLE);
3352 }
3353
3354 /* The FDI link training functions for ILK/Ibexpeak. */
3355 static void ironlake_fdi_link_train(struct drm_crtc *crtc)
3356 {
3357         struct drm_device *dev = crtc->dev;
3358         struct drm_i915_private *dev_priv = to_i915(dev);
3359         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
3360         int pipe = intel_crtc->pipe;
3361         i915_reg_t reg;
3362         u32 temp, tries;
3363
3364         /* FDI needs bits from pipe first */
3365         assert_pipe_enabled(dev_priv, pipe);
3366
3367         /* Train 1: umask FDI RX Interrupt symbol_lock and bit_lock bit
3368            for train result */
3369         reg = FDI_RX_IMR(pipe);
3370         temp = I915_READ(reg);
3371         temp &= ~FDI_RX_SYMBOL_LOCK;
3372         temp &= ~FDI_RX_BIT_LOCK;
3373         I915_WRITE(reg, temp);
3374         I915_READ(reg);
3375         udelay(150);
3376
3377         /* enable CPU FDI TX and PCH FDI RX */
3378         reg = FDI_TX_CTL(pipe);
3379         temp = I915_READ(reg);
3380         temp &= ~FDI_DP_PORT_WIDTH_MASK;
3381         temp |= FDI_DP_PORT_WIDTH(intel_crtc->config->fdi_lanes);
3382         temp &= ~FDI_LINK_TRAIN_NONE;
3383         temp |= FDI_LINK_TRAIN_PATTERN_1;
3384         I915_WRITE(reg, temp | FDI_TX_ENABLE);
3385
3386         reg = FDI_RX_CTL(pipe);
3387         temp = I915_READ(reg);
3388         temp &= ~FDI_LINK_TRAIN_NONE;
3389         temp |= FDI_LINK_TRAIN_PATTERN_1;
3390         I915_WRITE(reg, temp | FDI_RX_ENABLE);
3391
3392         POSTING_READ(reg);
3393         udelay(150);
3394
3395         /* Ironlake workaround, enable clock pointer after FDI enable*/
3396         I915_WRITE(FDI_RX_CHICKEN(pipe), FDI_RX_PHASE_SYNC_POINTER_OVR);
3397         I915_WRITE(FDI_RX_CHICKEN(pipe), FDI_RX_PHASE_SYNC_POINTER_OVR |
3398                    FDI_RX_PHASE_SYNC_POINTER_EN);
3399
3400         reg = FDI_RX_IIR(pipe);
3401         for (tries = 0; tries < 5; tries++) {
3402                 temp = I915_READ(reg);
3403                 DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
3404
3405                 if ((temp & FDI_RX_BIT_LOCK)) {
3406                         DRM_DEBUG_KMS("FDI train 1 done.\n");
3407                         I915_WRITE(reg, temp | FDI_RX_BIT_LOCK);
3408                         break;
3409                 }
3410         }
3411         if (tries == 5)
3412                 DRM_ERROR("FDI train 1 fail!\n");
3413
3414         /* Train 2 */
3415         reg = FDI_TX_CTL(pipe);
3416         temp = I915_READ(reg);
3417         temp &= ~FDI_LINK_TRAIN_NONE;
3418         temp |= FDI_LINK_TRAIN_PATTERN_2;
3419         I915_WRITE(reg, temp);
3420
3421         reg = FDI_RX_CTL(pipe);
3422         temp = I915_READ(reg);
3423         temp &= ~FDI_LINK_TRAIN_NONE;
3424         temp |= FDI_LINK_TRAIN_PATTERN_2;
3425         I915_WRITE(reg, temp);
3426
3427         POSTING_READ(reg);
3428         udelay(150);
3429
3430         reg = FDI_RX_IIR(pipe);
3431         for (tries = 0; tries < 5; tries++) {
3432                 temp = I915_READ(reg);
3433                 DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
3434
3435                 if (temp & FDI_RX_SYMBOL_LOCK) {
3436                         I915_WRITE(reg, temp | FDI_RX_SYMBOL_LOCK);
3437                         DRM_DEBUG_KMS("FDI train 2 done.\n");
3438                         break;
3439                 }
3440         }
3441         if (tries == 5)
3442                 DRM_ERROR("FDI train 2 fail!\n");
3443
3444         DRM_DEBUG_KMS("FDI train done\n");
3445
3446 }
3447
3448 static const int snb_b_fdi_train_param[] = {
3449         FDI_LINK_TRAIN_400MV_0DB_SNB_B,
3450         FDI_LINK_TRAIN_400MV_6DB_SNB_B,
3451         FDI_LINK_TRAIN_600MV_3_5DB_SNB_B,
3452         FDI_LINK_TRAIN_800MV_0DB_SNB_B,
3453 };
3454
3455 /* The FDI link training functions for SNB/Cougarpoint. */
3456 static void gen6_fdi_link_train(struct drm_crtc *crtc)
3457 {
3458         struct drm_device *dev = crtc->dev;
3459         struct drm_i915_private *dev_priv = to_i915(dev);
3460         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
3461         int pipe = intel_crtc->pipe;
3462         i915_reg_t reg;
3463         u32 temp, i, retry;
3464
3465         /* Train 1: umask FDI RX Interrupt symbol_lock and bit_lock bit
3466            for train result */
3467         reg = FDI_RX_IMR(pipe);
3468         temp = I915_READ(reg);
3469         temp &= ~FDI_RX_SYMBOL_LOCK;
3470         temp &= ~FDI_RX_BIT_LOCK;
3471         I915_WRITE(reg, temp);
3472
3473         POSTING_READ(reg);
3474         udelay(150);
3475
3476         /* enable CPU FDI TX and PCH FDI RX */
3477         reg = FDI_TX_CTL(pipe);
3478         temp = I915_READ(reg);
3479         temp &= ~FDI_DP_PORT_WIDTH_MASK;
3480         temp |= FDI_DP_PORT_WIDTH(intel_crtc->config->fdi_lanes);
3481         temp &= ~FDI_LINK_TRAIN_NONE;
3482         temp |= FDI_LINK_TRAIN_PATTERN_1;
3483         temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
3484         /* SNB-B */
3485         temp |= FDI_LINK_TRAIN_400MV_0DB_SNB_B;
3486         I915_WRITE(reg, temp | FDI_TX_ENABLE);
3487
3488         I915_WRITE(FDI_RX_MISC(pipe),
3489                    FDI_RX_TP1_TO_TP2_48 | FDI_RX_FDI_DELAY_90);
3490
3491         reg = FDI_RX_CTL(pipe);
3492         temp = I915_READ(reg);
3493         if (HAS_PCH_CPT(dev)) {
3494                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
3495                 temp |= FDI_LINK_TRAIN_PATTERN_1_CPT;
3496         } else {
3497                 temp &= ~FDI_LINK_TRAIN_NONE;
3498                 temp |= FDI_LINK_TRAIN_PATTERN_1;
3499         }
3500         I915_WRITE(reg, temp | FDI_RX_ENABLE);
3501
3502         POSTING_READ(reg);
3503         udelay(150);
3504
3505         for (i = 0; i < 4; i++) {
3506                 reg = FDI_TX_CTL(pipe);
3507                 temp = I915_READ(reg);
3508                 temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
3509                 temp |= snb_b_fdi_train_param[i];
3510                 I915_WRITE(reg, temp);
3511
3512                 POSTING_READ(reg);
3513                 udelay(500);
3514
3515                 for (retry = 0; retry < 5; retry++) {
3516                         reg = FDI_RX_IIR(pipe);
3517                         temp = I915_READ(reg);
3518                         DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
3519                         if (temp & FDI_RX_BIT_LOCK) {
3520                                 I915_WRITE(reg, temp | FDI_RX_BIT_LOCK);
3521                                 DRM_DEBUG_KMS("FDI train 1 done.\n");
3522                                 break;
3523                         }
3524                         udelay(50);
3525                 }
3526                 if (retry < 5)
3527                         break;
3528         }
3529         if (i == 4)
3530                 DRM_ERROR("FDI train 1 fail!\n");
3531
3532         /* Train 2 */
3533         reg = FDI_TX_CTL(pipe);
3534         temp = I915_READ(reg);
3535         temp &= ~FDI_LINK_TRAIN_NONE;
3536         temp |= FDI_LINK_TRAIN_PATTERN_2;
3537         if (IS_GEN6(dev)) {
3538                 temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
3539                 /* SNB-B */
3540                 temp |= FDI_LINK_TRAIN_400MV_0DB_SNB_B;
3541         }
3542         I915_WRITE(reg, temp);
3543
3544         reg = FDI_RX_CTL(pipe);
3545         temp = I915_READ(reg);
3546         if (HAS_PCH_CPT(dev)) {
3547                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
3548                 temp |= FDI_LINK_TRAIN_PATTERN_2_CPT;
3549         } else {
3550                 temp &= ~FDI_LINK_TRAIN_NONE;
3551                 temp |= FDI_LINK_TRAIN_PATTERN_2;
3552         }
3553         I915_WRITE(reg, temp);
3554
3555         POSTING_READ(reg);
3556         udelay(150);
3557
3558         for (i = 0; i < 4; i++) {
3559                 reg = FDI_TX_CTL(pipe);
3560                 temp = I915_READ(reg);
3561                 temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
3562                 temp |= snb_b_fdi_train_param[i];
3563                 I915_WRITE(reg, temp);
3564
3565                 POSTING_READ(reg);
3566                 udelay(500);
3567
3568                 for (retry = 0; retry < 5; retry++) {
3569                         reg = FDI_RX_IIR(pipe);
3570                         temp = I915_READ(reg);
3571                         DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
3572                         if (temp & FDI_RX_SYMBOL_LOCK) {
3573                                 I915_WRITE(reg, temp | FDI_RX_SYMBOL_LOCK);
3574                                 DRM_DEBUG_KMS("FDI train 2 done.\n");
3575                                 break;
3576                         }
3577                         udelay(50);
3578                 }
3579                 if (retry < 5)
3580                         break;
3581         }
3582         if (i == 4)
3583                 DRM_ERROR("FDI train 2 fail!\n");
3584
3585         DRM_DEBUG_KMS("FDI train done.\n");
3586 }
3587
3588 /* Manual link training for Ivy Bridge A0 parts */
3589 static void ivb_manual_fdi_link_train(struct drm_crtc *crtc)
3590 {
3591         struct drm_device *dev = crtc->dev;
3592         struct drm_i915_private *dev_priv = to_i915(dev);
3593         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
3594         int pipe = intel_crtc->pipe;
3595         i915_reg_t reg;
3596         u32 temp, i, j;
3597
3598         /* Train 1: umask FDI RX Interrupt symbol_lock and bit_lock bit
3599            for train result */
3600         reg = FDI_RX_IMR(pipe);
3601         temp = I915_READ(reg);
3602         temp &= ~FDI_RX_SYMBOL_LOCK;
3603         temp &= ~FDI_RX_BIT_LOCK;
3604         I915_WRITE(reg, temp);
3605
3606         POSTING_READ(reg);
3607         udelay(150);
3608
3609         DRM_DEBUG_KMS("FDI_RX_IIR before link train 0x%x\n",
3610                       I915_READ(FDI_RX_IIR(pipe)));
3611
3612         /* Try each vswing and preemphasis setting twice before moving on */
3613         for (j = 0; j < ARRAY_SIZE(snb_b_fdi_train_param) * 2; j++) {
3614                 /* disable first in case we need to retry */
3615                 reg = FDI_TX_CTL(pipe);
3616                 temp = I915_READ(reg);
3617                 temp &= ~(FDI_LINK_TRAIN_AUTO | FDI_LINK_TRAIN_NONE_IVB);
3618                 temp &= ~FDI_TX_ENABLE;
3619                 I915_WRITE(reg, temp);
3620
3621                 reg = FDI_RX_CTL(pipe);
3622                 temp = I915_READ(reg);
3623                 temp &= ~FDI_LINK_TRAIN_AUTO;
3624                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
3625                 temp &= ~FDI_RX_ENABLE;
3626                 I915_WRITE(reg, temp);
3627
3628                 /* enable CPU FDI TX and PCH FDI RX */
3629                 reg = FDI_TX_CTL(pipe);
3630                 temp = I915_READ(reg);
3631                 temp &= ~FDI_DP_PORT_WIDTH_MASK;
3632                 temp |= FDI_DP_PORT_WIDTH(intel_crtc->config->fdi_lanes);
3633                 temp |= FDI_LINK_TRAIN_PATTERN_1_IVB;
3634                 temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
3635                 temp |= snb_b_fdi_train_param[j/2];
3636                 temp |= FDI_COMPOSITE_SYNC;
3637                 I915_WRITE(reg, temp | FDI_TX_ENABLE);
3638
3639                 I915_WRITE(FDI_RX_MISC(pipe),
3640                            FDI_RX_TP1_TO_TP2_48 | FDI_RX_FDI_DELAY_90);
3641
3642                 reg = FDI_RX_CTL(pipe);
3643                 temp = I915_READ(reg);
3644                 temp |= FDI_LINK_TRAIN_PATTERN_1_CPT;
3645                 temp |= FDI_COMPOSITE_SYNC;
3646                 I915_WRITE(reg, temp | FDI_RX_ENABLE);
3647
3648                 POSTING_READ(reg);
3649                 udelay(1); /* should be 0.5us */
3650
3651                 for (i = 0; i < 4; i++) {
3652                         reg = FDI_RX_IIR(pipe);
3653                         temp = I915_READ(reg);
3654                         DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
3655
3656                         if (temp & FDI_RX_BIT_LOCK ||
3657                             (I915_READ(reg) & FDI_RX_BIT_LOCK)) {
3658                                 I915_WRITE(reg, temp | FDI_RX_BIT_LOCK);
3659                                 DRM_DEBUG_KMS("FDI train 1 done, level %i.\n",
3660                                               i);
3661                                 break;
3662                         }
3663                         udelay(1); /* should be 0.5us */
3664                 }
3665                 if (i == 4) {
3666                         DRM_DEBUG_KMS("FDI train 1 fail on vswing %d\n", j / 2);
3667                         continue;
3668                 }
3669
3670                 /* Train 2 */
3671                 reg = FDI_TX_CTL(pipe);
3672                 temp = I915_READ(reg);
3673                 temp &= ~FDI_LINK_TRAIN_NONE_IVB;
3674                 temp |= FDI_LINK_TRAIN_PATTERN_2_IVB;
3675                 I915_WRITE(reg, temp);
3676
3677                 reg = FDI_RX_CTL(pipe);
3678                 temp = I915_READ(reg);
3679                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
3680                 temp |= FDI_LINK_TRAIN_PATTERN_2_CPT;
3681                 I915_WRITE(reg, temp);
3682
3683                 POSTING_READ(reg);
3684                 udelay(2); /* should be 1.5us */
3685
3686                 for (i = 0; i < 4; i++) {
3687                         reg = FDI_RX_IIR(pipe);
3688                         temp = I915_READ(reg);
3689                         DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
3690
3691                         if (temp & FDI_RX_SYMBOL_LOCK ||
3692                             (I915_READ(reg) & FDI_RX_SYMBOL_LOCK)) {
3693                                 I915_WRITE(reg, temp | FDI_RX_SYMBOL_LOCK);
3694                                 DRM_DEBUG_KMS("FDI train 2 done, level %i.\n",
3695                                               i);
3696                                 goto train_done;
3697                         }
3698                         udelay(2); /* should be 1.5us */
3699                 }
3700                 if (i == 4)
3701                         DRM_DEBUG_KMS("FDI train 2 fail on vswing %d\n", j / 2);
3702         }
3703
3704 train_done:
3705         DRM_DEBUG_KMS("FDI train done.\n");
3706 }
3707
3708 static void ironlake_fdi_pll_enable(struct intel_crtc *intel_crtc)
3709 {
3710         struct drm_device *dev = intel_crtc->base.dev;
3711         struct drm_i915_private *dev_priv = to_i915(dev);
3712         int pipe = intel_crtc->pipe;
3713         i915_reg_t reg;
3714         u32 temp;
3715
3716         /* enable PCH FDI RX PLL, wait warmup plus DMI latency */
3717         reg = FDI_RX_CTL(pipe);
3718         temp = I915_READ(reg);
3719         temp &= ~(FDI_DP_PORT_WIDTH_MASK | (0x7 << 16));
3720         temp |= FDI_DP_PORT_WIDTH(intel_crtc->config->fdi_lanes);
3721         temp |= (I915_READ(PIPECONF(pipe)) & PIPECONF_BPC_MASK) << 11;
3722         I915_WRITE(reg, temp | FDI_RX_PLL_ENABLE);
3723
3724         POSTING_READ(reg);
3725         udelay(200);
3726
3727         /* Switch from Rawclk to PCDclk */
3728         temp = I915_READ(reg);
3729         I915_WRITE(reg, temp | FDI_PCDCLK);
3730
3731         POSTING_READ(reg);
3732         udelay(200);
3733
3734         /* Enable CPU FDI TX PLL, always on for Ironlake */
3735         reg = FDI_TX_CTL(pipe);
3736         temp = I915_READ(reg);
3737         if ((temp & FDI_TX_PLL_ENABLE) == 0) {
3738                 I915_WRITE(reg, temp | FDI_TX_PLL_ENABLE);
3739
3740                 POSTING_READ(reg);
3741                 udelay(100);
3742         }
3743 }
3744
3745 static void ironlake_fdi_pll_disable(struct intel_crtc *intel_crtc)
3746 {
3747         struct drm_device *dev = intel_crtc->base.dev;
3748         struct drm_i915_private *dev_priv = to_i915(dev);
3749         int pipe = intel_crtc->pipe;
3750         i915_reg_t reg;
3751         u32 temp;
3752
3753         /* Switch from PCDclk to Rawclk */
3754         reg = FDI_RX_CTL(pipe);
3755         temp = I915_READ(reg);
3756         I915_WRITE(reg, temp & ~FDI_PCDCLK);
3757
3758         /* Disable CPU FDI TX PLL */
3759         reg = FDI_TX_CTL(pipe);
3760         temp = I915_READ(reg);
3761         I915_WRITE(reg, temp & ~FDI_TX_PLL_ENABLE);
3762
3763         POSTING_READ(reg);
3764         udelay(100);
3765
3766         reg = FDI_RX_CTL(pipe);
3767         temp = I915_READ(reg);
3768         I915_WRITE(reg, temp & ~FDI_RX_PLL_ENABLE);
3769
3770         /* Wait for the clocks to turn off. */
3771         POSTING_READ(reg);
3772         udelay(100);
3773 }
3774
3775 static void ironlake_fdi_disable(struct drm_crtc *crtc)
3776 {
3777         struct drm_device *dev = crtc->dev;
3778         struct drm_i915_private *dev_priv = to_i915(dev);
3779         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
3780         int pipe = intel_crtc->pipe;
3781         i915_reg_t reg;
3782         u32 temp;
3783
3784         /* disable CPU FDI tx and PCH FDI rx */
3785         reg = FDI_TX_CTL(pipe);
3786         temp = I915_READ(reg);
3787         I915_WRITE(reg, temp & ~FDI_TX_ENABLE);
3788         POSTING_READ(reg);
3789
3790         reg = FDI_RX_CTL(pipe);
3791         temp = I915_READ(reg);
3792         temp &= ~(0x7 << 16);
3793         temp |= (I915_READ(PIPECONF(pipe)) & PIPECONF_BPC_MASK) << 11;
3794         I915_WRITE(reg, temp & ~FDI_RX_ENABLE);
3795
3796         POSTING_READ(reg);
3797         udelay(100);
3798
3799         /* Ironlake workaround, disable clock pointer after downing FDI */
3800         if (HAS_PCH_IBX(dev))
3801                 I915_WRITE(FDI_RX_CHICKEN(pipe), FDI_RX_PHASE_SYNC_POINTER_OVR);
3802
3803         /* still set train pattern 1 */
3804         reg = FDI_TX_CTL(pipe);
3805         temp = I915_READ(reg);
3806         temp &= ~FDI_LINK_TRAIN_NONE;
3807         temp |= FDI_LINK_TRAIN_PATTERN_1;
3808         I915_WRITE(reg, temp);
3809
3810         reg = FDI_RX_CTL(pipe);
3811         temp = I915_READ(reg);
3812         if (HAS_PCH_CPT(dev)) {
3813                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
3814                 temp |= FDI_LINK_TRAIN_PATTERN_1_CPT;
3815         } else {
3816                 temp &= ~FDI_LINK_TRAIN_NONE;
3817                 temp |= FDI_LINK_TRAIN_PATTERN_1;
3818         }
3819         /* BPC in FDI rx is consistent with that in PIPECONF */
3820         temp &= ~(0x07 << 16);
3821         temp |= (I915_READ(PIPECONF(pipe)) & PIPECONF_BPC_MASK) << 11;
3822         I915_WRITE(reg, temp);
3823
3824         POSTING_READ(reg);
3825         udelay(100);
3826 }
3827
3828 bool intel_has_pending_fb_unpin(struct drm_device *dev)
3829 {
3830         struct intel_crtc *crtc;
3831
3832         /* Note that we don't need to be called with mode_config.lock here
3833          * as our list of CRTC objects is static for the lifetime of the
3834          * device and so cannot disappear as we iterate. Similarly, we can
3835          * happily treat the predicates as racy, atomic checks as userspace
3836          * cannot claim and pin a new fb without at least acquring the
3837          * struct_mutex and so serialising with us.
3838          */
3839         for_each_intel_crtc(dev, crtc) {
3840                 if (atomic_read(&crtc->unpin_work_count) == 0)
3841                         continue;
3842
3843                 if (crtc->flip_work)
3844                         intel_wait_for_vblank(dev, crtc->pipe);
3845
3846                 return true;
3847         }
3848
3849         return false;
3850 }
3851
3852 static void page_flip_completed(struct intel_crtc *intel_crtc)
3853 {
3854         struct drm_i915_private *dev_priv = to_i915(intel_crtc->base.dev);
3855         struct intel_flip_work *work = intel_crtc->flip_work;
3856
3857         intel_crtc->flip_work = NULL;
3858
3859         if (work->event)
3860                 drm_crtc_send_vblank_event(&intel_crtc->base, work->event);
3861
3862         drm_crtc_vblank_put(&intel_crtc->base);
3863
3864         wake_up_all(&dev_priv->pending_flip_queue);
3865         queue_work(dev_priv->wq, &work->unpin_work);
3866
3867         trace_i915_flip_complete(intel_crtc->plane,
3868                                  work->pending_flip_obj);
3869 }
3870
3871 static int intel_crtc_wait_for_pending_flips(struct drm_crtc *crtc)
3872 {
3873         struct drm_device *dev = crtc->dev;
3874         struct drm_i915_private *dev_priv = to_i915(dev);
3875         long ret;
3876
3877         WARN_ON(waitqueue_active(&dev_priv->pending_flip_queue));
3878
3879         ret = wait_event_interruptible_timeout(
3880                                         dev_priv->pending_flip_queue,
3881                                         !intel_crtc_has_pending_flip(crtc),
3882                                         60*HZ);
3883
3884         if (ret < 0)
3885                 return ret;
3886
3887         if (ret == 0) {
3888                 struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
3889                 struct intel_flip_work *work;
3890
3891                 spin_lock_irq(&dev->event_lock);
3892                 work = intel_crtc->flip_work;
3893                 if (work && !is_mmio_work(work)) {
3894                         WARN_ONCE(1, "Removing stuck page flip\n");
3895                         page_flip_completed(intel_crtc);
3896                 }
3897                 spin_unlock_irq(&dev->event_lock);
3898         }
3899
3900         return 0;
3901 }
3902
3903 static void lpt_disable_iclkip(struct drm_i915_private *dev_priv)
3904 {
3905         u32 temp;
3906
3907         I915_WRITE(PIXCLK_GATE, PIXCLK_GATE_GATE);
3908
3909         mutex_lock(&dev_priv->sb_lock);
3910
3911         temp = intel_sbi_read(dev_priv, SBI_SSCCTL6, SBI_ICLK);
3912         temp |= SBI_SSCCTL_DISABLE;
3913         intel_sbi_write(dev_priv, SBI_SSCCTL6, temp, SBI_ICLK);
3914
3915         mutex_unlock(&dev_priv->sb_lock);
3916 }
3917
3918 /* Program iCLKIP clock to the desired frequency */
3919 static void lpt_program_iclkip(struct drm_crtc *crtc)
3920 {
3921         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
3922         int clock = to_intel_crtc(crtc)->config->base.adjusted_mode.crtc_clock;
3923         u32 divsel, phaseinc, auxdiv, phasedir = 0;
3924         u32 temp;
3925
3926         lpt_disable_iclkip(dev_priv);
3927
3928         /* The iCLK virtual clock root frequency is in MHz,
3929          * but the adjusted_mode->crtc_clock in in KHz. To get the
3930          * divisors, it is necessary to divide one by another, so we
3931          * convert the virtual clock precision to KHz here for higher
3932          * precision.
3933          */
3934         for (auxdiv = 0; auxdiv < 2; auxdiv++) {
3935                 u32 iclk_virtual_root_freq = 172800 * 1000;
3936                 u32 iclk_pi_range = 64;
3937                 u32 desired_divisor;
3938
3939                 desired_divisor = DIV_ROUND_CLOSEST(iclk_virtual_root_freq,
3940                                                     clock << auxdiv);
3941                 divsel = (desired_divisor / iclk_pi_range) - 2;
3942                 phaseinc = desired_divisor % iclk_pi_range;
3943
3944                 /*
3945                  * Near 20MHz is a corner case which is
3946                  * out of range for the 7-bit divisor
3947                  */
3948                 if (divsel <= 0x7f)
3949                         break;
3950         }
3951
3952         /* This should not happen with any sane values */
3953         WARN_ON(SBI_SSCDIVINTPHASE_DIVSEL(divsel) &
3954                 ~SBI_SSCDIVINTPHASE_DIVSEL_MASK);
3955         WARN_ON(SBI_SSCDIVINTPHASE_DIR(phasedir) &
3956                 ~SBI_SSCDIVINTPHASE_INCVAL_MASK);
3957
3958         DRM_DEBUG_KMS("iCLKIP clock: found settings for %dKHz refresh rate: auxdiv=%x, divsel=%x, phasedir=%x, phaseinc=%x\n",
3959                         clock,
3960                         auxdiv,
3961                         divsel,
3962                         phasedir,
3963                         phaseinc);
3964
3965         mutex_lock(&dev_priv->sb_lock);
3966
3967         /* Program SSCDIVINTPHASE6 */
3968         temp = intel_sbi_read(dev_priv, SBI_SSCDIVINTPHASE6, SBI_ICLK);
3969         temp &= ~SBI_SSCDIVINTPHASE_DIVSEL_MASK;
3970         temp |= SBI_SSCDIVINTPHASE_DIVSEL(divsel);
3971         temp &= ~SBI_SSCDIVINTPHASE_INCVAL_MASK;
3972         temp |= SBI_SSCDIVINTPHASE_INCVAL(phaseinc);
3973         temp |= SBI_SSCDIVINTPHASE_DIR(phasedir);
3974         temp |= SBI_SSCDIVINTPHASE_PROPAGATE;
3975         intel_sbi_write(dev_priv, SBI_SSCDIVINTPHASE6, temp, SBI_ICLK);
3976
3977         /* Program SSCAUXDIV */
3978         temp = intel_sbi_read(dev_priv, SBI_SSCAUXDIV6, SBI_ICLK);
3979         temp &= ~SBI_SSCAUXDIV_FINALDIV2SEL(1);
3980         temp |= SBI_SSCAUXDIV_FINALDIV2SEL(auxdiv);
3981         intel_sbi_write(dev_priv, SBI_SSCAUXDIV6, temp, SBI_ICLK);
3982
3983         /* Enable modulator and associated divider */
3984         temp = intel_sbi_read(dev_priv, SBI_SSCCTL6, SBI_ICLK);
3985         temp &= ~SBI_SSCCTL_DISABLE;
3986         intel_sbi_write(dev_priv, SBI_SSCCTL6, temp, SBI_ICLK);
3987
3988         mutex_unlock(&dev_priv->sb_lock);
3989
3990         /* Wait for initialization time */
3991         udelay(24);
3992
3993         I915_WRITE(PIXCLK_GATE, PIXCLK_GATE_UNGATE);
3994 }
3995
3996 int lpt_get_iclkip(struct drm_i915_private *dev_priv)
3997 {
3998         u32 divsel, phaseinc, auxdiv;
3999         u32 iclk_virtual_root_freq = 172800 * 1000;
4000         u32 iclk_pi_range = 64;
4001         u32 desired_divisor;
4002         u32 temp;
4003
4004         if ((I915_READ(PIXCLK_GATE) & PIXCLK_GATE_UNGATE) == 0)
4005                 return 0;
4006
4007         mutex_lock(&dev_priv->sb_lock);
4008
4009         temp = intel_sbi_read(dev_priv, SBI_SSCCTL6, SBI_ICLK);
4010         if (temp & SBI_SSCCTL_DISABLE) {
4011                 mutex_unlock(&dev_priv->sb_lock);
4012                 return 0;
4013         }
4014
4015         temp = intel_sbi_read(dev_priv, SBI_SSCDIVINTPHASE6, SBI_ICLK);
4016         divsel = (temp & SBI_SSCDIVINTPHASE_DIVSEL_MASK) >>
4017                 SBI_SSCDIVINTPHASE_DIVSEL_SHIFT;
4018         phaseinc = (temp & SBI_SSCDIVINTPHASE_INCVAL_MASK) >>
4019                 SBI_SSCDIVINTPHASE_INCVAL_SHIFT;
4020
4021         temp = intel_sbi_read(dev_priv, SBI_SSCAUXDIV6, SBI_ICLK);
4022         auxdiv = (temp & SBI_SSCAUXDIV_FINALDIV2SEL_MASK) >>
4023                 SBI_SSCAUXDIV_FINALDIV2SEL_SHIFT;
4024
4025         mutex_unlock(&dev_priv->sb_lock);
4026
4027         desired_divisor = (divsel + 2) * iclk_pi_range + phaseinc;
4028
4029         return DIV_ROUND_CLOSEST(iclk_virtual_root_freq,
4030                                  desired_divisor << auxdiv);
4031 }
4032
4033 static void ironlake_pch_transcoder_set_timings(struct intel_crtc *crtc,
4034                                                 enum pipe pch_transcoder)
4035 {
4036         struct drm_device *dev = crtc->base.dev;
4037         struct drm_i915_private *dev_priv = to_i915(dev);
4038         enum transcoder cpu_transcoder = crtc->config->cpu_transcoder;
4039
4040         I915_WRITE(PCH_TRANS_HTOTAL(pch_transcoder),
4041                    I915_READ(HTOTAL(cpu_transcoder)));
4042         I915_WRITE(PCH_TRANS_HBLANK(pch_transcoder),
4043                    I915_READ(HBLANK(cpu_transcoder)));
4044         I915_WRITE(PCH_TRANS_HSYNC(pch_transcoder),
4045                    I915_READ(HSYNC(cpu_transcoder)));
4046
4047         I915_WRITE(PCH_TRANS_VTOTAL(pch_transcoder),
4048                    I915_READ(VTOTAL(cpu_transcoder)));
4049         I915_WRITE(PCH_TRANS_VBLANK(pch_transcoder),
4050                    I915_READ(VBLANK(cpu_transcoder)));
4051         I915_WRITE(PCH_TRANS_VSYNC(pch_transcoder),
4052                    I915_READ(VSYNC(cpu_transcoder)));
4053         I915_WRITE(PCH_TRANS_VSYNCSHIFT(pch_transcoder),
4054                    I915_READ(VSYNCSHIFT(cpu_transcoder)));
4055 }
4056
4057 static void cpt_set_fdi_bc_bifurcation(struct drm_device *dev, bool enable)
4058 {
4059         struct drm_i915_private *dev_priv = to_i915(dev);
4060         uint32_t temp;
4061
4062         temp = I915_READ(SOUTH_CHICKEN1);
4063         if (!!(temp & FDI_BC_BIFURCATION_SELECT) == enable)
4064                 return;
4065
4066         WARN_ON(I915_READ(FDI_RX_CTL(PIPE_B)) & FDI_RX_ENABLE);
4067         WARN_ON(I915_READ(FDI_RX_CTL(PIPE_C)) & FDI_RX_ENABLE);
4068
4069         temp &= ~FDI_BC_BIFURCATION_SELECT;
4070         if (enable)
4071                 temp |= FDI_BC_BIFURCATION_SELECT;
4072
4073         DRM_DEBUG_KMS("%sabling fdi C rx\n", enable ? "en" : "dis");
4074         I915_WRITE(SOUTH_CHICKEN1, temp);
4075         POSTING_READ(SOUTH_CHICKEN1);
4076 }
4077
4078 static void ivybridge_update_fdi_bc_bifurcation(struct intel_crtc *intel_crtc)
4079 {
4080         struct drm_device *dev = intel_crtc->base.dev;
4081
4082         switch (intel_crtc->pipe) {
4083         case PIPE_A:
4084                 break;
4085         case PIPE_B:
4086                 if (intel_crtc->config->fdi_lanes > 2)
4087                         cpt_set_fdi_bc_bifurcation(dev, false);
4088                 else
4089                         cpt_set_fdi_bc_bifurcation(dev, true);
4090
4091                 break;
4092         case PIPE_C:
4093                 cpt_set_fdi_bc_bifurcation(dev, true);
4094
4095                 break;
4096         default:
4097                 BUG();
4098         }
4099 }
4100
4101 /* Return which DP Port should be selected for Transcoder DP control */
4102 static enum port
4103 intel_trans_dp_port_sel(struct drm_crtc *crtc)
4104 {
4105         struct drm_device *dev = crtc->dev;
4106         struct intel_encoder *encoder;
4107
4108         for_each_encoder_on_crtc(dev, crtc, encoder) {
4109                 if (encoder->type == INTEL_OUTPUT_DP ||
4110                     encoder->type == INTEL_OUTPUT_EDP)
4111                         return enc_to_dig_port(&encoder->base)->port;
4112         }
4113
4114         return -1;
4115 }
4116
4117 /*
4118  * Enable PCH resources required for PCH ports:
4119  *   - PCH PLLs
4120  *   - FDI training & RX/TX
4121  *   - update transcoder timings
4122  *   - DP transcoding bits
4123  *   - transcoder
4124  */
4125 static void ironlake_pch_enable(struct drm_crtc *crtc)
4126 {
4127         struct drm_device *dev = crtc->dev;
4128         struct drm_i915_private *dev_priv = to_i915(dev);
4129         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4130         int pipe = intel_crtc->pipe;
4131         u32 temp;
4132
4133         assert_pch_transcoder_disabled(dev_priv, pipe);
4134
4135         if (IS_IVYBRIDGE(dev))
4136                 ivybridge_update_fdi_bc_bifurcation(intel_crtc);
4137
4138         /* Write the TU size bits before fdi link training, so that error
4139          * detection works. */
4140         I915_WRITE(FDI_RX_TUSIZE1(pipe),
4141                    I915_READ(PIPE_DATA_M1(pipe)) & TU_SIZE_MASK);
4142
4143         /* For PCH output, training FDI link */
4144         dev_priv->display.fdi_link_train(crtc);
4145
4146         /* We need to program the right clock selection before writing the pixel
4147          * mutliplier into the DPLL. */
4148         if (HAS_PCH_CPT(dev)) {
4149                 u32 sel;
4150
4151                 temp = I915_READ(PCH_DPLL_SEL);
4152                 temp |= TRANS_DPLL_ENABLE(pipe);
4153                 sel = TRANS_DPLLB_SEL(pipe);
4154                 if (intel_crtc->config->shared_dpll ==
4155                     intel_get_shared_dpll_by_id(dev_priv, DPLL_ID_PCH_PLL_B))
4156                         temp |= sel;
4157                 else
4158                         temp &= ~sel;
4159                 I915_WRITE(PCH_DPLL_SEL, temp);
4160         }
4161
4162         /* XXX: pch pll's can be enabled any time before we enable the PCH
4163          * transcoder, and we actually should do this to not upset any PCH
4164          * transcoder that already use the clock when we share it.
4165          *
4166          * Note that enable_shared_dpll tries to do the right thing, but
4167          * get_shared_dpll unconditionally resets the pll - we need that to have
4168          * the right LVDS enable sequence. */
4169         intel_enable_shared_dpll(intel_crtc);
4170
4171         /* set transcoder timing, panel must allow it */
4172         assert_panel_unlocked(dev_priv, pipe);
4173         ironlake_pch_transcoder_set_timings(intel_crtc, pipe);
4174
4175         intel_fdi_normal_train(crtc);
4176
4177         /* For PCH DP, enable TRANS_DP_CTL */
4178         if (HAS_PCH_CPT(dev) && intel_crtc_has_dp_encoder(intel_crtc->config)) {
4179                 const struct drm_display_mode *adjusted_mode =
4180                         &intel_crtc->config->base.adjusted_mode;
4181                 u32 bpc = (I915_READ(PIPECONF(pipe)) & PIPECONF_BPC_MASK) >> 5;
4182                 i915_reg_t reg = TRANS_DP_CTL(pipe);
4183                 temp = I915_READ(reg);
4184                 temp &= ~(TRANS_DP_PORT_SEL_MASK |
4185                           TRANS_DP_SYNC_MASK |
4186                           TRANS_DP_BPC_MASK);
4187                 temp |= TRANS_DP_OUTPUT_ENABLE;
4188                 temp |= bpc << 9; /* same format but at 11:9 */
4189
4190                 if (adjusted_mode->flags & DRM_MODE_FLAG_PHSYNC)
4191                         temp |= TRANS_DP_HSYNC_ACTIVE_HIGH;
4192                 if (adjusted_mode->flags & DRM_MODE_FLAG_PVSYNC)
4193                         temp |= TRANS_DP_VSYNC_ACTIVE_HIGH;
4194
4195                 switch (intel_trans_dp_port_sel(crtc)) {
4196                 case PORT_B:
4197                         temp |= TRANS_DP_PORT_SEL_B;
4198                         break;
4199                 case PORT_C:
4200                         temp |= TRANS_DP_PORT_SEL_C;
4201                         break;
4202                 case PORT_D:
4203                         temp |= TRANS_DP_PORT_SEL_D;
4204                         break;
4205                 default:
4206                         BUG();
4207                 }
4208
4209                 I915_WRITE(reg, temp);
4210         }
4211
4212         ironlake_enable_pch_transcoder(dev_priv, pipe);
4213 }
4214
4215 static void lpt_pch_enable(struct drm_crtc *crtc)
4216 {
4217         struct drm_device *dev = crtc->dev;
4218         struct drm_i915_private *dev_priv = to_i915(dev);
4219         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4220         enum transcoder cpu_transcoder = intel_crtc->config->cpu_transcoder;
4221
4222         assert_pch_transcoder_disabled(dev_priv, TRANSCODER_A);
4223
4224         lpt_program_iclkip(crtc);
4225
4226         /* Set transcoder timing. */
4227         ironlake_pch_transcoder_set_timings(intel_crtc, PIPE_A);
4228
4229         lpt_enable_pch_transcoder(dev_priv, cpu_transcoder);
4230 }
4231
4232 static void cpt_verify_modeset(struct drm_device *dev, int pipe)
4233 {
4234         struct drm_i915_private *dev_priv = to_i915(dev);
4235         i915_reg_t dslreg = PIPEDSL(pipe);
4236         u32 temp;
4237
4238         temp = I915_READ(dslreg);
4239         udelay(500);
4240         if (wait_for(I915_READ(dslreg) != temp, 5)) {
4241                 if (wait_for(I915_READ(dslreg) != temp, 5))
4242                         DRM_ERROR("mode set failed: pipe %c stuck\n", pipe_name(pipe));
4243         }
4244 }
4245
4246 static int
4247 skl_update_scaler(struct intel_crtc_state *crtc_state, bool force_detach,
4248                   unsigned scaler_user, int *scaler_id, unsigned int rotation,
4249                   int src_w, int src_h, int dst_w, int dst_h)
4250 {
4251         struct intel_crtc_scaler_state *scaler_state =
4252                 &crtc_state->scaler_state;
4253         struct intel_crtc *intel_crtc =
4254                 to_intel_crtc(crtc_state->base.crtc);
4255         int need_scaling;
4256
4257         need_scaling = intel_rotation_90_or_270(rotation) ?
4258                 (src_h != dst_w || src_w != dst_h):
4259                 (src_w != dst_w || src_h != dst_h);
4260
4261         /*
4262          * if plane is being disabled or scaler is no more required or force detach
4263          *  - free scaler binded to this plane/crtc
4264          *  - in order to do this, update crtc->scaler_usage
4265          *
4266          * Here scaler state in crtc_state is set free so that
4267          * scaler can be assigned to other user. Actual register
4268          * update to free the scaler is done in plane/panel-fit programming.
4269          * For this purpose crtc/plane_state->scaler_id isn't reset here.
4270          */
4271         if (force_detach || !need_scaling) {
4272                 if (*scaler_id >= 0) {
4273                         scaler_state->scaler_users &= ~(1 << scaler_user);
4274                         scaler_state->scalers[*scaler_id].in_use = 0;
4275
4276                         DRM_DEBUG_KMS("scaler_user index %u.%u: "
4277                                 "Staged freeing scaler id %d scaler_users = 0x%x\n",
4278                                 intel_crtc->pipe, scaler_user, *scaler_id,
4279                                 scaler_state->scaler_users);
4280                         *scaler_id = -1;
4281                 }
4282                 return 0;
4283         }
4284
4285         /* range checks */
4286         if (src_w < SKL_MIN_SRC_W || src_h < SKL_MIN_SRC_H ||
4287                 dst_w < SKL_MIN_DST_W || dst_h < SKL_MIN_DST_H ||
4288
4289                 src_w > SKL_MAX_SRC_W || src_h > SKL_MAX_SRC_H ||
4290                 dst_w > SKL_MAX_DST_W || dst_h > SKL_MAX_DST_H) {
4291                 DRM_DEBUG_KMS("scaler_user index %u.%u: src %ux%u dst %ux%u "
4292                         "size is out of scaler range\n",
4293                         intel_crtc->pipe, scaler_user, src_w, src_h, dst_w, dst_h);
4294                 return -EINVAL;
4295         }
4296
4297         /* mark this plane as a scaler user in crtc_state */
4298         scaler_state->scaler_users |= (1 << scaler_user);
4299         DRM_DEBUG_KMS("scaler_user index %u.%u: "
4300                 "staged scaling request for %ux%u->%ux%u scaler_users = 0x%x\n",
4301                 intel_crtc->pipe, scaler_user, src_w, src_h, dst_w, dst_h,
4302                 scaler_state->scaler_users);
4303
4304         return 0;
4305 }
4306
4307 /**
4308  * skl_update_scaler_crtc - Stages update to scaler state for a given crtc.
4309  *
4310  * @state: crtc's scaler state
4311  *
4312  * Return
4313  *     0 - scaler_usage updated successfully
4314  *    error - requested scaling cannot be supported or other error condition
4315  */
4316 int skl_update_scaler_crtc(struct intel_crtc_state *state)
4317 {
4318         struct intel_crtc *intel_crtc = to_intel_crtc(state->base.crtc);
4319         const struct drm_display_mode *adjusted_mode = &state->base.adjusted_mode;
4320
4321         DRM_DEBUG_KMS("Updating scaler for [CRTC:%d:%s] scaler_user index %u.%u\n",
4322                       intel_crtc->base.base.id, intel_crtc->base.name,
4323                       intel_crtc->pipe, SKL_CRTC_INDEX);
4324
4325         return skl_update_scaler(state, !state->base.active, SKL_CRTC_INDEX,
4326                 &state->scaler_state.scaler_id, BIT(DRM_ROTATE_0),
4327                 state->pipe_src_w, state->pipe_src_h,
4328                 adjusted_mode->crtc_hdisplay, adjusted_mode->crtc_vdisplay);
4329 }
4330
4331 /**
4332  * skl_update_scaler_plane - Stages update to scaler state for a given plane.
4333  *
4334  * @state: crtc's scaler state
4335  * @plane_state: atomic plane state to update
4336  *
4337  * Return
4338  *     0 - scaler_usage updated successfully
4339  *    error - requested scaling cannot be supported or other error condition
4340  */
4341 static int skl_update_scaler_plane(struct intel_crtc_state *crtc_state,
4342                                    struct intel_plane_state *plane_state)
4343 {
4344
4345         struct intel_crtc *intel_crtc = to_intel_crtc(crtc_state->base.crtc);
4346         struct intel_plane *intel_plane =
4347                 to_intel_plane(plane_state->base.plane);
4348         struct drm_framebuffer *fb = plane_state->base.fb;
4349         int ret;
4350
4351         bool force_detach = !fb || !plane_state->visible;
4352
4353         DRM_DEBUG_KMS("Updating scaler for [PLANE:%d:%s] scaler_user index %u.%u\n",
4354                       intel_plane->base.base.id, intel_plane->base.name,
4355                       intel_crtc->pipe, drm_plane_index(&intel_plane->base));
4356
4357         ret = skl_update_scaler(crtc_state, force_detach,
4358                                 drm_plane_index(&intel_plane->base),
4359                                 &plane_state->scaler_id,
4360                                 plane_state->base.rotation,
4361                                 drm_rect_width(&plane_state->src) >> 16,
4362                                 drm_rect_height(&plane_state->src) >> 16,
4363                                 drm_rect_width(&plane_state->dst),
4364                                 drm_rect_height(&plane_state->dst));
4365
4366         if (ret || plane_state->scaler_id < 0)
4367                 return ret;
4368
4369         /* check colorkey */
4370         if (plane_state->ckey.flags != I915_SET_COLORKEY_NONE) {
4371                 DRM_DEBUG_KMS("[PLANE:%d:%s] scaling with color key not allowed",
4372                               intel_plane->base.base.id,
4373                               intel_plane->base.name);
4374                 return -EINVAL;
4375         }
4376
4377         /* Check src format */
4378         switch (fb->pixel_format) {
4379         case DRM_FORMAT_RGB565:
4380         case DRM_FORMAT_XBGR8888:
4381         case DRM_FORMAT_XRGB8888:
4382         case DRM_FORMAT_ABGR8888:
4383         case DRM_FORMAT_ARGB8888:
4384         case DRM_FORMAT_XRGB2101010:
4385         case DRM_FORMAT_XBGR2101010:
4386         case DRM_FORMAT_YUYV:
4387         case DRM_FORMAT_YVYU:
4388         case DRM_FORMAT_UYVY:
4389         case DRM_FORMAT_VYUY:
4390                 break;
4391         default:
4392                 DRM_DEBUG_KMS("[PLANE:%d:%s] FB:%d unsupported scaling format 0x%x\n",
4393                               intel_plane->base.base.id, intel_plane->base.name,
4394                               fb->base.id, fb->pixel_format);
4395                 return -EINVAL;
4396         }
4397
4398         return 0;
4399 }
4400
4401 static void skylake_scaler_disable(struct intel_crtc *crtc)
4402 {
4403         int i;
4404
4405         for (i = 0; i < crtc->num_scalers; i++)
4406                 skl_detach_scaler(crtc, i);
4407 }
4408
4409 static void skylake_pfit_enable(struct intel_crtc *crtc)
4410 {
4411         struct drm_device *dev = crtc->base.dev;
4412         struct drm_i915_private *dev_priv = to_i915(dev);
4413         int pipe = crtc->pipe;
4414         struct intel_crtc_scaler_state *scaler_state =
4415                 &crtc->config->scaler_state;
4416
4417         DRM_DEBUG_KMS("for crtc_state = %p\n", crtc->config);
4418
4419         if (crtc->config->pch_pfit.enabled) {
4420                 int id;
4421
4422                 if (WARN_ON(crtc->config->scaler_state.scaler_id < 0)) {
4423                         DRM_ERROR("Requesting pfit without getting a scaler first\n");
4424                         return;
4425                 }
4426
4427                 id = scaler_state->scaler_id;
4428                 I915_WRITE(SKL_PS_CTRL(pipe, id), PS_SCALER_EN |
4429                         PS_FILTER_MEDIUM | scaler_state->scalers[id].mode);
4430                 I915_WRITE(SKL_PS_WIN_POS(pipe, id), crtc->config->pch_pfit.pos);
4431                 I915_WRITE(SKL_PS_WIN_SZ(pipe, id), crtc->config->pch_pfit.size);
4432
4433                 DRM_DEBUG_KMS("for crtc_state = %p scaler_id = %d\n", crtc->config, id);
4434         }
4435 }
4436
4437 static void ironlake_pfit_enable(struct intel_crtc *crtc)
4438 {
4439         struct drm_device *dev = crtc->base.dev;
4440         struct drm_i915_private *dev_priv = to_i915(dev);
4441         int pipe = crtc->pipe;
4442
4443         if (crtc->config->pch_pfit.enabled) {
4444                 /* Force use of hard-coded filter coefficients
4445                  * as some pre-programmed values are broken,
4446                  * e.g. x201.
4447                  */
4448                 if (IS_IVYBRIDGE(dev) || IS_HASWELL(dev))
4449                         I915_WRITE(PF_CTL(pipe), PF_ENABLE | PF_FILTER_MED_3x3 |
4450                                                  PF_PIPE_SEL_IVB(pipe));
4451                 else
4452                         I915_WRITE(PF_CTL(pipe), PF_ENABLE | PF_FILTER_MED_3x3);
4453                 I915_WRITE(PF_WIN_POS(pipe), crtc->config->pch_pfit.pos);
4454                 I915_WRITE(PF_WIN_SZ(pipe), crtc->config->pch_pfit.size);
4455         }
4456 }
4457
4458 void hsw_enable_ips(struct intel_crtc *crtc)
4459 {
4460         struct drm_device *dev = crtc->base.dev;
4461         struct drm_i915_private *dev_priv = to_i915(dev);
4462
4463         if (!crtc->config->ips_enabled)
4464                 return;
4465
4466         /*
4467          * We can only enable IPS after we enable a plane and wait for a vblank
4468          * This function is called from post_plane_update, which is run after
4469          * a vblank wait.
4470          */
4471
4472         assert_plane_enabled(dev_priv, crtc->plane);
4473         if (IS_BROADWELL(dev)) {
4474                 mutex_lock(&dev_priv->rps.hw_lock);
4475                 WARN_ON(sandybridge_pcode_write(dev_priv, DISPLAY_IPS_CONTROL, 0xc0000000));
4476                 mutex_unlock(&dev_priv->rps.hw_lock);
4477                 /* Quoting Art Runyan: "its not safe to expect any particular
4478                  * value in IPS_CTL bit 31 after enabling IPS through the
4479                  * mailbox." Moreover, the mailbox may return a bogus state,
4480                  * so we need to just enable it and continue on.
4481                  */
4482         } else {
4483                 I915_WRITE(IPS_CTL, IPS_ENABLE);
4484                 /* The bit only becomes 1 in the next vblank, so this wait here
4485                  * is essentially intel_wait_for_vblank. If we don't have this
4486                  * and don't wait for vblanks until the end of crtc_enable, then
4487                  * the HW state readout code will complain that the expected
4488                  * IPS_CTL value is not the one we read. */
4489                 if (intel_wait_for_register(dev_priv,
4490                                             IPS_CTL, IPS_ENABLE, IPS_ENABLE,
4491                                             50))
4492                         DRM_ERROR("Timed out waiting for IPS enable\n");
4493         }
4494 }
4495
4496 void hsw_disable_ips(struct intel_crtc *crtc)
4497 {
4498         struct drm_device *dev = crtc->base.dev;
4499         struct drm_i915_private *dev_priv = to_i915(dev);
4500
4501         if (!crtc->config->ips_enabled)
4502                 return;
4503
4504         assert_plane_enabled(dev_priv, crtc->plane);
4505         if (IS_BROADWELL(dev)) {
4506                 mutex_lock(&dev_priv->rps.hw_lock);
4507                 WARN_ON(sandybridge_pcode_write(dev_priv, DISPLAY_IPS_CONTROL, 0));
4508                 mutex_unlock(&dev_priv->rps.hw_lock);
4509                 /* wait for pcode to finish disabling IPS, which may take up to 42ms */
4510                 if (intel_wait_for_register(dev_priv,
4511                                             IPS_CTL, IPS_ENABLE, 0,
4512                                             42))
4513                         DRM_ERROR("Timed out waiting for IPS disable\n");
4514         } else {
4515                 I915_WRITE(IPS_CTL, 0);
4516                 POSTING_READ(IPS_CTL);
4517         }
4518
4519         /* We need to wait for a vblank before we can disable the plane. */
4520         intel_wait_for_vblank(dev, crtc->pipe);
4521 }
4522
4523 static void intel_crtc_dpms_overlay_disable(struct intel_crtc *intel_crtc)
4524 {
4525         if (intel_crtc->overlay) {
4526                 struct drm_device *dev = intel_crtc->base.dev;
4527                 struct drm_i915_private *dev_priv = to_i915(dev);
4528
4529                 mutex_lock(&dev->struct_mutex);
4530                 dev_priv->mm.interruptible = false;
4531                 (void) intel_overlay_switch_off(intel_crtc->overlay);
4532                 dev_priv->mm.interruptible = true;
4533                 mutex_unlock(&dev->struct_mutex);
4534         }
4535
4536         /* Let userspace switch the overlay on again. In most cases userspace
4537          * has to recompute where to put it anyway.
4538          */
4539 }
4540
4541 /**
4542  * intel_post_enable_primary - Perform operations after enabling primary plane
4543  * @crtc: the CRTC whose primary plane was just enabled
4544  *
4545  * Performs potentially sleeping operations that must be done after the primary
4546  * plane is enabled, such as updating FBC and IPS.  Note that this may be
4547  * called due to an explicit primary plane update, or due to an implicit
4548  * re-enable that is caused when a sprite plane is updated to no longer
4549  * completely hide the primary plane.
4550  */
4551 static void
4552 intel_post_enable_primary(struct drm_crtc *crtc)
4553 {
4554         struct drm_device *dev = crtc->dev;
4555         struct drm_i915_private *dev_priv = to_i915(dev);
4556         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4557         int pipe = intel_crtc->pipe;
4558
4559         /*
4560          * FIXME IPS should be fine as long as one plane is
4561          * enabled, but in practice it seems to have problems
4562          * when going from primary only to sprite only and vice
4563          * versa.
4564          */
4565         hsw_enable_ips(intel_crtc);
4566
4567         /*
4568          * Gen2 reports pipe underruns whenever all planes are disabled.
4569          * So don't enable underrun reporting before at least some planes
4570          * are enabled.
4571          * FIXME: Need to fix the logic to work when we turn off all planes
4572          * but leave the pipe running.
4573          */
4574         if (IS_GEN2(dev))
4575                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
4576
4577         /* Underruns don't always raise interrupts, so check manually. */
4578         intel_check_cpu_fifo_underruns(dev_priv);
4579         intel_check_pch_fifo_underruns(dev_priv);
4580 }
4581
4582 /* FIXME move all this to pre_plane_update() with proper state tracking */
4583 static void
4584 intel_pre_disable_primary(struct drm_crtc *crtc)
4585 {
4586         struct drm_device *dev = crtc->dev;
4587         struct drm_i915_private *dev_priv = to_i915(dev);
4588         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4589         int pipe = intel_crtc->pipe;
4590
4591         /*
4592          * Gen2 reports pipe underruns whenever all planes are disabled.
4593          * So diasble underrun reporting before all the planes get disabled.
4594          * FIXME: Need to fix the logic to work when we turn off all planes
4595          * but leave the pipe running.
4596          */
4597         if (IS_GEN2(dev))
4598                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, false);
4599
4600         /*
4601          * FIXME IPS should be fine as long as one plane is
4602          * enabled, but in practice it seems to have problems
4603          * when going from primary only to sprite only and vice
4604          * versa.
4605          */
4606         hsw_disable_ips(intel_crtc);
4607 }
4608
4609 /* FIXME get rid of this and use pre_plane_update */
4610 static void
4611 intel_pre_disable_primary_noatomic(struct drm_crtc *crtc)
4612 {
4613         struct drm_device *dev = crtc->dev;
4614         struct drm_i915_private *dev_priv = to_i915(dev);
4615         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4616         int pipe = intel_crtc->pipe;
4617
4618         intel_pre_disable_primary(crtc);
4619
4620         /*
4621          * Vblank time updates from the shadow to live plane control register
4622          * are blocked if the memory self-refresh mode is active at that
4623          * moment. So to make sure the plane gets truly disabled, disable
4624          * first the self-refresh mode. The self-refresh enable bit in turn
4625          * will be checked/applied by the HW only at the next frame start
4626          * event which is after the vblank start event, so we need to have a
4627          * wait-for-vblank between disabling the plane and the pipe.
4628          */
4629         if (HAS_GMCH_DISPLAY(dev)) {
4630                 intel_set_memory_cxsr(dev_priv, false);
4631                 dev_priv->wm.vlv.cxsr = false;
4632                 intel_wait_for_vblank(dev, pipe);
4633         }
4634 }
4635
4636 static void intel_post_plane_update(struct intel_crtc_state *old_crtc_state)
4637 {
4638         struct intel_crtc *crtc = to_intel_crtc(old_crtc_state->base.crtc);
4639         struct drm_atomic_state *old_state = old_crtc_state->base.state;
4640         struct intel_crtc_state *pipe_config =
4641                 to_intel_crtc_state(crtc->base.state);
4642         struct drm_device *dev = crtc->base.dev;
4643         struct drm_plane *primary = crtc->base.primary;
4644         struct drm_plane_state *old_pri_state =
4645                 drm_atomic_get_existing_plane_state(old_state, primary);
4646
4647         intel_frontbuffer_flip(dev, pipe_config->fb_bits);
4648
4649         crtc->wm.cxsr_allowed = true;
4650
4651         if (pipe_config->update_wm_post && pipe_config->base.active)
4652                 intel_update_watermarks(&crtc->base);
4653
4654         if (old_pri_state) {
4655                 struct intel_plane_state *primary_state =
4656                         to_intel_plane_state(primary->state);
4657                 struct intel_plane_state *old_primary_state =
4658                         to_intel_plane_state(old_pri_state);
4659
4660                 intel_fbc_post_update(crtc);
4661
4662                 if (primary_state->visible &&
4663                     (needs_modeset(&pipe_config->base) ||
4664                      !old_primary_state->visible))
4665                         intel_post_enable_primary(&crtc->base);
4666         }
4667 }
4668
4669 static void intel_pre_plane_update(struct intel_crtc_state *old_crtc_state)
4670 {
4671         struct intel_crtc *crtc = to_intel_crtc(old_crtc_state->base.crtc);
4672         struct drm_device *dev = crtc->base.dev;
4673         struct drm_i915_private *dev_priv = to_i915(dev);
4674         struct intel_crtc_state *pipe_config =
4675                 to_intel_crtc_state(crtc->base.state);
4676         struct drm_atomic_state *old_state = old_crtc_state->base.state;
4677         struct drm_plane *primary = crtc->base.primary;
4678         struct drm_plane_state *old_pri_state =
4679                 drm_atomic_get_existing_plane_state(old_state, primary);
4680         bool modeset = needs_modeset(&pipe_config->base);
4681
4682         if (old_pri_state) {
4683                 struct intel_plane_state *primary_state =
4684                         to_intel_plane_state(primary->state);
4685                 struct intel_plane_state *old_primary_state =
4686                         to_intel_plane_state(old_pri_state);
4687
4688                 intel_fbc_pre_update(crtc, pipe_config, primary_state);
4689
4690                 if (old_primary_state->visible &&
4691                     (modeset || !primary_state->visible))
4692                         intel_pre_disable_primary(&crtc->base);
4693         }
4694
4695         if (pipe_config->disable_cxsr && HAS_GMCH_DISPLAY(dev)) {
4696                 crtc->wm.cxsr_allowed = false;
4697
4698                 /*
4699                  * Vblank time updates from the shadow to live plane control register
4700                  * are blocked if the memory self-refresh mode is active at that
4701                  * moment. So to make sure the plane gets truly disabled, disable
4702                  * first the self-refresh mode. The self-refresh enable bit in turn
4703                  * will be checked/applied by the HW only at the next frame start
4704                  * event which is after the vblank start event, so we need to have a
4705                  * wait-for-vblank between disabling the plane and the pipe.
4706                  */
4707                 if (old_crtc_state->base.active) {
4708                         intel_set_memory_cxsr(dev_priv, false);
4709                         dev_priv->wm.vlv.cxsr = false;
4710                         intel_wait_for_vblank(dev, crtc->pipe);
4711                 }
4712         }
4713
4714         /*
4715          * IVB workaround: must disable low power watermarks for at least
4716          * one frame before enabling scaling.  LP watermarks can be re-enabled
4717          * when scaling is disabled.
4718          *
4719          * WaCxSRDisabledForSpriteScaling:ivb
4720          */
4721         if (pipe_config->disable_lp_wm) {
4722                 ilk_disable_lp_wm(dev);
4723                 intel_wait_for_vblank(dev, crtc->pipe);
4724         }
4725
4726         /*
4727          * If we're doing a modeset, we're done.  No need to do any pre-vblank
4728          * watermark programming here.
4729          */
4730         if (needs_modeset(&pipe_config->base))
4731                 return;
4732
4733         /*
4734          * For platforms that support atomic watermarks, program the
4735          * 'intermediate' watermarks immediately.  On pre-gen9 platforms, these
4736          * will be the intermediate values that are safe for both pre- and
4737          * post- vblank; when vblank happens, the 'active' values will be set
4738          * to the final 'target' values and we'll do this again to get the
4739          * optimal watermarks.  For gen9+ platforms, the values we program here
4740          * will be the final target values which will get automatically latched
4741          * at vblank time; no further programming will be necessary.
4742          *
4743          * If a platform hasn't been transitioned to atomic watermarks yet,
4744          * we'll continue to update watermarks the old way, if flags tell
4745          * us to.
4746          */
4747         if (dev_priv->display.initial_watermarks != NULL)
4748                 dev_priv->display.initial_watermarks(pipe_config);
4749         else if (pipe_config->update_wm_pre)
4750                 intel_update_watermarks(&crtc->base);
4751 }
4752
4753 static void intel_crtc_disable_planes(struct drm_crtc *crtc, unsigned plane_mask)
4754 {
4755         struct drm_device *dev = crtc->dev;
4756         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4757         struct drm_plane *p;
4758         int pipe = intel_crtc->pipe;
4759
4760         intel_crtc_dpms_overlay_disable(intel_crtc);
4761
4762         drm_for_each_plane_mask(p, dev, plane_mask)
4763                 to_intel_plane(p)->disable_plane(p, crtc);
4764
4765         /*
4766          * FIXME: Once we grow proper nuclear flip support out of this we need
4767          * to compute the mask of flip planes precisely. For the time being
4768          * consider this a flip to a NULL plane.
4769          */
4770         intel_frontbuffer_flip(dev, INTEL_FRONTBUFFER_ALL_MASK(pipe));
4771 }
4772
4773 static void ironlake_crtc_enable(struct drm_crtc *crtc)
4774 {
4775         struct drm_device *dev = crtc->dev;
4776         struct drm_i915_private *dev_priv = to_i915(dev);
4777         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4778         struct intel_encoder *encoder;
4779         int pipe = intel_crtc->pipe;
4780         struct intel_crtc_state *pipe_config =
4781                 to_intel_crtc_state(crtc->state);
4782
4783         if (WARN_ON(intel_crtc->active))
4784                 return;
4785
4786         /*
4787          * Sometimes spurious CPU pipe underruns happen during FDI
4788          * training, at least with VGA+HDMI cloning. Suppress them.
4789          *
4790          * On ILK we get an occasional spurious CPU pipe underruns
4791          * between eDP port A enable and vdd enable. Also PCH port
4792          * enable seems to result in the occasional CPU pipe underrun.
4793          *
4794          * Spurious PCH underruns also occur during PCH enabling.
4795          */
4796         if (intel_crtc->config->has_pch_encoder || IS_GEN5(dev_priv))
4797                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, false);
4798         if (intel_crtc->config->has_pch_encoder)
4799                 intel_set_pch_fifo_underrun_reporting(dev_priv, pipe, false);
4800
4801         if (intel_crtc->config->has_pch_encoder)
4802                 intel_prepare_shared_dpll(intel_crtc);
4803
4804         if (intel_crtc_has_dp_encoder(intel_crtc->config))
4805                 intel_dp_set_m_n(intel_crtc, M1_N1);
4806
4807         intel_set_pipe_timings(intel_crtc);
4808         intel_set_pipe_src_size(intel_crtc);
4809
4810         if (intel_crtc->config->has_pch_encoder) {
4811                 intel_cpu_transcoder_set_m_n(intel_crtc,
4812                                      &intel_crtc->config->fdi_m_n, NULL);
4813         }
4814
4815         ironlake_set_pipeconf(crtc);
4816
4817         intel_crtc->active = true;
4818
4819         for_each_encoder_on_crtc(dev, crtc, encoder)
4820                 if (encoder->pre_enable)
4821                         encoder->pre_enable(encoder);
4822
4823         if (intel_crtc->config->has_pch_encoder) {
4824                 /* Note: FDI PLL enabling _must_ be done before we enable the
4825                  * cpu pipes, hence this is separate from all the other fdi/pch
4826                  * enabling. */
4827                 ironlake_fdi_pll_enable(intel_crtc);
4828         } else {
4829                 assert_fdi_tx_disabled(dev_priv, pipe);
4830                 assert_fdi_rx_disabled(dev_priv, pipe);
4831         }
4832
4833         ironlake_pfit_enable(intel_crtc);
4834
4835         /*
4836          * On ILK+ LUT must be loaded before the pipe is running but with
4837          * clocks enabled
4838          */
4839         intel_color_load_luts(&pipe_config->base);
4840
4841         if (dev_priv->display.initial_watermarks != NULL)
4842                 dev_priv->display.initial_watermarks(intel_crtc->config);
4843         intel_enable_pipe(intel_crtc);
4844
4845         if (intel_crtc->config->has_pch_encoder)
4846                 ironlake_pch_enable(crtc);
4847
4848         assert_vblank_disabled(crtc);
4849         drm_crtc_vblank_on(crtc);
4850
4851         for_each_encoder_on_crtc(dev, crtc, encoder)
4852                 encoder->enable(encoder);
4853
4854         if (HAS_PCH_CPT(dev))
4855                 cpt_verify_modeset(dev, intel_crtc->pipe);
4856
4857         /* Must wait for vblank to avoid spurious PCH FIFO underruns */
4858         if (intel_crtc->config->has_pch_encoder)
4859                 intel_wait_for_vblank(dev, pipe);
4860         intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
4861         intel_set_pch_fifo_underrun_reporting(dev_priv, pipe, true);
4862 }
4863
4864 /* IPS only exists on ULT machines and is tied to pipe A. */
4865 static bool hsw_crtc_supports_ips(struct intel_crtc *crtc)
4866 {
4867         return HAS_IPS(crtc->base.dev) && crtc->pipe == PIPE_A;
4868 }
4869
4870 static void haswell_crtc_enable(struct drm_crtc *crtc)
4871 {
4872         struct drm_device *dev = crtc->dev;
4873         struct drm_i915_private *dev_priv = to_i915(dev);
4874         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4875         struct intel_encoder *encoder;
4876         int pipe = intel_crtc->pipe, hsw_workaround_pipe;
4877         enum transcoder cpu_transcoder = intel_crtc->config->cpu_transcoder;
4878         struct intel_crtc_state *pipe_config =
4879                 to_intel_crtc_state(crtc->state);
4880
4881         if (WARN_ON(intel_crtc->active))
4882                 return;
4883
4884         if (intel_crtc->config->has_pch_encoder)
4885                 intel_set_pch_fifo_underrun_reporting(dev_priv, TRANSCODER_A,
4886                                                       false);
4887
4888         for_each_encoder_on_crtc(dev, crtc, encoder)
4889                 if (encoder->pre_pll_enable)
4890                         encoder->pre_pll_enable(encoder);
4891
4892         if (intel_crtc->config->shared_dpll)
4893                 intel_enable_shared_dpll(intel_crtc);
4894
4895         if (intel_crtc_has_dp_encoder(intel_crtc->config))
4896                 intel_dp_set_m_n(intel_crtc, M1_N1);
4897
4898         if (!transcoder_is_dsi(cpu_transcoder))
4899                 intel_set_pipe_timings(intel_crtc);
4900
4901         intel_set_pipe_src_size(intel_crtc);
4902
4903         if (cpu_transcoder != TRANSCODER_EDP &&
4904             !transcoder_is_dsi(cpu_transcoder)) {
4905                 I915_WRITE(PIPE_MULT(cpu_transcoder),
4906                            intel_crtc->config->pixel_multiplier - 1);
4907         }
4908
4909         if (intel_crtc->config->has_pch_encoder) {
4910                 intel_cpu_transcoder_set_m_n(intel_crtc,
4911                                      &intel_crtc->config->fdi_m_n, NULL);
4912         }
4913
4914         if (!transcoder_is_dsi(cpu_transcoder))
4915                 haswell_set_pipeconf(crtc);
4916
4917         haswell_set_pipemisc(crtc);
4918
4919         intel_color_set_csc(&pipe_config->base);
4920
4921         intel_crtc->active = true;
4922
4923         if (intel_crtc->config->has_pch_encoder)
4924                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, false);
4925         else
4926                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
4927
4928         for_each_encoder_on_crtc(dev, crtc, encoder) {
4929                 if (encoder->pre_enable)
4930                         encoder->pre_enable(encoder);
4931         }
4932
4933         if (intel_crtc->config->has_pch_encoder)
4934                 dev_priv->display.fdi_link_train(crtc);
4935
4936         if (!transcoder_is_dsi(cpu_transcoder))
4937                 intel_ddi_enable_pipe_clock(intel_crtc);
4938
4939         if (INTEL_INFO(dev)->gen >= 9)
4940                 skylake_pfit_enable(intel_crtc);
4941         else
4942                 ironlake_pfit_enable(intel_crtc);
4943
4944         /*
4945          * On ILK+ LUT must be loaded before the pipe is running but with
4946          * clocks enabled
4947          */
4948         intel_color_load_luts(&pipe_config->base);
4949
4950         intel_ddi_set_pipe_settings(crtc);
4951         if (!transcoder_is_dsi(cpu_transcoder))
4952                 intel_ddi_enable_transcoder_func(crtc);
4953
4954         if (dev_priv->display.initial_watermarks != NULL)
4955                 dev_priv->display.initial_watermarks(pipe_config);
4956         else
4957                 intel_update_watermarks(crtc);
4958
4959         /* XXX: Do the pipe assertions at the right place for BXT DSI. */
4960         if (!transcoder_is_dsi(cpu_transcoder))
4961                 intel_enable_pipe(intel_crtc);
4962
4963         if (intel_crtc->config->has_pch_encoder)
4964                 lpt_pch_enable(crtc);
4965
4966         if (intel_crtc->config->dp_encoder_is_mst)
4967                 intel_ddi_set_vc_payload_alloc(crtc, true);
4968
4969         assert_vblank_disabled(crtc);
4970         drm_crtc_vblank_on(crtc);
4971
4972         for_each_encoder_on_crtc(dev, crtc, encoder) {
4973                 encoder->enable(encoder);
4974                 intel_opregion_notify_encoder(encoder, true);
4975         }
4976
4977         if (intel_crtc->config->has_pch_encoder) {
4978                 intel_wait_for_vblank(dev, pipe);
4979                 intel_wait_for_vblank(dev, pipe);
4980                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
4981                 intel_set_pch_fifo_underrun_reporting(dev_priv, TRANSCODER_A,
4982                                                       true);
4983         }
4984
4985         /* If we change the relative order between pipe/planes enabling, we need
4986          * to change the workaround. */
4987         hsw_workaround_pipe = pipe_config->hsw_workaround_pipe;
4988         if (IS_HASWELL(dev) && hsw_workaround_pipe != INVALID_PIPE) {
4989                 intel_wait_for_vblank(dev, hsw_workaround_pipe);
4990                 intel_wait_for_vblank(dev, hsw_workaround_pipe);
4991         }
4992 }
4993
4994 static void ironlake_pfit_disable(struct intel_crtc *crtc, bool force)
4995 {
4996         struct drm_device *dev = crtc->base.dev;
4997         struct drm_i915_private *dev_priv = to_i915(dev);
4998         int pipe = crtc->pipe;
4999
5000         /* To avoid upsetting the power well on haswell only disable the pfit if
5001          * it's in use. The hw state code will make sure we get this right. */
5002         if (force || crtc->config->pch_pfit.enabled) {
5003                 I915_WRITE(PF_CTL(pipe), 0);
5004                 I915_WRITE(PF_WIN_POS(pipe), 0);
5005                 I915_WRITE(PF_WIN_SZ(pipe), 0);
5006         }
5007 }
5008
5009 static void ironlake_crtc_disable(struct drm_crtc *crtc)
5010 {
5011         struct drm_device *dev = crtc->dev;
5012         struct drm_i915_private *dev_priv = to_i915(dev);
5013         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5014         struct intel_encoder *encoder;
5015         int pipe = intel_crtc->pipe;
5016
5017         /*
5018          * Sometimes spurious CPU pipe underruns happen when the
5019          * pipe is already disabled, but FDI RX/TX is still enabled.
5020          * Happens at least with VGA+HDMI cloning. Suppress them.
5021          */
5022         if (intel_crtc->config->has_pch_encoder) {
5023                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, false);
5024                 intel_set_pch_fifo_underrun_reporting(dev_priv, pipe, false);
5025         }
5026
5027         for_each_encoder_on_crtc(dev, crtc, encoder)
5028                 encoder->disable(encoder);
5029
5030         drm_crtc_vblank_off(crtc);
5031         assert_vblank_disabled(crtc);
5032
5033         intel_disable_pipe(intel_crtc);
5034
5035         ironlake_pfit_disable(intel_crtc, false);
5036
5037         if (intel_crtc->config->has_pch_encoder)
5038                 ironlake_fdi_disable(crtc);
5039
5040         for_each_encoder_on_crtc(dev, crtc, encoder)
5041                 if (encoder->post_disable)
5042                         encoder->post_disable(encoder);
5043
5044         if (intel_crtc->config->has_pch_encoder) {
5045                 ironlake_disable_pch_transcoder(dev_priv, pipe);
5046
5047                 if (HAS_PCH_CPT(dev)) {
5048                         i915_reg_t reg;
5049                         u32 temp;
5050
5051                         /* disable TRANS_DP_CTL */
5052                         reg = TRANS_DP_CTL(pipe);
5053                         temp = I915_READ(reg);
5054                         temp &= ~(TRANS_DP_OUTPUT_ENABLE |
5055                                   TRANS_DP_PORT_SEL_MASK);
5056                         temp |= TRANS_DP_PORT_SEL_NONE;
5057                         I915_WRITE(reg, temp);
5058
5059                         /* disable DPLL_SEL */
5060                         temp = I915_READ(PCH_DPLL_SEL);
5061                         temp &= ~(TRANS_DPLL_ENABLE(pipe) | TRANS_DPLLB_SEL(pipe));
5062                         I915_WRITE(PCH_DPLL_SEL, temp);
5063                 }
5064
5065                 ironlake_fdi_pll_disable(intel_crtc);
5066         }
5067
5068         intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
5069         intel_set_pch_fifo_underrun_reporting(dev_priv, pipe, true);
5070 }
5071
5072 static void haswell_crtc_disable(struct drm_crtc *crtc)
5073 {
5074         struct drm_device *dev = crtc->dev;
5075         struct drm_i915_private *dev_priv = to_i915(dev);
5076         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5077         struct intel_encoder *encoder;
5078         enum transcoder cpu_transcoder = intel_crtc->config->cpu_transcoder;
5079
5080         if (intel_crtc->config->has_pch_encoder)
5081                 intel_set_pch_fifo_underrun_reporting(dev_priv, TRANSCODER_A,
5082                                                       false);
5083
5084         for_each_encoder_on_crtc(dev, crtc, encoder) {
5085                 intel_opregion_notify_encoder(encoder, false);
5086                 encoder->disable(encoder);
5087         }
5088
5089         drm_crtc_vblank_off(crtc);
5090         assert_vblank_disabled(crtc);
5091
5092         /* XXX: Do the pipe assertions at the right place for BXT DSI. */
5093         if (!transcoder_is_dsi(cpu_transcoder))
5094                 intel_disable_pipe(intel_crtc);
5095
5096         if (intel_crtc->config->dp_encoder_is_mst)
5097                 intel_ddi_set_vc_payload_alloc(crtc, false);
5098
5099         if (!transcoder_is_dsi(cpu_transcoder))
5100                 intel_ddi_disable_transcoder_func(dev_priv, cpu_transcoder);
5101
5102         if (INTEL_INFO(dev)->gen >= 9)
5103                 skylake_scaler_disable(intel_crtc);
5104         else
5105                 ironlake_pfit_disable(intel_crtc, false);
5106
5107         if (!transcoder_is_dsi(cpu_transcoder))
5108                 intel_ddi_disable_pipe_clock(intel_crtc);
5109
5110         for_each_encoder_on_crtc(dev, crtc, encoder)
5111                 if (encoder->post_disable)
5112                         encoder->post_disable(encoder);
5113
5114         if (intel_crtc->config->has_pch_encoder) {
5115                 lpt_disable_pch_transcoder(dev_priv);
5116                 lpt_disable_iclkip(dev_priv);
5117                 intel_ddi_fdi_disable(crtc);
5118
5119                 intel_set_pch_fifo_underrun_reporting(dev_priv, TRANSCODER_A,
5120                                                       true);
5121         }
5122 }
5123
5124 static void i9xx_pfit_enable(struct intel_crtc *crtc)
5125 {
5126         struct drm_device *dev = crtc->base.dev;
5127         struct drm_i915_private *dev_priv = to_i915(dev);
5128         struct intel_crtc_state *pipe_config = crtc->config;
5129
5130         if (!pipe_config->gmch_pfit.control)
5131                 return;
5132
5133         /*
5134          * The panel fitter should only be adjusted whilst the pipe is disabled,
5135          * according to register description and PRM.
5136          */
5137         WARN_ON(I915_READ(PFIT_CONTROL) & PFIT_ENABLE);
5138         assert_pipe_disabled(dev_priv, crtc->pipe);
5139
5140         I915_WRITE(PFIT_PGM_RATIOS, pipe_config->gmch_pfit.pgm_ratios);
5141         I915_WRITE(PFIT_CONTROL, pipe_config->gmch_pfit.control);
5142
5143         /* Border color in case we don't scale up to the full screen. Black by
5144          * default, change to something else for debugging. */
5145         I915_WRITE(BCLRPAT(crtc->pipe), 0);
5146 }
5147
5148 static enum intel_display_power_domain port_to_power_domain(enum port port)
5149 {
5150         switch (port) {
5151         case PORT_A:
5152                 return POWER_DOMAIN_PORT_DDI_A_LANES;
5153         case PORT_B:
5154                 return POWER_DOMAIN_PORT_DDI_B_LANES;
5155         case PORT_C:
5156                 return POWER_DOMAIN_PORT_DDI_C_LANES;
5157         case PORT_D:
5158                 return POWER_DOMAIN_PORT_DDI_D_LANES;
5159         case PORT_E:
5160                 return POWER_DOMAIN_PORT_DDI_E_LANES;
5161         default:
5162                 MISSING_CASE(port);
5163                 return POWER_DOMAIN_PORT_OTHER;
5164         }
5165 }
5166
5167 static enum intel_display_power_domain port_to_aux_power_domain(enum port port)
5168 {
5169         switch (port) {
5170         case PORT_A:
5171                 return POWER_DOMAIN_AUX_A;
5172         case PORT_B:
5173                 return POWER_DOMAIN_AUX_B;
5174         case PORT_C:
5175                 return POWER_DOMAIN_AUX_C;
5176         case PORT_D:
5177                 return POWER_DOMAIN_AUX_D;
5178         case PORT_E:
5179                 /* FIXME: Check VBT for actual wiring of PORT E */
5180                 return POWER_DOMAIN_AUX_D;
5181         default:
5182                 MISSING_CASE(port);
5183                 return POWER_DOMAIN_AUX_A;
5184         }
5185 }
5186
5187 enum intel_display_power_domain
5188 intel_display_port_power_domain(struct intel_encoder *intel_encoder)
5189 {
5190         struct drm_device *dev = intel_encoder->base.dev;
5191         struct intel_digital_port *intel_dig_port;
5192
5193         switch (intel_encoder->type) {
5194         case INTEL_OUTPUT_UNKNOWN:
5195                 /* Only DDI platforms should ever use this output type */
5196                 WARN_ON_ONCE(!HAS_DDI(dev));
5197         case INTEL_OUTPUT_DP:
5198         case INTEL_OUTPUT_HDMI:
5199         case INTEL_OUTPUT_EDP:
5200                 intel_dig_port = enc_to_dig_port(&intel_encoder->base);
5201                 return port_to_power_domain(intel_dig_port->port);
5202         case INTEL_OUTPUT_DP_MST:
5203                 intel_dig_port = enc_to_mst(&intel_encoder->base)->primary;
5204                 return port_to_power_domain(intel_dig_port->port);
5205         case INTEL_OUTPUT_ANALOG:
5206                 return POWER_DOMAIN_PORT_CRT;
5207         case INTEL_OUTPUT_DSI:
5208                 return POWER_DOMAIN_PORT_DSI;
5209         default:
5210                 return POWER_DOMAIN_PORT_OTHER;
5211         }
5212 }
5213
5214 enum intel_display_power_domain
5215 intel_display_port_aux_power_domain(struct intel_encoder *intel_encoder)
5216 {
5217         struct drm_device *dev = intel_encoder->base.dev;
5218         struct intel_digital_port *intel_dig_port;
5219
5220         switch (intel_encoder->type) {
5221         case INTEL_OUTPUT_UNKNOWN:
5222         case INTEL_OUTPUT_HDMI:
5223                 /*
5224                  * Only DDI platforms should ever use these output types.
5225                  * We can get here after the HDMI detect code has already set
5226                  * the type of the shared encoder. Since we can't be sure
5227                  * what's the status of the given connectors, play safe and
5228                  * run the DP detection too.
5229                  */
5230                 WARN_ON_ONCE(!HAS_DDI(dev));
5231         case INTEL_OUTPUT_DP:
5232         case INTEL_OUTPUT_EDP:
5233                 intel_dig_port = enc_to_dig_port(&intel_encoder->base);
5234                 return port_to_aux_power_domain(intel_dig_port->port);
5235         case INTEL_OUTPUT_DP_MST:
5236                 intel_dig_port = enc_to_mst(&intel_encoder->base)->primary;
5237                 return port_to_aux_power_domain(intel_dig_port->port);
5238         default:
5239                 MISSING_CASE(intel_encoder->type);
5240                 return POWER_DOMAIN_AUX_A;
5241         }
5242 }
5243
5244 static unsigned long get_crtc_power_domains(struct drm_crtc *crtc,
5245                                             struct intel_crtc_state *crtc_state)
5246 {
5247         struct drm_device *dev = crtc->dev;
5248         struct drm_encoder *encoder;
5249         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5250         enum pipe pipe = intel_crtc->pipe;
5251         unsigned long mask;
5252         enum transcoder transcoder = crtc_state->cpu_transcoder;
5253
5254         if (!crtc_state->base.active)
5255                 return 0;
5256
5257         mask = BIT(POWER_DOMAIN_PIPE(pipe));
5258         mask |= BIT(POWER_DOMAIN_TRANSCODER(transcoder));
5259         if (crtc_state->pch_pfit.enabled ||
5260             crtc_state->pch_pfit.force_thru)
5261                 mask |= BIT(POWER_DOMAIN_PIPE_PANEL_FITTER(pipe));
5262
5263         drm_for_each_encoder_mask(encoder, dev, crtc_state->base.encoder_mask) {
5264                 struct intel_encoder *intel_encoder = to_intel_encoder(encoder);
5265
5266                 mask |= BIT(intel_display_port_power_domain(intel_encoder));
5267         }
5268
5269         if (crtc_state->shared_dpll)
5270                 mask |= BIT(POWER_DOMAIN_PLLS);
5271
5272         return mask;
5273 }
5274
5275 static unsigned long
5276 modeset_get_crtc_power_domains(struct drm_crtc *crtc,
5277                                struct intel_crtc_state *crtc_state)
5278 {
5279         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
5280         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5281         enum intel_display_power_domain domain;
5282         unsigned long domains, new_domains, old_domains;
5283
5284         old_domains = intel_crtc->enabled_power_domains;
5285         intel_crtc->enabled_power_domains = new_domains =
5286                 get_crtc_power_domains(crtc, crtc_state);
5287
5288         domains = new_domains & ~old_domains;
5289
5290         for_each_power_domain(domain, domains)
5291                 intel_display_power_get(dev_priv, domain);
5292
5293         return old_domains & ~new_domains;
5294 }
5295
5296 static void modeset_put_power_domains(struct drm_i915_private *dev_priv,
5297                                       unsigned long domains)
5298 {
5299         enum intel_display_power_domain domain;
5300
5301         for_each_power_domain(domain, domains)
5302                 intel_display_power_put(dev_priv, domain);
5303 }
5304
5305 static int intel_compute_max_dotclk(struct drm_i915_private *dev_priv)
5306 {
5307         int max_cdclk_freq = dev_priv->max_cdclk_freq;
5308
5309         if (INTEL_INFO(dev_priv)->gen >= 9 ||
5310             IS_HASWELL(dev_priv) || IS_BROADWELL(dev_priv))
5311                 return max_cdclk_freq;
5312         else if (IS_CHERRYVIEW(dev_priv))
5313                 return max_cdclk_freq*95/100;
5314         else if (INTEL_INFO(dev_priv)->gen < 4)
5315                 return 2*max_cdclk_freq*90/100;
5316         else
5317                 return max_cdclk_freq*90/100;
5318 }
5319
5320 static int skl_calc_cdclk(int max_pixclk, int vco);
5321
5322 static void intel_update_max_cdclk(struct drm_device *dev)
5323 {
5324         struct drm_i915_private *dev_priv = to_i915(dev);
5325
5326         if (IS_SKYLAKE(dev) || IS_KABYLAKE(dev)) {
5327                 u32 limit = I915_READ(SKL_DFSM) & SKL_DFSM_CDCLK_LIMIT_MASK;
5328                 int max_cdclk, vco;
5329
5330                 vco = dev_priv->skl_preferred_vco_freq;
5331                 WARN_ON(vco != 8100000 && vco != 8640000);
5332
5333                 /*
5334                  * Use the lower (vco 8640) cdclk values as a
5335                  * first guess. skl_calc_cdclk() will correct it
5336                  * if the preferred vco is 8100 instead.
5337                  */
5338                 if (limit == SKL_DFSM_CDCLK_LIMIT_675)
5339                         max_cdclk = 617143;
5340                 else if (limit == SKL_DFSM_CDCLK_LIMIT_540)
5341                         max_cdclk = 540000;
5342                 else if (limit == SKL_DFSM_CDCLK_LIMIT_450)
5343                         max_cdclk = 432000;
5344                 else
5345                         max_cdclk = 308571;
5346
5347                 dev_priv->max_cdclk_freq = skl_calc_cdclk(max_cdclk, vco);
5348         } else if (IS_BROXTON(dev)) {
5349                 dev_priv->max_cdclk_freq = 624000;
5350         } else if (IS_BROADWELL(dev))  {
5351                 /*
5352                  * FIXME with extra cooling we can allow
5353                  * 540 MHz for ULX and 675 Mhz for ULT.
5354                  * How can we know if extra cooling is
5355                  * available? PCI ID, VTB, something else?
5356                  */
5357                 if (I915_READ(FUSE_STRAP) & HSW_CDCLK_LIMIT)
5358                         dev_priv->max_cdclk_freq = 450000;
5359                 else if (IS_BDW_ULX(dev))
5360                         dev_priv->max_cdclk_freq = 450000;
5361                 else if (IS_BDW_ULT(dev))
5362                         dev_priv->max_cdclk_freq = 540000;
5363                 else
5364                         dev_priv->max_cdclk_freq = 675000;
5365         } else if (IS_CHERRYVIEW(dev)) {
5366                 dev_priv->max_cdclk_freq = 320000;
5367         } else if (IS_VALLEYVIEW(dev)) {
5368                 dev_priv->max_cdclk_freq = 400000;
5369         } else {
5370                 /* otherwise assume cdclk is fixed */
5371                 dev_priv->max_cdclk_freq = dev_priv->cdclk_freq;
5372         }
5373
5374         dev_priv->max_dotclk_freq = intel_compute_max_dotclk(dev_priv);
5375
5376         DRM_DEBUG_DRIVER("Max CD clock rate: %d kHz\n",
5377                          dev_priv->max_cdclk_freq);
5378
5379         DRM_DEBUG_DRIVER("Max dotclock rate: %d kHz\n",
5380                          dev_priv->max_dotclk_freq);
5381 }
5382
5383 static void intel_update_cdclk(struct drm_device *dev)
5384 {
5385         struct drm_i915_private *dev_priv = to_i915(dev);
5386
5387         dev_priv->cdclk_freq = dev_priv->display.get_display_clock_speed(dev);
5388
5389         if (INTEL_GEN(dev_priv) >= 9)
5390                 DRM_DEBUG_DRIVER("Current CD clock rate: %d kHz, VCO: %d kHz, ref: %d kHz\n",
5391                                  dev_priv->cdclk_freq, dev_priv->cdclk_pll.vco,
5392                                  dev_priv->cdclk_pll.ref);
5393         else
5394                 DRM_DEBUG_DRIVER("Current CD clock rate: %d kHz\n",
5395                                  dev_priv->cdclk_freq);
5396
5397         /*
5398          * 9:0 CMBUS [sic] CDCLK frequency (cdfreq):
5399          * Programmng [sic] note: bit[9:2] should be programmed to the number
5400          * of cdclk that generates 4MHz reference clock freq which is used to
5401          * generate GMBus clock. This will vary with the cdclk freq.
5402          */
5403         if (IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv))
5404                 I915_WRITE(GMBUSFREQ_VLV, DIV_ROUND_UP(dev_priv->cdclk_freq, 1000));
5405 }
5406
5407 /* convert from kHz to .1 fixpoint MHz with -1MHz offset */
5408 static int skl_cdclk_decimal(int cdclk)
5409 {
5410         return DIV_ROUND_CLOSEST(cdclk - 1000, 500);
5411 }
5412
5413 static int bxt_de_pll_vco(struct drm_i915_private *dev_priv, int cdclk)
5414 {
5415         int ratio;
5416
5417         if (cdclk == dev_priv->cdclk_pll.ref)
5418                 return 0;
5419
5420         switch (cdclk) {
5421         default:
5422                 MISSING_CASE(cdclk);
5423         case 144000:
5424         case 288000:
5425         case 384000:
5426         case 576000:
5427                 ratio = 60;
5428                 break;
5429         case 624000:
5430                 ratio = 65;
5431                 break;
5432         }
5433
5434         return dev_priv->cdclk_pll.ref * ratio;
5435 }
5436
5437 static void bxt_de_pll_disable(struct drm_i915_private *dev_priv)
5438 {
5439         I915_WRITE(BXT_DE_PLL_ENABLE, 0);
5440
5441         /* Timeout 200us */
5442         if (intel_wait_for_register(dev_priv,
5443                                     BXT_DE_PLL_ENABLE, BXT_DE_PLL_LOCK, 0,
5444                                     1))
5445                 DRM_ERROR("timeout waiting for DE PLL unlock\n");
5446
5447         dev_priv->cdclk_pll.vco = 0;
5448 }
5449
5450 static void bxt_de_pll_enable(struct drm_i915_private *dev_priv, int vco)
5451 {
5452         int ratio = DIV_ROUND_CLOSEST(vco, dev_priv->cdclk_pll.ref);
5453         u32 val;
5454
5455         val = I915_READ(BXT_DE_PLL_CTL);
5456         val &= ~BXT_DE_PLL_RATIO_MASK;
5457         val |= BXT_DE_PLL_RATIO(ratio);
5458         I915_WRITE(BXT_DE_PLL_CTL, val);
5459
5460         I915_WRITE(BXT_DE_PLL_ENABLE, BXT_DE_PLL_PLL_ENABLE);
5461
5462         /* Timeout 200us */
5463         if (intel_wait_for_register(dev_priv,
5464                                     BXT_DE_PLL_ENABLE,
5465                                     BXT_DE_PLL_LOCK,
5466                                     BXT_DE_PLL_LOCK,
5467                                     1))
5468                 DRM_ERROR("timeout waiting for DE PLL lock\n");
5469
5470         dev_priv->cdclk_pll.vco = vco;
5471 }
5472
5473 static void bxt_set_cdclk(struct drm_i915_private *dev_priv, int cdclk)
5474 {
5475         u32 val, divider;
5476         int vco, ret;
5477
5478         vco = bxt_de_pll_vco(dev_priv, cdclk);
5479
5480         DRM_DEBUG_DRIVER("Changing CDCLK to %d kHz (VCO %d kHz)\n", cdclk, vco);
5481
5482         /* cdclk = vco / 2 / div{1,1.5,2,4} */
5483         switch (DIV_ROUND_CLOSEST(vco, cdclk)) {
5484         case 8:
5485                 divider = BXT_CDCLK_CD2X_DIV_SEL_4;
5486                 break;
5487         case 4:
5488                 divider = BXT_CDCLK_CD2X_DIV_SEL_2;
5489                 break;
5490         case 3:
5491                 divider = BXT_CDCLK_CD2X_DIV_SEL_1_5;
5492                 break;
5493         case 2:
5494                 divider = BXT_CDCLK_CD2X_DIV_SEL_1;
5495                 break;
5496         default:
5497                 WARN_ON(cdclk != dev_priv->cdclk_pll.ref);
5498                 WARN_ON(vco != 0);
5499
5500                 divider = BXT_CDCLK_CD2X_DIV_SEL_1;
5501                 break;
5502         }
5503
5504         /* Inform power controller of upcoming frequency change */
5505         mutex_lock(&dev_priv->rps.hw_lock);
5506         ret = sandybridge_pcode_write(dev_priv, HSW_PCODE_DE_WRITE_FREQ_REQ,
5507                                       0x80000000);
5508         mutex_unlock(&dev_priv->rps.hw_lock);
5509
5510         if (ret) {
5511                 DRM_ERROR("PCode CDCLK freq change notify failed (err %d, freq %d)\n",
5512                           ret, cdclk);
5513                 return;
5514         }
5515
5516         if (dev_priv->cdclk_pll.vco != 0 &&
5517             dev_priv->cdclk_pll.vco != vco)
5518                 bxt_de_pll_disable(dev_priv);
5519
5520         if (dev_priv->cdclk_pll.vco != vco)
5521                 bxt_de_pll_enable(dev_priv, vco);
5522
5523         val = divider | skl_cdclk_decimal(cdclk);
5524         /*
5525          * FIXME if only the cd2x divider needs changing, it could be done
5526          * without shutting off the pipe (if only one pipe is active).
5527          */
5528         val |= BXT_CDCLK_CD2X_PIPE_NONE;
5529         /*
5530          * Disable SSA Precharge when CD clock frequency < 500 MHz,
5531          * enable otherwise.
5532          */
5533         if (cdclk >= 500000)
5534                 val |= BXT_CDCLK_SSA_PRECHARGE_ENABLE;
5535         I915_WRITE(CDCLK_CTL, val);
5536
5537         mutex_lock(&dev_priv->rps.hw_lock);
5538         ret = sandybridge_pcode_write(dev_priv, HSW_PCODE_DE_WRITE_FREQ_REQ,
5539                                       DIV_ROUND_UP(cdclk, 25000));
5540         mutex_unlock(&dev_priv->rps.hw_lock);
5541
5542         if (ret) {
5543                 DRM_ERROR("PCode CDCLK freq set failed, (err %d, freq %d)\n",
5544                           ret, cdclk);
5545                 return;
5546         }
5547
5548         intel_update_cdclk(&dev_priv->drm);
5549 }
5550
5551 static void bxt_sanitize_cdclk(struct drm_i915_private *dev_priv)
5552 {
5553         u32 cdctl, expected;
5554
5555         intel_update_cdclk(&dev_priv->drm);
5556
5557         if (dev_priv->cdclk_pll.vco == 0 ||
5558             dev_priv->cdclk_freq == dev_priv->cdclk_pll.ref)
5559                 goto sanitize;
5560
5561         /* DPLL okay; verify the cdclock
5562          *
5563          * Some BIOS versions leave an incorrect decimal frequency value and
5564          * set reserved MBZ bits in CDCLK_CTL at least during exiting from S4,
5565          * so sanitize this register.
5566          */
5567         cdctl = I915_READ(CDCLK_CTL);
5568         /*
5569          * Let's ignore the pipe field, since BIOS could have configured the
5570          * dividers both synching to an active pipe, or asynchronously
5571          * (PIPE_NONE).
5572          */
5573         cdctl &= ~BXT_CDCLK_CD2X_PIPE_NONE;
5574
5575         expected = (cdctl & BXT_CDCLK_CD2X_DIV_SEL_MASK) |
5576                    skl_cdclk_decimal(dev_priv->cdclk_freq);
5577         /*
5578          * Disable SSA Precharge when CD clock frequency < 500 MHz,
5579          * enable otherwise.
5580          */
5581         if (dev_priv->cdclk_freq >= 500000)
5582                 expected |= BXT_CDCLK_SSA_PRECHARGE_ENABLE;
5583
5584         if (cdctl == expected)
5585                 /* All well; nothing to sanitize */
5586                 return;
5587
5588 sanitize:
5589         DRM_DEBUG_KMS("Sanitizing cdclk programmed by pre-os\n");
5590
5591         /* force cdclk programming */
5592         dev_priv->cdclk_freq = 0;
5593
5594         /* force full PLL disable + enable */
5595         dev_priv->cdclk_pll.vco = -1;
5596 }
5597
5598 void bxt_init_cdclk(struct drm_i915_private *dev_priv)
5599 {
5600         bxt_sanitize_cdclk(dev_priv);
5601
5602         if (dev_priv->cdclk_freq != 0 && dev_priv->cdclk_pll.vco != 0)
5603                 return;
5604
5605         /*
5606          * FIXME:
5607          * - The initial CDCLK needs to be read from VBT.
5608          *   Need to make this change after VBT has changes for BXT.
5609          */
5610         bxt_set_cdclk(dev_priv, bxt_calc_cdclk(0));
5611 }
5612
5613 void bxt_uninit_cdclk(struct drm_i915_private *dev_priv)
5614 {
5615         bxt_set_cdclk(dev_priv, dev_priv->cdclk_pll.ref);
5616 }
5617
5618 static int skl_calc_cdclk(int max_pixclk, int vco)
5619 {
5620         if (vco == 8640000) {
5621                 if (max_pixclk > 540000)
5622                         return 617143;
5623                 else if (max_pixclk > 432000)
5624                         return 540000;
5625                 else if (max_pixclk > 308571)
5626                         return 432000;
5627                 else
5628                         return 308571;
5629         } else {
5630                 if (max_pixclk > 540000)
5631                         return 675000;
5632                 else if (max_pixclk > 450000)
5633                         return 540000;
5634                 else if (max_pixclk > 337500)
5635                         return 450000;
5636                 else
5637                         return 337500;
5638         }
5639 }
5640
5641 static void
5642 skl_dpll0_update(struct drm_i915_private *dev_priv)
5643 {
5644         u32 val;
5645
5646         dev_priv->cdclk_pll.ref = 24000;
5647         dev_priv->cdclk_pll.vco = 0;
5648
5649         val = I915_READ(LCPLL1_CTL);
5650         if ((val & LCPLL_PLL_ENABLE) == 0)
5651                 return;
5652
5653         if (WARN_ON((val & LCPLL_PLL_LOCK) == 0))
5654                 return;
5655
5656         val = I915_READ(DPLL_CTRL1);
5657
5658         if (WARN_ON((val & (DPLL_CTRL1_HDMI_MODE(SKL_DPLL0) |
5659                             DPLL_CTRL1_SSC(SKL_DPLL0) |
5660                             DPLL_CTRL1_OVERRIDE(SKL_DPLL0))) !=
5661                     DPLL_CTRL1_OVERRIDE(SKL_DPLL0)))
5662                 return;
5663
5664         switch (val & DPLL_CTRL1_LINK_RATE_MASK(SKL_DPLL0)) {
5665         case DPLL_CTRL1_LINK_RATE(DPLL_CTRL1_LINK_RATE_810, SKL_DPLL0):
5666         case DPLL_CTRL1_LINK_RATE(DPLL_CTRL1_LINK_RATE_1350, SKL_DPLL0):
5667         case DPLL_CTRL1_LINK_RATE(DPLL_CTRL1_LINK_RATE_1620, SKL_DPLL0):
5668         case DPLL_CTRL1_LINK_RATE(DPLL_CTRL1_LINK_RATE_2700, SKL_DPLL0):
5669                 dev_priv->cdclk_pll.vco = 8100000;
5670                 break;
5671         case DPLL_CTRL1_LINK_RATE(DPLL_CTRL1_LINK_RATE_1080, SKL_DPLL0):
5672         case DPLL_CTRL1_LINK_RATE(DPLL_CTRL1_LINK_RATE_2160, SKL_DPLL0):
5673                 dev_priv->cdclk_pll.vco = 8640000;
5674                 break;
5675         default:
5676                 MISSING_CASE(val & DPLL_CTRL1_LINK_RATE_MASK(SKL_DPLL0));
5677                 break;
5678         }
5679 }
5680
5681 void skl_set_preferred_cdclk_vco(struct drm_i915_private *dev_priv, int vco)
5682 {
5683         bool changed = dev_priv->skl_preferred_vco_freq != vco;
5684
5685         dev_priv->skl_preferred_vco_freq = vco;
5686
5687         if (changed)
5688                 intel_update_max_cdclk(&dev_priv->drm);
5689 }
5690
5691 static void
5692 skl_dpll0_enable(struct drm_i915_private *dev_priv, int vco)
5693 {
5694         int min_cdclk = skl_calc_cdclk(0, vco);
5695         u32 val;
5696
5697         WARN_ON(vco != 8100000 && vco != 8640000);
5698
5699         /* select the minimum CDCLK before enabling DPLL 0 */
5700         val = CDCLK_FREQ_337_308 | skl_cdclk_decimal(min_cdclk);
5701         I915_WRITE(CDCLK_CTL, val);
5702         POSTING_READ(CDCLK_CTL);
5703
5704         /*
5705          * We always enable DPLL0 with the lowest link rate possible, but still
5706          * taking into account the VCO required to operate the eDP panel at the
5707          * desired frequency. The usual DP link rates operate with a VCO of
5708          * 8100 while the eDP 1.4 alternate link rates need a VCO of 8640.
5709          * The modeset code is responsible for the selection of the exact link
5710          * rate later on, with the constraint of choosing a frequency that
5711          * works with vco.
5712          */
5713         val = I915_READ(DPLL_CTRL1);
5714
5715         val &= ~(DPLL_CTRL1_HDMI_MODE(SKL_DPLL0) | DPLL_CTRL1_SSC(SKL_DPLL0) |
5716                  DPLL_CTRL1_LINK_RATE_MASK(SKL_DPLL0));
5717         val |= DPLL_CTRL1_OVERRIDE(SKL_DPLL0);
5718         if (vco == 8640000)
5719                 val |= DPLL_CTRL1_LINK_RATE(DPLL_CTRL1_LINK_RATE_1080,
5720                                             SKL_DPLL0);
5721         else
5722                 val |= DPLL_CTRL1_LINK_RATE(DPLL_CTRL1_LINK_RATE_810,
5723                                             SKL_DPLL0);
5724
5725         I915_WRITE(DPLL_CTRL1, val);
5726         POSTING_READ(DPLL_CTRL1);
5727
5728         I915_WRITE(LCPLL1_CTL, I915_READ(LCPLL1_CTL) | LCPLL_PLL_ENABLE);
5729
5730         if (intel_wait_for_register(dev_priv,
5731                                     LCPLL1_CTL, LCPLL_PLL_LOCK, LCPLL_PLL_LOCK,
5732                                     5))
5733                 DRM_ERROR("DPLL0 not locked\n");
5734
5735         dev_priv->cdclk_pll.vco = vco;
5736
5737         /* We'll want to keep using the current vco from now on. */
5738         skl_set_preferred_cdclk_vco(dev_priv, vco);
5739 }
5740
5741 static void
5742 skl_dpll0_disable(struct drm_i915_private *dev_priv)
5743 {
5744         I915_WRITE(LCPLL1_CTL, I915_READ(LCPLL1_CTL) & ~LCPLL_PLL_ENABLE);
5745         if (intel_wait_for_register(dev_priv,
5746                                    LCPLL1_CTL, LCPLL_PLL_LOCK, 0,
5747                                    1))
5748                 DRM_ERROR("Couldn't disable DPLL0\n");
5749
5750         dev_priv->cdclk_pll.vco = 0;
5751 }
5752
5753 static bool skl_cdclk_pcu_ready(struct drm_i915_private *dev_priv)
5754 {
5755         int ret;
5756         u32 val;
5757
5758         /* inform PCU we want to change CDCLK */
5759         val = SKL_CDCLK_PREPARE_FOR_CHANGE;
5760         mutex_lock(&dev_priv->rps.hw_lock);
5761         ret = sandybridge_pcode_read(dev_priv, SKL_PCODE_CDCLK_CONTROL, &val);
5762         mutex_unlock(&dev_priv->rps.hw_lock);
5763
5764         return ret == 0 && (val & SKL_CDCLK_READY_FOR_CHANGE);
5765 }
5766
5767 static bool skl_cdclk_wait_for_pcu_ready(struct drm_i915_private *dev_priv)
5768 {
5769         return _wait_for(skl_cdclk_pcu_ready(dev_priv), 3000, 10) == 0;
5770 }
5771
5772 static void skl_set_cdclk(struct drm_i915_private *dev_priv, int cdclk, int vco)
5773 {
5774         struct drm_device *dev = &dev_priv->drm;
5775         u32 freq_select, pcu_ack;
5776
5777         WARN_ON((cdclk == 24000) != (vco == 0));
5778
5779         DRM_DEBUG_DRIVER("Changing CDCLK to %d kHz (VCO %d kHz)\n", cdclk, vco);
5780
5781         if (!skl_cdclk_wait_for_pcu_ready(dev_priv)) {
5782                 DRM_ERROR("failed to inform PCU about cdclk change\n");
5783                 return;
5784         }
5785
5786         /* set CDCLK_CTL */
5787         switch (cdclk) {
5788         case 450000:
5789         case 432000:
5790                 freq_select = CDCLK_FREQ_450_432;
5791                 pcu_ack = 1;
5792                 break;
5793         case 540000:
5794                 freq_select = CDCLK_FREQ_540;
5795                 pcu_ack = 2;
5796                 break;
5797         case 308571:
5798         case 337500:
5799         default:
5800                 freq_select = CDCLK_FREQ_337_308;
5801                 pcu_ack = 0;
5802                 break;
5803         case 617143:
5804         case 675000:
5805                 freq_select = CDCLK_FREQ_675_617;
5806                 pcu_ack = 3;
5807                 break;
5808         }
5809
5810         if (dev_priv->cdclk_pll.vco != 0 &&
5811             dev_priv->cdclk_pll.vco != vco)
5812                 skl_dpll0_disable(dev_priv);
5813
5814         if (dev_priv->cdclk_pll.vco != vco)
5815                 skl_dpll0_enable(dev_priv, vco);
5816
5817         I915_WRITE(CDCLK_CTL, freq_select | skl_cdclk_decimal(cdclk));
5818         POSTING_READ(CDCLK_CTL);
5819
5820         /* inform PCU of the change */
5821         mutex_lock(&dev_priv->rps.hw_lock);
5822         sandybridge_pcode_write(dev_priv, SKL_PCODE_CDCLK_CONTROL, pcu_ack);
5823         mutex_unlock(&dev_priv->rps.hw_lock);
5824
5825         intel_update_cdclk(dev);
5826 }
5827
5828 static void skl_sanitize_cdclk(struct drm_i915_private *dev_priv);
5829
5830 void skl_uninit_cdclk(struct drm_i915_private *dev_priv)
5831 {
5832         skl_set_cdclk(dev_priv, dev_priv->cdclk_pll.ref, 0);
5833 }
5834
5835 void skl_init_cdclk(struct drm_i915_private *dev_priv)
5836 {
5837         int cdclk, vco;
5838
5839         skl_sanitize_cdclk(dev_priv);
5840
5841         if (dev_priv->cdclk_freq != 0 && dev_priv->cdclk_pll.vco != 0) {
5842                 /*
5843                  * Use the current vco as our initial
5844                  * guess as to what the preferred vco is.
5845                  */
5846                 if (dev_priv->skl_preferred_vco_freq == 0)
5847                         skl_set_preferred_cdclk_vco(dev_priv,
5848                                                     dev_priv->cdclk_pll.vco);
5849                 return;
5850         }
5851
5852         vco = dev_priv->skl_preferred_vco_freq;
5853         if (vco == 0)
5854                 vco = 8100000;
5855         cdclk = skl_calc_cdclk(0, vco);
5856
5857         skl_set_cdclk(dev_priv, cdclk, vco);
5858 }
5859
5860 static void skl_sanitize_cdclk(struct drm_i915_private *dev_priv)
5861 {
5862         uint32_t cdctl, expected;
5863
5864         /*
5865          * check if the pre-os intialized the display
5866          * There is SWF18 scratchpad register defined which is set by the
5867          * pre-os which can be used by the OS drivers to check the status
5868          */
5869         if ((I915_READ(SWF_ILK(0x18)) & 0x00FFFFFF) == 0)
5870                 goto sanitize;
5871
5872         intel_update_cdclk(&dev_priv->drm);
5873         /* Is PLL enabled and locked ? */
5874         if (dev_priv->cdclk_pll.vco == 0 ||
5875             dev_priv->cdclk_freq == dev_priv->cdclk_pll.ref)
5876                 goto sanitize;
5877
5878         /* DPLL okay; verify the cdclock
5879          *
5880          * Noticed in some instances that the freq selection is correct but
5881          * decimal part is programmed wrong from BIOS where pre-os does not
5882          * enable display. Verify the same as well.
5883          */
5884         cdctl = I915_READ(CDCLK_CTL);
5885         expected = (cdctl & CDCLK_FREQ_SEL_MASK) |
5886                 skl_cdclk_decimal(dev_priv->cdclk_freq);
5887         if (cdctl == expected)
5888                 /* All well; nothing to sanitize */
5889                 return;
5890
5891 sanitize:
5892         DRM_DEBUG_KMS("Sanitizing cdclk programmed by pre-os\n");
5893
5894         /* force cdclk programming */
5895         dev_priv->cdclk_freq = 0;
5896         /* force full PLL disable + enable */
5897         dev_priv->cdclk_pll.vco = -1;
5898 }
5899
5900 /* Adjust CDclk dividers to allow high res or save power if possible */
5901 static void valleyview_set_cdclk(struct drm_device *dev, int cdclk)
5902 {
5903         struct drm_i915_private *dev_priv = to_i915(dev);
5904         u32 val, cmd;
5905
5906         WARN_ON(dev_priv->display.get_display_clock_speed(dev)
5907                                         != dev_priv->cdclk_freq);
5908
5909         if (cdclk >= 320000) /* jump to highest voltage for 400MHz too */
5910                 cmd = 2;
5911         else if (cdclk == 266667)
5912                 cmd = 1;
5913         else
5914                 cmd = 0;
5915
5916         mutex_lock(&dev_priv->rps.hw_lock);
5917         val = vlv_punit_read(dev_priv, PUNIT_REG_DSPFREQ);
5918         val &= ~DSPFREQGUAR_MASK;
5919         val |= (cmd << DSPFREQGUAR_SHIFT);
5920         vlv_punit_write(dev_priv, PUNIT_REG_DSPFREQ, val);
5921         if (wait_for((vlv_punit_read(dev_priv, PUNIT_REG_DSPFREQ) &
5922                       DSPFREQSTAT_MASK) == (cmd << DSPFREQSTAT_SHIFT),
5923                      50)) {
5924                 DRM_ERROR("timed out waiting for CDclk change\n");
5925         }
5926         mutex_unlock(&dev_priv->rps.hw_lock);
5927
5928         mutex_lock(&dev_priv->sb_lock);
5929
5930         if (cdclk == 400000) {
5931                 u32 divider;
5932
5933                 divider = DIV_ROUND_CLOSEST(dev_priv->hpll_freq << 1, cdclk) - 1;
5934
5935                 /* adjust cdclk divider */
5936                 val = vlv_cck_read(dev_priv, CCK_DISPLAY_CLOCK_CONTROL);
5937                 val &= ~CCK_FREQUENCY_VALUES;
5938                 val |= divider;
5939                 vlv_cck_write(dev_priv, CCK_DISPLAY_CLOCK_CONTROL, val);
5940
5941                 if (wait_for((vlv_cck_read(dev_priv, CCK_DISPLAY_CLOCK_CONTROL) &
5942                               CCK_FREQUENCY_STATUS) == (divider << CCK_FREQUENCY_STATUS_SHIFT),
5943                              50))
5944                         DRM_ERROR("timed out waiting for CDclk change\n");
5945         }
5946
5947         /* adjust self-refresh exit latency value */
5948         val = vlv_bunit_read(dev_priv, BUNIT_REG_BISOC);
5949         val &= ~0x7f;
5950
5951         /*
5952          * For high bandwidth configs, we set a higher latency in the bunit
5953          * so that the core display fetch happens in time to avoid underruns.
5954          */
5955         if (cdclk == 400000)
5956                 val |= 4500 / 250; /* 4.5 usec */
5957         else
5958                 val |= 3000 / 250; /* 3.0 usec */
5959         vlv_bunit_write(dev_priv, BUNIT_REG_BISOC, val);
5960
5961         mutex_unlock(&dev_priv->sb_lock);
5962
5963         intel_update_cdclk(dev);
5964 }
5965
5966 static void cherryview_set_cdclk(struct drm_device *dev, int cdclk)
5967 {
5968         struct drm_i915_private *dev_priv = to_i915(dev);
5969         u32 val, cmd;
5970
5971         WARN_ON(dev_priv->display.get_display_clock_speed(dev)
5972                                                 != dev_priv->cdclk_freq);
5973
5974         switch (cdclk) {
5975         case 333333:
5976         case 320000:
5977         case 266667:
5978         case 200000:
5979                 break;
5980         default:
5981                 MISSING_CASE(cdclk);
5982                 return;
5983         }
5984
5985         /*
5986          * Specs are full of misinformation, but testing on actual
5987          * hardware has shown that we just need to write the desired
5988          * CCK divider into the Punit register.
5989          */
5990         cmd = DIV_ROUND_CLOSEST(dev_priv->hpll_freq << 1, cdclk) - 1;
5991
5992         mutex_lock(&dev_priv->rps.hw_lock);
5993         val = vlv_punit_read(dev_priv, PUNIT_REG_DSPFREQ);
5994         val &= ~DSPFREQGUAR_MASK_CHV;
5995         val |= (cmd << DSPFREQGUAR_SHIFT_CHV);
5996         vlv_punit_write(dev_priv, PUNIT_REG_DSPFREQ, val);
5997         if (wait_for((vlv_punit_read(dev_priv, PUNIT_REG_DSPFREQ) &
5998                       DSPFREQSTAT_MASK_CHV) == (cmd << DSPFREQSTAT_SHIFT_CHV),
5999                      50)) {
6000                 DRM_ERROR("timed out waiting for CDclk change\n");
6001         }
6002         mutex_unlock(&dev_priv->rps.hw_lock);
6003
6004         intel_update_cdclk(dev);
6005 }
6006
6007 static int valleyview_calc_cdclk(struct drm_i915_private *dev_priv,
6008                                  int max_pixclk)
6009 {
6010         int freq_320 = (dev_priv->hpll_freq <<  1) % 320000 != 0 ? 333333 : 320000;
6011         int limit = IS_CHERRYVIEW(dev_priv) ? 95 : 90;
6012
6013         /*
6014          * Really only a few cases to deal with, as only 4 CDclks are supported:
6015          *   200MHz
6016          *   267MHz
6017          *   320/333MHz (depends on HPLL freq)
6018          *   400MHz (VLV only)
6019          * So we check to see whether we're above 90% (VLV) or 95% (CHV)
6020          * of the lower bin and adjust if needed.
6021          *
6022          * We seem to get an unstable or solid color picture at 200MHz.
6023          * Not sure what's wrong. For now use 200MHz only when all pipes
6024          * are off.
6025          */
6026         if (!IS_CHERRYVIEW(dev_priv) &&
6027             max_pixclk > freq_320*limit/100)
6028                 return 400000;
6029         else if (max_pixclk > 266667*limit/100)
6030                 return freq_320;
6031         else if (max_pixclk > 0)
6032                 return 266667;
6033         else
6034                 return 200000;
6035 }
6036
6037 static int bxt_calc_cdclk(int max_pixclk)
6038 {
6039         if (max_pixclk > 576000)
6040                 return 624000;
6041         else if (max_pixclk > 384000)
6042                 return 576000;
6043         else if (max_pixclk > 288000)
6044                 return 384000;
6045         else if (max_pixclk > 144000)
6046                 return 288000;
6047         else
6048                 return 144000;
6049 }
6050
6051 /* Compute the max pixel clock for new configuration. */
6052 static int intel_mode_max_pixclk(struct drm_device *dev,
6053                                  struct drm_atomic_state *state)
6054 {
6055         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
6056         struct drm_i915_private *dev_priv = to_i915(dev);
6057         struct drm_crtc *crtc;
6058         struct drm_crtc_state *crtc_state;
6059         unsigned max_pixclk = 0, i;
6060         enum pipe pipe;
6061
6062         memcpy(intel_state->min_pixclk, dev_priv->min_pixclk,
6063                sizeof(intel_state->min_pixclk));
6064
6065         for_each_crtc_in_state(state, crtc, crtc_state, i) {
6066                 int pixclk = 0;
6067
6068                 if (crtc_state->enable)
6069                         pixclk = crtc_state->adjusted_mode.crtc_clock;
6070
6071                 intel_state->min_pixclk[i] = pixclk;
6072         }
6073
6074         for_each_pipe(dev_priv, pipe)
6075                 max_pixclk = max(intel_state->min_pixclk[pipe], max_pixclk);
6076
6077         return max_pixclk;
6078 }
6079
6080 static int valleyview_modeset_calc_cdclk(struct drm_atomic_state *state)
6081 {
6082         struct drm_device *dev = state->dev;
6083         struct drm_i915_private *dev_priv = to_i915(dev);
6084         int max_pixclk = intel_mode_max_pixclk(dev, state);
6085         struct intel_atomic_state *intel_state =
6086                 to_intel_atomic_state(state);
6087
6088         intel_state->cdclk = intel_state->dev_cdclk =
6089                 valleyview_calc_cdclk(dev_priv, max_pixclk);
6090
6091         if (!intel_state->active_crtcs)
6092                 intel_state->dev_cdclk = valleyview_calc_cdclk(dev_priv, 0);
6093
6094         return 0;
6095 }
6096
6097 static int bxt_modeset_calc_cdclk(struct drm_atomic_state *state)
6098 {
6099         int max_pixclk = ilk_max_pixel_rate(state);
6100         struct intel_atomic_state *intel_state =
6101                 to_intel_atomic_state(state);
6102
6103         intel_state->cdclk = intel_state->dev_cdclk =
6104                 bxt_calc_cdclk(max_pixclk);
6105
6106         if (!intel_state->active_crtcs)
6107                 intel_state->dev_cdclk = bxt_calc_cdclk(0);
6108
6109         return 0;
6110 }
6111
6112 static void vlv_program_pfi_credits(struct drm_i915_private *dev_priv)
6113 {
6114         unsigned int credits, default_credits;
6115
6116         if (IS_CHERRYVIEW(dev_priv))
6117                 default_credits = PFI_CREDIT(12);
6118         else
6119                 default_credits = PFI_CREDIT(8);
6120
6121         if (dev_priv->cdclk_freq >= dev_priv->czclk_freq) {
6122                 /* CHV suggested value is 31 or 63 */
6123                 if (IS_CHERRYVIEW(dev_priv))
6124                         credits = PFI_CREDIT_63;
6125                 else
6126                         credits = PFI_CREDIT(15);
6127         } else {
6128                 credits = default_credits;
6129         }
6130
6131         /*
6132          * WA - write default credits before re-programming
6133          * FIXME: should we also set the resend bit here?
6134          */
6135         I915_WRITE(GCI_CONTROL, VGA_FAST_MODE_DISABLE |
6136                    default_credits);
6137
6138         I915_WRITE(GCI_CONTROL, VGA_FAST_MODE_DISABLE |
6139                    credits | PFI_CREDIT_RESEND);
6140
6141         /*
6142          * FIXME is this guaranteed to clear
6143          * immediately or should we poll for it?
6144          */
6145         WARN_ON(I915_READ(GCI_CONTROL) & PFI_CREDIT_RESEND);
6146 }
6147
6148 static void valleyview_modeset_commit_cdclk(struct drm_atomic_state *old_state)
6149 {
6150         struct drm_device *dev = old_state->dev;
6151         struct drm_i915_private *dev_priv = to_i915(dev);
6152         struct intel_atomic_state *old_intel_state =
6153                 to_intel_atomic_state(old_state);
6154         unsigned req_cdclk = old_intel_state->dev_cdclk;
6155
6156         /*
6157          * FIXME: We can end up here with all power domains off, yet
6158          * with a CDCLK frequency other than the minimum. To account
6159          * for this take the PIPE-A power domain, which covers the HW
6160          * blocks needed for the following programming. This can be
6161          * removed once it's guaranteed that we get here either with
6162          * the minimum CDCLK set, or the required power domains
6163          * enabled.
6164          */
6165         intel_display_power_get(dev_priv, POWER_DOMAIN_PIPE_A);
6166
6167         if (IS_CHERRYVIEW(dev))
6168                 cherryview_set_cdclk(dev, req_cdclk);
6169         else
6170                 valleyview_set_cdclk(dev, req_cdclk);
6171
6172         vlv_program_pfi_credits(dev_priv);
6173
6174         intel_display_power_put(dev_priv, POWER_DOMAIN_PIPE_A);
6175 }
6176
6177 static void valleyview_crtc_enable(struct drm_crtc *crtc)
6178 {
6179         struct drm_device *dev = crtc->dev;
6180         struct drm_i915_private *dev_priv = to_i915(dev);
6181         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
6182         struct intel_encoder *encoder;
6183         struct intel_crtc_state *pipe_config =
6184                 to_intel_crtc_state(crtc->state);
6185         int pipe = intel_crtc->pipe;
6186
6187         if (WARN_ON(intel_crtc->active))
6188                 return;
6189
6190         if (intel_crtc_has_dp_encoder(intel_crtc->config))
6191                 intel_dp_set_m_n(intel_crtc, M1_N1);
6192
6193         intel_set_pipe_timings(intel_crtc);
6194         intel_set_pipe_src_size(intel_crtc);
6195
6196         if (IS_CHERRYVIEW(dev) && pipe == PIPE_B) {
6197                 struct drm_i915_private *dev_priv = to_i915(dev);
6198
6199                 I915_WRITE(CHV_BLEND(pipe), CHV_BLEND_LEGACY);
6200                 I915_WRITE(CHV_CANVAS(pipe), 0);
6201         }
6202
6203         i9xx_set_pipeconf(intel_crtc);
6204
6205         intel_crtc->active = true;
6206
6207         intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
6208
6209         for_each_encoder_on_crtc(dev, crtc, encoder)
6210                 if (encoder->pre_pll_enable)
6211                         encoder->pre_pll_enable(encoder);
6212
6213         if (IS_CHERRYVIEW(dev)) {
6214                 chv_prepare_pll(intel_crtc, intel_crtc->config);
6215                 chv_enable_pll(intel_crtc, intel_crtc->config);
6216         } else {
6217                 vlv_prepare_pll(intel_crtc, intel_crtc->config);
6218                 vlv_enable_pll(intel_crtc, intel_crtc->config);
6219         }
6220
6221         for_each_encoder_on_crtc(dev, crtc, encoder)
6222                 if (encoder->pre_enable)
6223                         encoder->pre_enable(encoder);
6224
6225         i9xx_pfit_enable(intel_crtc);
6226
6227         intel_color_load_luts(&pipe_config->base);
6228
6229         intel_update_watermarks(crtc);
6230         intel_enable_pipe(intel_crtc);
6231
6232         assert_vblank_disabled(crtc);
6233         drm_crtc_vblank_on(crtc);
6234
6235         for_each_encoder_on_crtc(dev, crtc, encoder)
6236                 encoder->enable(encoder);
6237 }
6238
6239 static void i9xx_set_pll_dividers(struct intel_crtc *crtc)
6240 {
6241         struct drm_device *dev = crtc->base.dev;
6242         struct drm_i915_private *dev_priv = to_i915(dev);
6243
6244         I915_WRITE(FP0(crtc->pipe), crtc->config->dpll_hw_state.fp0);
6245         I915_WRITE(FP1(crtc->pipe), crtc->config->dpll_hw_state.fp1);
6246 }
6247
6248 static void i9xx_crtc_enable(struct drm_crtc *crtc)
6249 {
6250         struct drm_device *dev = crtc->dev;
6251         struct drm_i915_private *dev_priv = to_i915(dev);
6252         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
6253         struct intel_encoder *encoder;
6254         struct intel_crtc_state *pipe_config =
6255                 to_intel_crtc_state(crtc->state);
6256         enum pipe pipe = intel_crtc->pipe;
6257
6258         if (WARN_ON(intel_crtc->active))
6259                 return;
6260
6261         i9xx_set_pll_dividers(intel_crtc);
6262
6263         if (intel_crtc_has_dp_encoder(intel_crtc->config))
6264                 intel_dp_set_m_n(intel_crtc, M1_N1);
6265
6266         intel_set_pipe_timings(intel_crtc);
6267         intel_set_pipe_src_size(intel_crtc);
6268
6269         i9xx_set_pipeconf(intel_crtc);
6270
6271         intel_crtc->active = true;
6272
6273         if (!IS_GEN2(dev))
6274                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
6275
6276         for_each_encoder_on_crtc(dev, crtc, encoder)
6277                 if (encoder->pre_enable)
6278                         encoder->pre_enable(encoder);
6279
6280         i9xx_enable_pll(intel_crtc);
6281
6282         i9xx_pfit_enable(intel_crtc);
6283
6284         intel_color_load_luts(&pipe_config->base);
6285
6286         intel_update_watermarks(crtc);
6287         intel_enable_pipe(intel_crtc);
6288
6289         assert_vblank_disabled(crtc);
6290         drm_crtc_vblank_on(crtc);
6291
6292         for_each_encoder_on_crtc(dev, crtc, encoder)
6293                 encoder->enable(encoder);
6294 }
6295
6296 static void i9xx_pfit_disable(struct intel_crtc *crtc)
6297 {
6298         struct drm_device *dev = crtc->base.dev;
6299         struct drm_i915_private *dev_priv = to_i915(dev);
6300
6301         if (!crtc->config->gmch_pfit.control)
6302                 return;
6303
6304         assert_pipe_disabled(dev_priv, crtc->pipe);
6305
6306         DRM_DEBUG_DRIVER("disabling pfit, current: 0x%08x\n",
6307                          I915_READ(PFIT_CONTROL));
6308         I915_WRITE(PFIT_CONTROL, 0);
6309 }
6310
6311 static void i9xx_crtc_disable(struct drm_crtc *crtc)
6312 {
6313         struct drm_device *dev = crtc->dev;
6314         struct drm_i915_private *dev_priv = to_i915(dev);
6315         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
6316         struct intel_encoder *encoder;
6317         int pipe = intel_crtc->pipe;
6318
6319         /*
6320          * On gen2 planes are double buffered but the pipe isn't, so we must
6321          * wait for planes to fully turn off before disabling the pipe.
6322          */
6323         if (IS_GEN2(dev))
6324                 intel_wait_for_vblank(dev, pipe);
6325
6326         for_each_encoder_on_crtc(dev, crtc, encoder)
6327                 encoder->disable(encoder);
6328
6329         drm_crtc_vblank_off(crtc);
6330         assert_vblank_disabled(crtc);
6331
6332         intel_disable_pipe(intel_crtc);
6333
6334         i9xx_pfit_disable(intel_crtc);
6335
6336         for_each_encoder_on_crtc(dev, crtc, encoder)
6337                 if (encoder->post_disable)
6338                         encoder->post_disable(encoder);
6339
6340         if (!intel_crtc_has_type(intel_crtc->config, INTEL_OUTPUT_DSI)) {
6341                 if (IS_CHERRYVIEW(dev))
6342                         chv_disable_pll(dev_priv, pipe);
6343                 else if (IS_VALLEYVIEW(dev))
6344                         vlv_disable_pll(dev_priv, pipe);
6345                 else
6346                         i9xx_disable_pll(intel_crtc);
6347         }
6348
6349         for_each_encoder_on_crtc(dev, crtc, encoder)
6350                 if (encoder->post_pll_disable)
6351                         encoder->post_pll_disable(encoder);
6352
6353         if (!IS_GEN2(dev))
6354                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, false);
6355 }
6356
6357 static void intel_crtc_disable_noatomic(struct drm_crtc *crtc)
6358 {
6359         struct intel_encoder *encoder;
6360         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
6361         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
6362         enum intel_display_power_domain domain;
6363         unsigned long domains;
6364
6365         if (!intel_crtc->active)
6366                 return;
6367
6368         if (to_intel_plane_state(crtc->primary->state)->visible) {
6369                 WARN_ON(intel_crtc->flip_work);
6370
6371                 intel_pre_disable_primary_noatomic(crtc);
6372
6373                 intel_crtc_disable_planes(crtc, 1 << drm_plane_index(crtc->primary));
6374                 to_intel_plane_state(crtc->primary->state)->visible = false;
6375         }
6376
6377         dev_priv->display.crtc_disable(crtc);
6378
6379         DRM_DEBUG_KMS("[CRTC:%d:%s] hw state adjusted, was enabled, now disabled\n",
6380                       crtc->base.id, crtc->name);
6381
6382         WARN_ON(drm_atomic_set_mode_for_crtc(crtc->state, NULL) < 0);
6383         crtc->state->active = false;
6384         intel_crtc->active = false;
6385         crtc->enabled = false;
6386         crtc->state->connector_mask = 0;
6387         crtc->state->encoder_mask = 0;
6388
6389         for_each_encoder_on_crtc(crtc->dev, crtc, encoder)
6390                 encoder->base.crtc = NULL;
6391
6392         intel_fbc_disable(intel_crtc);
6393         intel_update_watermarks(crtc);
6394         intel_disable_shared_dpll(intel_crtc);
6395
6396         domains = intel_crtc->enabled_power_domains;
6397         for_each_power_domain(domain, domains)
6398                 intel_display_power_put(dev_priv, domain);
6399         intel_crtc->enabled_power_domains = 0;
6400
6401         dev_priv->active_crtcs &= ~(1 << intel_crtc->pipe);
6402         dev_priv->min_pixclk[intel_crtc->pipe] = 0;
6403 }
6404
6405 /*
6406  * turn all crtc's off, but do not adjust state
6407  * This has to be paired with a call to intel_modeset_setup_hw_state.
6408  */
6409 int intel_display_suspend(struct drm_device *dev)
6410 {
6411         struct drm_i915_private *dev_priv = to_i915(dev);
6412         struct drm_atomic_state *state;
6413         int ret;
6414
6415         state = drm_atomic_helper_suspend(dev);
6416         ret = PTR_ERR_OR_ZERO(state);
6417         if (ret)
6418                 DRM_ERROR("Suspending crtc's failed with %i\n", ret);
6419         else
6420                 dev_priv->modeset_restore_state = state;
6421         return ret;
6422 }
6423
6424 void intel_encoder_destroy(struct drm_encoder *encoder)
6425 {
6426         struct intel_encoder *intel_encoder = to_intel_encoder(encoder);
6427
6428         drm_encoder_cleanup(encoder);
6429         kfree(intel_encoder);
6430 }
6431
6432 /* Cross check the actual hw state with our own modeset state tracking (and it's
6433  * internal consistency). */
6434 static void intel_connector_verify_state(struct intel_connector *connector)
6435 {
6436         struct drm_crtc *crtc = connector->base.state->crtc;
6437
6438         DRM_DEBUG_KMS("[CONNECTOR:%d:%s]\n",
6439                       connector->base.base.id,
6440                       connector->base.name);
6441
6442         if (connector->get_hw_state(connector)) {
6443                 struct intel_encoder *encoder = connector->encoder;
6444                 struct drm_connector_state *conn_state = connector->base.state;
6445
6446                 I915_STATE_WARN(!crtc,
6447                          "connector enabled without attached crtc\n");
6448
6449                 if (!crtc)
6450                         return;
6451
6452                 I915_STATE_WARN(!crtc->state->active,
6453                       "connector is active, but attached crtc isn't\n");
6454
6455                 if (!encoder || encoder->type == INTEL_OUTPUT_DP_MST)
6456                         return;
6457
6458                 I915_STATE_WARN(conn_state->best_encoder != &encoder->base,
6459                         "atomic encoder doesn't match attached encoder\n");
6460
6461                 I915_STATE_WARN(conn_state->crtc != encoder->base.crtc,
6462                         "attached encoder crtc differs from connector crtc\n");
6463         } else {
6464                 I915_STATE_WARN(crtc && crtc->state->active,
6465                         "attached crtc is active, but connector isn't\n");
6466                 I915_STATE_WARN(!crtc && connector->base.state->best_encoder,
6467                         "best encoder set without crtc!\n");
6468         }
6469 }
6470
6471 int intel_connector_init(struct intel_connector *connector)
6472 {
6473         drm_atomic_helper_connector_reset(&connector->base);
6474
6475         if (!connector->base.state)
6476                 return -ENOMEM;
6477
6478         return 0;
6479 }
6480
6481 struct intel_connector *intel_connector_alloc(void)
6482 {
6483         struct intel_connector *connector;
6484
6485         connector = kzalloc(sizeof *connector, GFP_KERNEL);
6486         if (!connector)
6487                 return NULL;
6488
6489         if (intel_connector_init(connector) < 0) {
6490                 kfree(connector);
6491                 return NULL;
6492         }
6493
6494         return connector;
6495 }
6496
6497 /* Simple connector->get_hw_state implementation for encoders that support only
6498  * one connector and no cloning and hence the encoder state determines the state
6499  * of the connector. */
6500 bool intel_connector_get_hw_state(struct intel_connector *connector)
6501 {
6502         enum pipe pipe = 0;
6503         struct intel_encoder *encoder = connector->encoder;
6504
6505         return encoder->get_hw_state(encoder, &pipe);
6506 }
6507
6508 static int pipe_required_fdi_lanes(struct intel_crtc_state *crtc_state)
6509 {
6510         if (crtc_state->base.enable && crtc_state->has_pch_encoder)
6511                 return crtc_state->fdi_lanes;
6512
6513         return 0;
6514 }
6515
6516 static int ironlake_check_fdi_lanes(struct drm_device *dev, enum pipe pipe,
6517                                      struct intel_crtc_state *pipe_config)
6518 {
6519         struct drm_atomic_state *state = pipe_config->base.state;
6520         struct intel_crtc *other_crtc;
6521         struct intel_crtc_state *other_crtc_state;
6522
6523         DRM_DEBUG_KMS("checking fdi config on pipe %c, lanes %i\n",
6524                       pipe_name(pipe), pipe_config->fdi_lanes);
6525         if (pipe_config->fdi_lanes > 4) {
6526                 DRM_DEBUG_KMS("invalid fdi lane config on pipe %c: %i lanes\n",
6527                               pipe_name(pipe), pipe_config->fdi_lanes);
6528                 return -EINVAL;
6529         }
6530
6531         if (IS_HASWELL(dev) || IS_BROADWELL(dev)) {
6532                 if (pipe_config->fdi_lanes > 2) {
6533                         DRM_DEBUG_KMS("only 2 lanes on haswell, required: %i lanes\n",
6534                                       pipe_config->fdi_lanes);
6535                         return -EINVAL;
6536                 } else {
6537                         return 0;
6538                 }
6539         }
6540
6541         if (INTEL_INFO(dev)->num_pipes == 2)
6542                 return 0;
6543
6544         /* Ivybridge 3 pipe is really complicated */
6545         switch (pipe) {
6546         case PIPE_A:
6547                 return 0;
6548         case PIPE_B:
6549                 if (pipe_config->fdi_lanes <= 2)
6550                         return 0;
6551
6552                 other_crtc = to_intel_crtc(intel_get_crtc_for_pipe(dev, PIPE_C));
6553                 other_crtc_state =
6554                         intel_atomic_get_crtc_state(state, other_crtc);
6555                 if (IS_ERR(other_crtc_state))
6556                         return PTR_ERR(other_crtc_state);
6557
6558                 if (pipe_required_fdi_lanes(other_crtc_state) > 0) {
6559                         DRM_DEBUG_KMS("invalid shared fdi lane config on pipe %c: %i lanes\n",
6560                                       pipe_name(pipe), pipe_config->fdi_lanes);
6561                         return -EINVAL;
6562                 }
6563                 return 0;
6564         case PIPE_C:
6565                 if (pipe_config->fdi_lanes > 2) {
6566                         DRM_DEBUG_KMS("only 2 lanes on pipe %c: required %i lanes\n",
6567                                       pipe_name(pipe), pipe_config->fdi_lanes);
6568                         return -EINVAL;
6569                 }
6570
6571                 other_crtc = to_intel_crtc(intel_get_crtc_for_pipe(dev, PIPE_B));
6572                 other_crtc_state =
6573                         intel_atomic_get_crtc_state(state, other_crtc);
6574                 if (IS_ERR(other_crtc_state))
6575                         return PTR_ERR(other_crtc_state);
6576
6577                 if (pipe_required_fdi_lanes(other_crtc_state) > 2) {
6578                         DRM_DEBUG_KMS("fdi link B uses too many lanes to enable link C\n");
6579                         return -EINVAL;
6580                 }
6581                 return 0;
6582         default:
6583                 BUG();
6584         }
6585 }
6586
6587 #define RETRY 1
6588 static int ironlake_fdi_compute_config(struct intel_crtc *intel_crtc,
6589                                        struct intel_crtc_state *pipe_config)
6590 {
6591         struct drm_device *dev = intel_crtc->base.dev;
6592         const struct drm_display_mode *adjusted_mode = &pipe_config->base.adjusted_mode;
6593         int lane, link_bw, fdi_dotclock, ret;
6594         bool needs_recompute = false;
6595
6596 retry:
6597         /* FDI is a binary signal running at ~2.7GHz, encoding
6598          * each output octet as 10 bits. The actual frequency
6599          * is stored as a divider into a 100MHz clock, and the
6600          * mode pixel clock is stored in units of 1KHz.
6601          * Hence the bw of each lane in terms of the mode signal
6602          * is:
6603          */
6604         link_bw = intel_fdi_link_freq(to_i915(dev), pipe_config);
6605
6606         fdi_dotclock = adjusted_mode->crtc_clock;
6607
6608         lane = ironlake_get_lanes_required(fdi_dotclock, link_bw,
6609                                            pipe_config->pipe_bpp);
6610
6611         pipe_config->fdi_lanes = lane;
6612
6613         intel_link_compute_m_n(pipe_config->pipe_bpp, lane, fdi_dotclock,
6614                                link_bw, &pipe_config->fdi_m_n);
6615
6616         ret = ironlake_check_fdi_lanes(dev, intel_crtc->pipe, pipe_config);
6617         if (ret == -EINVAL && pipe_config->pipe_bpp > 6*3) {
6618                 pipe_config->pipe_bpp -= 2*3;
6619                 DRM_DEBUG_KMS("fdi link bw constraint, reducing pipe bpp to %i\n",
6620                               pipe_config->pipe_bpp);
6621                 needs_recompute = true;
6622                 pipe_config->bw_constrained = true;
6623
6624                 goto retry;
6625         }
6626
6627         if (needs_recompute)
6628                 return RETRY;
6629
6630         return ret;
6631 }
6632
6633 static bool pipe_config_supports_ips(struct drm_i915_private *dev_priv,
6634                                      struct intel_crtc_state *pipe_config)
6635 {
6636         if (pipe_config->pipe_bpp > 24)
6637                 return false;
6638
6639         /* HSW can handle pixel rate up to cdclk? */
6640         if (IS_HASWELL(dev_priv))
6641                 return true;
6642
6643         /*
6644          * We compare against max which means we must take
6645          * the increased cdclk requirement into account when
6646          * calculating the new cdclk.
6647          *
6648          * Should measure whether using a lower cdclk w/o IPS
6649          */
6650         return ilk_pipe_pixel_rate(pipe_config) <=
6651                 dev_priv->max_cdclk_freq * 95 / 100;
6652 }
6653
6654 static void hsw_compute_ips_config(struct intel_crtc *crtc,
6655                                    struct intel_crtc_state *pipe_config)
6656 {
6657         struct drm_device *dev = crtc->base.dev;
6658         struct drm_i915_private *dev_priv = to_i915(dev);
6659
6660         pipe_config->ips_enabled = i915.enable_ips &&
6661                 hsw_crtc_supports_ips(crtc) &&
6662                 pipe_config_supports_ips(dev_priv, pipe_config);
6663 }
6664
6665 static bool intel_crtc_supports_double_wide(const struct intel_crtc *crtc)
6666 {
6667         const struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
6668
6669         /* GDG double wide on either pipe, otherwise pipe A only */
6670         return INTEL_INFO(dev_priv)->gen < 4 &&
6671                 (crtc->pipe == PIPE_A || IS_I915G(dev_priv));
6672 }
6673
6674 static int intel_crtc_compute_config(struct intel_crtc *crtc,
6675                                      struct intel_crtc_state *pipe_config)
6676 {
6677         struct drm_device *dev = crtc->base.dev;
6678         struct drm_i915_private *dev_priv = to_i915(dev);
6679         const struct drm_display_mode *adjusted_mode = &pipe_config->base.adjusted_mode;
6680         int clock_limit = dev_priv->max_dotclk_freq;
6681
6682         if (INTEL_INFO(dev)->gen < 4) {
6683                 clock_limit = dev_priv->max_cdclk_freq * 9 / 10;
6684
6685                 /*
6686                  * Enable double wide mode when the dot clock
6687                  * is > 90% of the (display) core speed.
6688                  */
6689                 if (intel_crtc_supports_double_wide(crtc) &&
6690                     adjusted_mode->crtc_clock > clock_limit) {
6691                         clock_limit = dev_priv->max_dotclk_freq;
6692                         pipe_config->double_wide = true;
6693                 }
6694         }
6695
6696         if (adjusted_mode->crtc_clock > clock_limit) {
6697                 DRM_DEBUG_KMS("requested pixel clock (%d kHz) too high (max: %d kHz, double wide: %s)\n",
6698                               adjusted_mode->crtc_clock, clock_limit,
6699                               yesno(pipe_config->double_wide));
6700                 return -EINVAL;
6701         }
6702
6703         /*
6704          * Pipe horizontal size must be even in:
6705          * - DVO ganged mode
6706          * - LVDS dual channel mode
6707          * - Double wide pipe
6708          */
6709         if ((intel_crtc_has_type(pipe_config, INTEL_OUTPUT_LVDS) &&
6710              intel_is_dual_link_lvds(dev)) || pipe_config->double_wide)
6711                 pipe_config->pipe_src_w &= ~1;
6712
6713         /* Cantiga+ cannot handle modes with a hsync front porch of 0.
6714          * WaPruneModeWithIncorrectHsyncOffset:ctg,elk,ilk,snb,ivb,vlv,hsw.
6715          */
6716         if ((INTEL_INFO(dev)->gen > 4 || IS_G4X(dev)) &&
6717                 adjusted_mode->crtc_hsync_start == adjusted_mode->crtc_hdisplay)
6718                 return -EINVAL;
6719
6720         if (HAS_IPS(dev))
6721                 hsw_compute_ips_config(crtc, pipe_config);
6722
6723         if (pipe_config->has_pch_encoder)
6724                 return ironlake_fdi_compute_config(crtc, pipe_config);
6725
6726         return 0;
6727 }
6728
6729 static int skylake_get_display_clock_speed(struct drm_device *dev)
6730 {
6731         struct drm_i915_private *dev_priv = to_i915(dev);
6732         uint32_t cdctl;
6733
6734         skl_dpll0_update(dev_priv);
6735
6736         if (dev_priv->cdclk_pll.vco == 0)
6737                 return dev_priv->cdclk_pll.ref;
6738
6739         cdctl = I915_READ(CDCLK_CTL);
6740
6741         if (dev_priv->cdclk_pll.vco == 8640000) {
6742                 switch (cdctl & CDCLK_FREQ_SEL_MASK) {
6743                 case CDCLK_FREQ_450_432:
6744                         return 432000;
6745                 case CDCLK_FREQ_337_308:
6746                         return 308571;
6747                 case CDCLK_FREQ_540:
6748                         return 540000;
6749                 case CDCLK_FREQ_675_617:
6750                         return 617143;
6751                 default:
6752                         MISSING_CASE(cdctl & CDCLK_FREQ_SEL_MASK);
6753                 }
6754         } else {
6755                 switch (cdctl & CDCLK_FREQ_SEL_MASK) {
6756                 case CDCLK_FREQ_450_432:
6757                         return 450000;
6758                 case CDCLK_FREQ_337_308:
6759                         return 337500;
6760                 case CDCLK_FREQ_540:
6761                         return 540000;
6762                 case CDCLK_FREQ_675_617:
6763                         return 675000;
6764                 default:
6765                         MISSING_CASE(cdctl & CDCLK_FREQ_SEL_MASK);
6766                 }
6767         }
6768
6769         return dev_priv->cdclk_pll.ref;
6770 }
6771
6772 static void bxt_de_pll_update(struct drm_i915_private *dev_priv)
6773 {
6774         u32 val;
6775
6776         dev_priv->cdclk_pll.ref = 19200;
6777         dev_priv->cdclk_pll.vco = 0;
6778
6779         val = I915_READ(BXT_DE_PLL_ENABLE);
6780         if ((val & BXT_DE_PLL_PLL_ENABLE) == 0)
6781                 return;
6782
6783         if (WARN_ON((val & BXT_DE_PLL_LOCK) == 0))
6784                 return;
6785
6786         val = I915_READ(BXT_DE_PLL_CTL);
6787         dev_priv->cdclk_pll.vco = (val & BXT_DE_PLL_RATIO_MASK) *
6788                 dev_priv->cdclk_pll.ref;
6789 }
6790
6791 static int broxton_get_display_clock_speed(struct drm_device *dev)
6792 {
6793         struct drm_i915_private *dev_priv = to_i915(dev);
6794         u32 divider;
6795         int div, vco;
6796
6797         bxt_de_pll_update(dev_priv);
6798
6799         vco = dev_priv->cdclk_pll.vco;
6800         if (vco == 0)
6801                 return dev_priv->cdclk_pll.ref;
6802
6803         divider = I915_READ(CDCLK_CTL) & BXT_CDCLK_CD2X_DIV_SEL_MASK;
6804
6805         switch (divider) {
6806         case BXT_CDCLK_CD2X_DIV_SEL_1:
6807                 div = 2;
6808                 break;
6809         case BXT_CDCLK_CD2X_DIV_SEL_1_5:
6810                 div = 3;
6811                 break;
6812         case BXT_CDCLK_CD2X_DIV_SEL_2:
6813                 div = 4;
6814                 break;
6815         case BXT_CDCLK_CD2X_DIV_SEL_4:
6816                 div = 8;
6817                 break;
6818         default:
6819                 MISSING_CASE(divider);
6820                 return dev_priv->cdclk_pll.ref;
6821         }
6822
6823         return DIV_ROUND_CLOSEST(vco, div);
6824 }
6825
6826 static int broadwell_get_display_clock_speed(struct drm_device *dev)
6827 {
6828         struct drm_i915_private *dev_priv = to_i915(dev);
6829         uint32_t lcpll = I915_READ(LCPLL_CTL);
6830         uint32_t freq = lcpll & LCPLL_CLK_FREQ_MASK;
6831
6832         if (lcpll & LCPLL_CD_SOURCE_FCLK)
6833                 return 800000;
6834         else if (I915_READ(FUSE_STRAP) & HSW_CDCLK_LIMIT)
6835                 return 450000;
6836         else if (freq == LCPLL_CLK_FREQ_450)
6837                 return 450000;
6838         else if (freq == LCPLL_CLK_FREQ_54O_BDW)
6839                 return 540000;
6840         else if (freq == LCPLL_CLK_FREQ_337_5_BDW)
6841                 return 337500;
6842         else
6843                 return 675000;
6844 }
6845
6846 static int haswell_get_display_clock_speed(struct drm_device *dev)
6847 {
6848         struct drm_i915_private *dev_priv = to_i915(dev);
6849         uint32_t lcpll = I915_READ(LCPLL_CTL);
6850         uint32_t freq = lcpll & LCPLL_CLK_FREQ_MASK;
6851
6852         if (lcpll & LCPLL_CD_SOURCE_FCLK)
6853                 return 800000;
6854         else if (I915_READ(FUSE_STRAP) & HSW_CDCLK_LIMIT)
6855                 return 450000;
6856         else if (freq == LCPLL_CLK_FREQ_450)
6857                 return 450000;
6858         else if (IS_HSW_ULT(dev))
6859                 return 337500;
6860         else
6861                 return 540000;
6862 }
6863
6864 static int valleyview_get_display_clock_speed(struct drm_device *dev)
6865 {
6866         return vlv_get_cck_clock_hpll(to_i915(dev), "cdclk",
6867                                       CCK_DISPLAY_CLOCK_CONTROL);
6868 }
6869
6870 static int ilk_get_display_clock_speed(struct drm_device *dev)
6871 {
6872         return 450000;
6873 }
6874
6875 static int i945_get_display_clock_speed(struct drm_device *dev)
6876 {
6877         return 400000;
6878 }
6879
6880 static int i915_get_display_clock_speed(struct drm_device *dev)
6881 {
6882         return 333333;
6883 }
6884
6885 static int i9xx_misc_get_display_clock_speed(struct drm_device *dev)
6886 {
6887         return 200000;
6888 }
6889
6890 static int pnv_get_display_clock_speed(struct drm_device *dev)
6891 {
6892         u16 gcfgc = 0;
6893
6894         pci_read_config_word(dev->pdev, GCFGC, &gcfgc);
6895
6896         switch (gcfgc & GC_DISPLAY_CLOCK_MASK) {
6897         case GC_DISPLAY_CLOCK_267_MHZ_PNV:
6898                 return 266667;
6899         case GC_DISPLAY_CLOCK_333_MHZ_PNV:
6900                 return 333333;
6901         case GC_DISPLAY_CLOCK_444_MHZ_PNV:
6902                 return 444444;
6903         case GC_DISPLAY_CLOCK_200_MHZ_PNV:
6904                 return 200000;
6905         default:
6906                 DRM_ERROR("Unknown pnv display core clock 0x%04x\n", gcfgc);
6907         case GC_DISPLAY_CLOCK_133_MHZ_PNV:
6908                 return 133333;
6909         case GC_DISPLAY_CLOCK_167_MHZ_PNV:
6910                 return 166667;
6911         }
6912 }
6913
6914 static int i915gm_get_display_clock_speed(struct drm_device *dev)
6915 {
6916         u16 gcfgc = 0;
6917
6918         pci_read_config_word(dev->pdev, GCFGC, &gcfgc);
6919
6920         if (gcfgc & GC_LOW_FREQUENCY_ENABLE)
6921                 return 133333;
6922         else {
6923                 switch (gcfgc & GC_DISPLAY_CLOCK_MASK) {
6924                 case GC_DISPLAY_CLOCK_333_MHZ:
6925                         return 333333;
6926                 default:
6927                 case GC_DISPLAY_CLOCK_190_200_MHZ:
6928                         return 190000;
6929                 }
6930         }
6931 }
6932
6933 static int i865_get_display_clock_speed(struct drm_device *dev)
6934 {
6935         return 266667;
6936 }
6937
6938 static int i85x_get_display_clock_speed(struct drm_device *dev)
6939 {
6940         u16 hpllcc = 0;
6941
6942         /*
6943          * 852GM/852GMV only supports 133 MHz and the HPLLCC
6944          * encoding is different :(
6945          * FIXME is this the right way to detect 852GM/852GMV?
6946          */
6947         if (dev->pdev->revision == 0x1)
6948                 return 133333;
6949
6950         pci_bus_read_config_word(dev->pdev->bus,
6951                                  PCI_DEVFN(0, 3), HPLLCC, &hpllcc);
6952
6953         /* Assume that the hardware is in the high speed state.  This
6954          * should be the default.
6955          */
6956         switch (hpllcc & GC_CLOCK_CONTROL_MASK) {
6957         case GC_CLOCK_133_200:
6958         case GC_CLOCK_133_200_2:
6959         case GC_CLOCK_100_200:
6960                 return 200000;
6961         case GC_CLOCK_166_250:
6962                 return 250000;
6963         case GC_CLOCK_100_133:
6964                 return 133333;
6965         case GC_CLOCK_133_266:
6966         case GC_CLOCK_133_266_2:
6967         case GC_CLOCK_166_266:
6968                 return 266667;
6969         }
6970
6971         /* Shouldn't happen */
6972         return 0;
6973 }
6974
6975 static int i830_get_display_clock_speed(struct drm_device *dev)
6976 {
6977         return 133333;
6978 }
6979
6980 static unsigned int intel_hpll_vco(struct drm_device *dev)
6981 {
6982         struct drm_i915_private *dev_priv = to_i915(dev);
6983         static const unsigned int blb_vco[8] = {
6984                 [0] = 3200000,
6985                 [1] = 4000000,
6986                 [2] = 5333333,
6987                 [3] = 4800000,
6988                 [4] = 6400000,
6989         };
6990         static const unsigned int pnv_vco[8] = {
6991                 [0] = 3200000,
6992                 [1] = 4000000,
6993                 [2] = 5333333,
6994                 [3] = 4800000,
6995                 [4] = 2666667,
6996         };
6997         static const unsigned int cl_vco[8] = {
6998                 [0] = 3200000,
6999                 [1] = 4000000,
7000                 [2] = 5333333,
7001                 [3] = 6400000,
7002                 [4] = 3333333,
7003                 [5] = 3566667,
7004                 [6] = 4266667,
7005         };
7006         static const unsigned int elk_vco[8] = {
7007                 [0] = 3200000,
7008                 [1] = 4000000,
7009                 [2] = 5333333,
7010                 [3] = 4800000,
7011         };
7012         static const unsigned int ctg_vco[8] = {
7013                 [0] = 3200000,
7014                 [1] = 4000000,
7015                 [2] = 5333333,
7016                 [3] = 6400000,
7017                 [4] = 2666667,
7018                 [5] = 4266667,
7019         };
7020         const unsigned int *vco_table;
7021         unsigned int vco;
7022         uint8_t tmp = 0;
7023
7024         /* FIXME other chipsets? */
7025         if (IS_GM45(dev))
7026                 vco_table = ctg_vco;
7027         else if (IS_G4X(dev))
7028                 vco_table = elk_vco;
7029         else if (IS_CRESTLINE(dev))
7030                 vco_table = cl_vco;
7031         else if (IS_PINEVIEW(dev))
7032                 vco_table = pnv_vco;
7033         else if (IS_G33(dev))
7034                 vco_table = blb_vco;
7035         else
7036                 return 0;
7037
7038         tmp = I915_READ(IS_MOBILE(dev) ? HPLLVCO_MOBILE : HPLLVCO);
7039
7040         vco = vco_table[tmp & 0x7];
7041         if (vco == 0)
7042                 DRM_ERROR("Bad HPLL VCO (HPLLVCO=0x%02x)\n", tmp);
7043         else
7044                 DRM_DEBUG_KMS("HPLL VCO %u kHz\n", vco);
7045
7046         return vco;
7047 }
7048
7049 static int gm45_get_display_clock_speed(struct drm_device *dev)
7050 {
7051         unsigned int cdclk_sel, vco = intel_hpll_vco(dev);
7052         uint16_t tmp = 0;
7053
7054         pci_read_config_word(dev->pdev, GCFGC, &tmp);
7055
7056         cdclk_sel = (tmp >> 12) & 0x1;
7057
7058         switch (vco) {
7059         case 2666667:
7060         case 4000000:
7061         case 5333333:
7062                 return cdclk_sel ? 333333 : 222222;
7063         case 3200000:
7064                 return cdclk_sel ? 320000 : 228571;
7065         default:
7066                 DRM_ERROR("Unable to determine CDCLK. HPLL VCO=%u, CFGC=0x%04x\n", vco, tmp);
7067                 return 222222;
7068         }
7069 }
7070
7071 static int i965gm_get_display_clock_speed(struct drm_device *dev)
7072 {
7073         static const uint8_t div_3200[] = { 16, 10,  8 };
7074         static const uint8_t div_4000[] = { 20, 12, 10 };
7075         static const uint8_t div_5333[] = { 24, 16, 14 };
7076         const uint8_t *div_table;
7077         unsigned int cdclk_sel, vco = intel_hpll_vco(dev);
7078         uint16_t tmp = 0;
7079
7080         pci_read_config_word(dev->pdev, GCFGC, &tmp);
7081
7082         cdclk_sel = ((tmp >> 8) & 0x1f) - 1;
7083
7084         if (cdclk_sel >= ARRAY_SIZE(div_3200))
7085                 goto fail;
7086
7087         switch (vco) {
7088         case 3200000:
7089                 div_table = div_3200;
7090                 break;
7091         case 4000000:
7092                 div_table = div_4000;
7093                 break;
7094         case 5333333:
7095                 div_table = div_5333;
7096                 break;
7097         default:
7098                 goto fail;
7099         }
7100
7101         return DIV_ROUND_CLOSEST(vco, div_table[cdclk_sel]);
7102
7103 fail:
7104         DRM_ERROR("Unable to determine CDCLK. HPLL VCO=%u kHz, CFGC=0x%04x\n", vco, tmp);
7105         return 200000;
7106 }
7107
7108 static int g33_get_display_clock_speed(struct drm_device *dev)
7109 {
7110         static const uint8_t div_3200[] = { 12, 10,  8,  7, 5, 16 };
7111         static const uint8_t div_4000[] = { 14, 12, 10,  8, 6, 20 };
7112         static const uint8_t div_4800[] = { 20, 14, 12, 10, 8, 24 };
7113         static const uint8_t div_5333[] = { 20, 16, 12, 12, 8, 28 };
7114         const uint8_t *div_table;
7115         unsigned int cdclk_sel, vco = intel_hpll_vco(dev);
7116         uint16_t tmp = 0;
7117
7118         pci_read_config_word(dev->pdev, GCFGC, &tmp);
7119
7120         cdclk_sel = (tmp >> 4) & 0x7;
7121
7122         if (cdclk_sel >= ARRAY_SIZE(div_3200))
7123                 goto fail;
7124
7125         switch (vco) {
7126         case 3200000:
7127                 div_table = div_3200;
7128                 break;
7129         case 4000000:
7130                 div_table = div_4000;
7131                 break;
7132         case 4800000:
7133                 div_table = div_4800;
7134                 break;
7135         case 5333333:
7136                 div_table = div_5333;
7137                 break;
7138         default:
7139                 goto fail;
7140         }
7141
7142         return DIV_ROUND_CLOSEST(vco, div_table[cdclk_sel]);
7143
7144 fail:
7145         DRM_ERROR("Unable to determine CDCLK. HPLL VCO=%u kHz, CFGC=0x%08x\n", vco, tmp);
7146         return 190476;
7147 }
7148
7149 static void
7150 intel_reduce_m_n_ratio(uint32_t *num, uint32_t *den)
7151 {
7152         while (*num > DATA_LINK_M_N_MASK ||
7153                *den > DATA_LINK_M_N_MASK) {
7154                 *num >>= 1;
7155                 *den >>= 1;
7156         }
7157 }
7158
7159 static void compute_m_n(unsigned int m, unsigned int n,
7160                         uint32_t *ret_m, uint32_t *ret_n)
7161 {
7162         *ret_n = min_t(unsigned int, roundup_pow_of_two(n), DATA_LINK_N_MAX);
7163         *ret_m = div_u64((uint64_t) m * *ret_n, n);
7164         intel_reduce_m_n_ratio(ret_m, ret_n);
7165 }
7166
7167 void
7168 intel_link_compute_m_n(int bits_per_pixel, int nlanes,
7169                        int pixel_clock, int link_clock,
7170                        struct intel_link_m_n *m_n)
7171 {
7172         m_n->tu = 64;
7173
7174         compute_m_n(bits_per_pixel * pixel_clock,
7175                     link_clock * nlanes * 8,
7176                     &m_n->gmch_m, &m_n->gmch_n);
7177
7178         compute_m_n(pixel_clock, link_clock,
7179                     &m_n->link_m, &m_n->link_n);
7180 }
7181
7182 static inline bool intel_panel_use_ssc(struct drm_i915_private *dev_priv)
7183 {
7184         if (i915.panel_use_ssc >= 0)
7185                 return i915.panel_use_ssc != 0;
7186         return dev_priv->vbt.lvds_use_ssc
7187                 && !(dev_priv->quirks & QUIRK_LVDS_SSC_DISABLE);
7188 }
7189
7190 static uint32_t pnv_dpll_compute_fp(struct dpll *dpll)
7191 {
7192         return (1 << dpll->n) << 16 | dpll->m2;
7193 }
7194
7195 static uint32_t i9xx_dpll_compute_fp(struct dpll *dpll)
7196 {
7197         return dpll->n << 16 | dpll->m1 << 8 | dpll->m2;
7198 }
7199
7200 static void i9xx_update_pll_dividers(struct intel_crtc *crtc,
7201                                      struct intel_crtc_state *crtc_state,
7202                                      struct dpll *reduced_clock)
7203 {
7204         struct drm_device *dev = crtc->base.dev;
7205         u32 fp, fp2 = 0;
7206
7207         if (IS_PINEVIEW(dev)) {
7208                 fp = pnv_dpll_compute_fp(&crtc_state->dpll);
7209                 if (reduced_clock)
7210                         fp2 = pnv_dpll_compute_fp(reduced_clock);
7211         } else {
7212                 fp = i9xx_dpll_compute_fp(&crtc_state->dpll);
7213                 if (reduced_clock)
7214                         fp2 = i9xx_dpll_compute_fp(reduced_clock);
7215         }
7216
7217         crtc_state->dpll_hw_state.fp0 = fp;
7218
7219         crtc->lowfreq_avail = false;
7220         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS) &&
7221             reduced_clock) {
7222                 crtc_state->dpll_hw_state.fp1 = fp2;
7223                 crtc->lowfreq_avail = true;
7224         } else {
7225                 crtc_state->dpll_hw_state.fp1 = fp;
7226         }
7227 }
7228
7229 static void vlv_pllb_recal_opamp(struct drm_i915_private *dev_priv, enum pipe
7230                 pipe)
7231 {
7232         u32 reg_val;
7233
7234         /*
7235          * PLLB opamp always calibrates to max value of 0x3f, force enable it
7236          * and set it to a reasonable value instead.
7237          */
7238         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW9(1));
7239         reg_val &= 0xffffff00;
7240         reg_val |= 0x00000030;
7241         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW9(1), reg_val);
7242
7243         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_REF_DW13);
7244         reg_val &= 0x8cffffff;
7245         reg_val = 0x8c000000;
7246         vlv_dpio_write(dev_priv, pipe, VLV_REF_DW13, reg_val);
7247
7248         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW9(1));
7249         reg_val &= 0xffffff00;
7250         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW9(1), reg_val);
7251
7252         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_REF_DW13);
7253         reg_val &= 0x00ffffff;
7254         reg_val |= 0xb0000000;
7255         vlv_dpio_write(dev_priv, pipe, VLV_REF_DW13, reg_val);
7256 }
7257
7258 static void intel_pch_transcoder_set_m_n(struct intel_crtc *crtc,
7259                                          struct intel_link_m_n *m_n)
7260 {
7261         struct drm_device *dev = crtc->base.dev;
7262         struct drm_i915_private *dev_priv = to_i915(dev);
7263         int pipe = crtc->pipe;
7264
7265         I915_WRITE(PCH_TRANS_DATA_M1(pipe), TU_SIZE(m_n->tu) | m_n->gmch_m);
7266         I915_WRITE(PCH_TRANS_DATA_N1(pipe), m_n->gmch_n);
7267         I915_WRITE(PCH_TRANS_LINK_M1(pipe), m_n->link_m);
7268         I915_WRITE(PCH_TRANS_LINK_N1(pipe), m_n->link_n);
7269 }
7270
7271 static void intel_cpu_transcoder_set_m_n(struct intel_crtc *crtc,
7272                                          struct intel_link_m_n *m_n,
7273                                          struct intel_link_m_n *m2_n2)
7274 {
7275         struct drm_device *dev = crtc->base.dev;
7276         struct drm_i915_private *dev_priv = to_i915(dev);
7277         int pipe = crtc->pipe;
7278         enum transcoder transcoder = crtc->config->cpu_transcoder;
7279
7280         if (INTEL_INFO(dev)->gen >= 5) {
7281                 I915_WRITE(PIPE_DATA_M1(transcoder), TU_SIZE(m_n->tu) | m_n->gmch_m);
7282                 I915_WRITE(PIPE_DATA_N1(transcoder), m_n->gmch_n);
7283                 I915_WRITE(PIPE_LINK_M1(transcoder), m_n->link_m);
7284                 I915_WRITE(PIPE_LINK_N1(transcoder), m_n->link_n);
7285                 /* M2_N2 registers to be set only for gen < 8 (M2_N2 available
7286                  * for gen < 8) and if DRRS is supported (to make sure the
7287                  * registers are not unnecessarily accessed).
7288                  */
7289                 if (m2_n2 && (IS_CHERRYVIEW(dev) || INTEL_INFO(dev)->gen < 8) &&
7290                         crtc->config->has_drrs) {
7291                         I915_WRITE(PIPE_DATA_M2(transcoder),
7292                                         TU_SIZE(m2_n2->tu) | m2_n2->gmch_m);
7293                         I915_WRITE(PIPE_DATA_N2(transcoder), m2_n2->gmch_n);
7294                         I915_WRITE(PIPE_LINK_M2(transcoder), m2_n2->link_m);
7295                         I915_WRITE(PIPE_LINK_N2(transcoder), m2_n2->link_n);
7296                 }
7297         } else {
7298                 I915_WRITE(PIPE_DATA_M_G4X(pipe), TU_SIZE(m_n->tu) | m_n->gmch_m);
7299                 I915_WRITE(PIPE_DATA_N_G4X(pipe), m_n->gmch_n);
7300                 I915_WRITE(PIPE_LINK_M_G4X(pipe), m_n->link_m);
7301                 I915_WRITE(PIPE_LINK_N_G4X(pipe), m_n->link_n);
7302         }
7303 }
7304
7305 void intel_dp_set_m_n(struct intel_crtc *crtc, enum link_m_n_set m_n)
7306 {
7307         struct intel_link_m_n *dp_m_n, *dp_m2_n2 = NULL;
7308
7309         if (m_n == M1_N1) {
7310                 dp_m_n = &crtc->config->dp_m_n;
7311                 dp_m2_n2 = &crtc->config->dp_m2_n2;
7312         } else if (m_n == M2_N2) {
7313
7314                 /*
7315                  * M2_N2 registers are not supported. Hence m2_n2 divider value
7316                  * needs to be programmed into M1_N1.
7317                  */
7318                 dp_m_n = &crtc->config->dp_m2_n2;
7319         } else {
7320                 DRM_ERROR("Unsupported divider value\n");
7321                 return;
7322         }
7323
7324         if (crtc->config->has_pch_encoder)
7325                 intel_pch_transcoder_set_m_n(crtc, &crtc->config->dp_m_n);
7326         else
7327                 intel_cpu_transcoder_set_m_n(crtc, dp_m_n, dp_m2_n2);
7328 }
7329
7330 static void vlv_compute_dpll(struct intel_crtc *crtc,
7331                              struct intel_crtc_state *pipe_config)
7332 {
7333         pipe_config->dpll_hw_state.dpll = DPLL_INTEGRATED_REF_CLK_VLV |
7334                 DPLL_REF_CLK_ENABLE_VLV | DPLL_VGA_MODE_DIS;
7335         if (crtc->pipe != PIPE_A)
7336                 pipe_config->dpll_hw_state.dpll |= DPLL_INTEGRATED_CRI_CLK_VLV;
7337
7338         /* DPLL not used with DSI, but still need the rest set up */
7339         if (!intel_crtc_has_type(pipe_config, INTEL_OUTPUT_DSI))
7340                 pipe_config->dpll_hw_state.dpll |= DPLL_VCO_ENABLE |
7341                         DPLL_EXT_BUFFER_ENABLE_VLV;
7342
7343         pipe_config->dpll_hw_state.dpll_md =
7344                 (pipe_config->pixel_multiplier - 1) << DPLL_MD_UDI_MULTIPLIER_SHIFT;
7345 }
7346
7347 static void chv_compute_dpll(struct intel_crtc *crtc,
7348                              struct intel_crtc_state *pipe_config)
7349 {
7350         pipe_config->dpll_hw_state.dpll = DPLL_SSC_REF_CLK_CHV |
7351                 DPLL_REF_CLK_ENABLE_VLV | DPLL_VGA_MODE_DIS;
7352         if (crtc->pipe != PIPE_A)
7353                 pipe_config->dpll_hw_state.dpll |= DPLL_INTEGRATED_CRI_CLK_VLV;
7354
7355         /* DPLL not used with DSI, but still need the rest set up */
7356         if (!intel_crtc_has_type(pipe_config, INTEL_OUTPUT_DSI))
7357                 pipe_config->dpll_hw_state.dpll |= DPLL_VCO_ENABLE;
7358
7359         pipe_config->dpll_hw_state.dpll_md =
7360                 (pipe_config->pixel_multiplier - 1) << DPLL_MD_UDI_MULTIPLIER_SHIFT;
7361 }
7362
7363 static void vlv_prepare_pll(struct intel_crtc *crtc,
7364                             const struct intel_crtc_state *pipe_config)
7365 {
7366         struct drm_device *dev = crtc->base.dev;
7367         struct drm_i915_private *dev_priv = to_i915(dev);
7368         enum pipe pipe = crtc->pipe;
7369         u32 mdiv;
7370         u32 bestn, bestm1, bestm2, bestp1, bestp2;
7371         u32 coreclk, reg_val;
7372
7373         /* Enable Refclk */
7374         I915_WRITE(DPLL(pipe),
7375                    pipe_config->dpll_hw_state.dpll &
7376                    ~(DPLL_VCO_ENABLE | DPLL_EXT_BUFFER_ENABLE_VLV));
7377
7378         /* No need to actually set up the DPLL with DSI */
7379         if ((pipe_config->dpll_hw_state.dpll & DPLL_VCO_ENABLE) == 0)
7380                 return;
7381
7382         mutex_lock(&dev_priv->sb_lock);
7383
7384         bestn = pipe_config->dpll.n;
7385         bestm1 = pipe_config->dpll.m1;
7386         bestm2 = pipe_config->dpll.m2;
7387         bestp1 = pipe_config->dpll.p1;
7388         bestp2 = pipe_config->dpll.p2;
7389
7390         /* See eDP HDMI DPIO driver vbios notes doc */
7391
7392         /* PLL B needs special handling */
7393         if (pipe == PIPE_B)
7394                 vlv_pllb_recal_opamp(dev_priv, pipe);
7395
7396         /* Set up Tx target for periodic Rcomp update */
7397         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW9_BCAST, 0x0100000f);
7398
7399         /* Disable target IRef on PLL */
7400         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW8(pipe));
7401         reg_val &= 0x00ffffff;
7402         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW8(pipe), reg_val);
7403
7404         /* Disable fast lock */
7405         vlv_dpio_write(dev_priv, pipe, VLV_CMN_DW0, 0x610);
7406
7407         /* Set idtafcrecal before PLL is enabled */
7408         mdiv = ((bestm1 << DPIO_M1DIV_SHIFT) | (bestm2 & DPIO_M2DIV_MASK));
7409         mdiv |= ((bestp1 << DPIO_P1_SHIFT) | (bestp2 << DPIO_P2_SHIFT));
7410         mdiv |= ((bestn << DPIO_N_SHIFT));
7411         mdiv |= (1 << DPIO_K_SHIFT);
7412
7413         /*
7414          * Post divider depends on pixel clock rate, DAC vs digital (and LVDS,
7415          * but we don't support that).
7416          * Note: don't use the DAC post divider as it seems unstable.
7417          */
7418         mdiv |= (DPIO_POST_DIV_HDMIDP << DPIO_POST_DIV_SHIFT);
7419         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW3(pipe), mdiv);
7420
7421         mdiv |= DPIO_ENABLE_CALIBRATION;
7422         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW3(pipe), mdiv);
7423
7424         /* Set HBR and RBR LPF coefficients */
7425         if (pipe_config->port_clock == 162000 ||
7426             intel_crtc_has_type(crtc->config, INTEL_OUTPUT_ANALOG) ||
7427             intel_crtc_has_type(crtc->config, INTEL_OUTPUT_HDMI))
7428                 vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW10(pipe),
7429                                  0x009f0003);
7430         else
7431                 vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW10(pipe),
7432                                  0x00d0000f);
7433
7434         if (intel_crtc_has_dp_encoder(pipe_config)) {
7435                 /* Use SSC source */
7436                 if (pipe == PIPE_A)
7437                         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW5(pipe),
7438                                          0x0df40000);
7439                 else
7440                         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW5(pipe),
7441                                          0x0df70000);
7442         } else { /* HDMI or VGA */
7443                 /* Use bend source */
7444                 if (pipe == PIPE_A)
7445                         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW5(pipe),
7446                                          0x0df70000);
7447                 else
7448                         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW5(pipe),
7449                                          0x0df40000);
7450         }
7451
7452         coreclk = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW7(pipe));
7453         coreclk = (coreclk & 0x0000ff00) | 0x01c00000;
7454         if (intel_crtc_has_dp_encoder(crtc->config))
7455                 coreclk |= 0x01000000;
7456         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW7(pipe), coreclk);
7457
7458         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW11(pipe), 0x87871000);
7459         mutex_unlock(&dev_priv->sb_lock);
7460 }
7461
7462 static void chv_prepare_pll(struct intel_crtc *crtc,
7463                             const struct intel_crtc_state *pipe_config)
7464 {
7465         struct drm_device *dev = crtc->base.dev;
7466         struct drm_i915_private *dev_priv = to_i915(dev);
7467         enum pipe pipe = crtc->pipe;
7468         enum dpio_channel port = vlv_pipe_to_channel(pipe);
7469         u32 loopfilter, tribuf_calcntr;
7470         u32 bestn, bestm1, bestm2, bestp1, bestp2, bestm2_frac;
7471         u32 dpio_val;
7472         int vco;
7473
7474         /* Enable Refclk and SSC */
7475         I915_WRITE(DPLL(pipe),
7476                    pipe_config->dpll_hw_state.dpll & ~DPLL_VCO_ENABLE);
7477
7478         /* No need to actually set up the DPLL with DSI */
7479         if ((pipe_config->dpll_hw_state.dpll & DPLL_VCO_ENABLE) == 0)
7480                 return;
7481
7482         bestn = pipe_config->dpll.n;
7483         bestm2_frac = pipe_config->dpll.m2 & 0x3fffff;
7484         bestm1 = pipe_config->dpll.m1;
7485         bestm2 = pipe_config->dpll.m2 >> 22;
7486         bestp1 = pipe_config->dpll.p1;
7487         bestp2 = pipe_config->dpll.p2;
7488         vco = pipe_config->dpll.vco;
7489         dpio_val = 0;
7490         loopfilter = 0;
7491
7492         mutex_lock(&dev_priv->sb_lock);
7493
7494         /* p1 and p2 divider */
7495         vlv_dpio_write(dev_priv, pipe, CHV_CMN_DW13(port),
7496                         5 << DPIO_CHV_S1_DIV_SHIFT |
7497                         bestp1 << DPIO_CHV_P1_DIV_SHIFT |
7498                         bestp2 << DPIO_CHV_P2_DIV_SHIFT |
7499                         1 << DPIO_CHV_K_DIV_SHIFT);
7500
7501         /* Feedback post-divider - m2 */
7502         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW0(port), bestm2);
7503
7504         /* Feedback refclk divider - n and m1 */
7505         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW1(port),
7506                         DPIO_CHV_M1_DIV_BY_2 |
7507                         1 << DPIO_CHV_N_DIV_SHIFT);
7508
7509         /* M2 fraction division */
7510         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW2(port), bestm2_frac);
7511
7512         /* M2 fraction division enable */
7513         dpio_val = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW3(port));
7514         dpio_val &= ~(DPIO_CHV_FEEDFWD_GAIN_MASK | DPIO_CHV_FRAC_DIV_EN);
7515         dpio_val |= (2 << DPIO_CHV_FEEDFWD_GAIN_SHIFT);
7516         if (bestm2_frac)
7517                 dpio_val |= DPIO_CHV_FRAC_DIV_EN;
7518         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW3(port), dpio_val);
7519
7520         /* Program digital lock detect threshold */
7521         dpio_val = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW9(port));
7522         dpio_val &= ~(DPIO_CHV_INT_LOCK_THRESHOLD_MASK |
7523                                         DPIO_CHV_INT_LOCK_THRESHOLD_SEL_COARSE);
7524         dpio_val |= (0x5 << DPIO_CHV_INT_LOCK_THRESHOLD_SHIFT);
7525         if (!bestm2_frac)
7526                 dpio_val |= DPIO_CHV_INT_LOCK_THRESHOLD_SEL_COARSE;
7527         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW9(port), dpio_val);
7528
7529         /* Loop filter */
7530         if (vco == 5400000) {
7531                 loopfilter |= (0x3 << DPIO_CHV_PROP_COEFF_SHIFT);
7532                 loopfilter |= (0x8 << DPIO_CHV_INT_COEFF_SHIFT);
7533                 loopfilter |= (0x1 << DPIO_CHV_GAIN_CTRL_SHIFT);
7534                 tribuf_calcntr = 0x9;
7535         } else if (vco <= 6200000) {
7536                 loopfilter |= (0x5 << DPIO_CHV_PROP_COEFF_SHIFT);
7537                 loopfilter |= (0xB << DPIO_CHV_INT_COEFF_SHIFT);
7538                 loopfilter |= (0x3 << DPIO_CHV_GAIN_CTRL_SHIFT);
7539                 tribuf_calcntr = 0x9;
7540         } else if (vco <= 6480000) {
7541                 loopfilter |= (0x4 << DPIO_CHV_PROP_COEFF_SHIFT);
7542                 loopfilter |= (0x9 << DPIO_CHV_INT_COEFF_SHIFT);
7543                 loopfilter |= (0x3 << DPIO_CHV_GAIN_CTRL_SHIFT);
7544                 tribuf_calcntr = 0x8;
7545         } else {
7546                 /* Not supported. Apply the same limits as in the max case */
7547                 loopfilter |= (0x4 << DPIO_CHV_PROP_COEFF_SHIFT);
7548                 loopfilter |= (0x9 << DPIO_CHV_INT_COEFF_SHIFT);
7549                 loopfilter |= (0x3 << DPIO_CHV_GAIN_CTRL_SHIFT);
7550                 tribuf_calcntr = 0;
7551         }
7552         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW6(port), loopfilter);
7553
7554         dpio_val = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW8(port));
7555         dpio_val &= ~DPIO_CHV_TDC_TARGET_CNT_MASK;
7556         dpio_val |= (tribuf_calcntr << DPIO_CHV_TDC_TARGET_CNT_SHIFT);
7557         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW8(port), dpio_val);
7558
7559         /* AFC Recal */
7560         vlv_dpio_write(dev_priv, pipe, CHV_CMN_DW14(port),
7561                         vlv_dpio_read(dev_priv, pipe, CHV_CMN_DW14(port)) |
7562                         DPIO_AFC_RECAL);
7563
7564         mutex_unlock(&dev_priv->sb_lock);
7565 }
7566
7567 /**
7568  * vlv_force_pll_on - forcibly enable just the PLL
7569  * @dev_priv: i915 private structure
7570  * @pipe: pipe PLL to enable
7571  * @dpll: PLL configuration
7572  *
7573  * Enable the PLL for @pipe using the supplied @dpll config. To be used
7574  * in cases where we need the PLL enabled even when @pipe is not going to
7575  * be enabled.
7576  */
7577 int vlv_force_pll_on(struct drm_device *dev, enum pipe pipe,
7578                      const struct dpll *dpll)
7579 {
7580         struct intel_crtc *crtc =
7581                 to_intel_crtc(intel_get_crtc_for_pipe(dev, pipe));
7582         struct intel_crtc_state *pipe_config;
7583
7584         pipe_config = kzalloc(sizeof(*pipe_config), GFP_KERNEL);
7585         if (!pipe_config)
7586                 return -ENOMEM;
7587
7588         pipe_config->base.crtc = &crtc->base;
7589         pipe_config->pixel_multiplier = 1;
7590         pipe_config->dpll = *dpll;
7591
7592         if (IS_CHERRYVIEW(dev)) {
7593                 chv_compute_dpll(crtc, pipe_config);
7594                 chv_prepare_pll(crtc, pipe_config);
7595                 chv_enable_pll(crtc, pipe_config);
7596         } else {
7597                 vlv_compute_dpll(crtc, pipe_config);
7598                 vlv_prepare_pll(crtc, pipe_config);
7599                 vlv_enable_pll(crtc, pipe_config);
7600         }
7601
7602         kfree(pipe_config);
7603
7604         return 0;
7605 }
7606
7607 /**
7608  * vlv_force_pll_off - forcibly disable just the PLL
7609  * @dev_priv: i915 private structure
7610  * @pipe: pipe PLL to disable
7611  *
7612  * Disable the PLL for @pipe. To be used in cases where we need
7613  * the PLL enabled even when @pipe is not going to be enabled.
7614  */
7615 void vlv_force_pll_off(struct drm_device *dev, enum pipe pipe)
7616 {
7617         if (IS_CHERRYVIEW(dev))
7618                 chv_disable_pll(to_i915(dev), pipe);
7619         else
7620                 vlv_disable_pll(to_i915(dev), pipe);
7621 }
7622
7623 static void i9xx_compute_dpll(struct intel_crtc *crtc,
7624                               struct intel_crtc_state *crtc_state,
7625                               struct dpll *reduced_clock)
7626 {
7627         struct drm_device *dev = crtc->base.dev;
7628         struct drm_i915_private *dev_priv = to_i915(dev);
7629         u32 dpll;
7630         struct dpll *clock = &crtc_state->dpll;
7631
7632         i9xx_update_pll_dividers(crtc, crtc_state, reduced_clock);
7633
7634         dpll = DPLL_VGA_MODE_DIS;
7635
7636         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS))
7637                 dpll |= DPLLB_MODE_LVDS;
7638         else
7639                 dpll |= DPLLB_MODE_DAC_SERIAL;
7640
7641         if (IS_I945G(dev) || IS_I945GM(dev) || IS_G33(dev)) {
7642                 dpll |= (crtc_state->pixel_multiplier - 1)
7643                         << SDVO_MULTIPLIER_SHIFT_HIRES;
7644         }
7645
7646         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_SDVO) ||
7647             intel_crtc_has_type(crtc_state, INTEL_OUTPUT_HDMI))
7648                 dpll |= DPLL_SDVO_HIGH_SPEED;
7649
7650         if (intel_crtc_has_dp_encoder(crtc_state))
7651                 dpll |= DPLL_SDVO_HIGH_SPEED;
7652
7653         /* compute bitmask from p1 value */
7654         if (IS_PINEVIEW(dev))
7655                 dpll |= (1 << (clock->p1 - 1)) << DPLL_FPA01_P1_POST_DIV_SHIFT_PINEVIEW;
7656         else {
7657                 dpll |= (1 << (clock->p1 - 1)) << DPLL_FPA01_P1_POST_DIV_SHIFT;
7658                 if (IS_G4X(dev) && reduced_clock)
7659                         dpll |= (1 << (reduced_clock->p1 - 1)) << DPLL_FPA1_P1_POST_DIV_SHIFT;
7660         }
7661         switch (clock->p2) {
7662         case 5:
7663                 dpll |= DPLL_DAC_SERIAL_P2_CLOCK_DIV_5;
7664                 break;
7665         case 7:
7666                 dpll |= DPLLB_LVDS_P2_CLOCK_DIV_7;
7667                 break;
7668         case 10:
7669                 dpll |= DPLL_DAC_SERIAL_P2_CLOCK_DIV_10;
7670                 break;
7671         case 14:
7672                 dpll |= DPLLB_LVDS_P2_CLOCK_DIV_14;
7673                 break;
7674         }
7675         if (INTEL_INFO(dev)->gen >= 4)
7676                 dpll |= (6 << PLL_LOAD_PULSE_PHASE_SHIFT);
7677
7678         if (crtc_state->sdvo_tv_clock)
7679                 dpll |= PLL_REF_INPUT_TVCLKINBC;
7680         else if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS) &&
7681                  intel_panel_use_ssc(dev_priv))
7682                 dpll |= PLLB_REF_INPUT_SPREADSPECTRUMIN;
7683         else
7684                 dpll |= PLL_REF_INPUT_DREFCLK;
7685
7686         dpll |= DPLL_VCO_ENABLE;
7687         crtc_state->dpll_hw_state.dpll = dpll;
7688
7689         if (INTEL_INFO(dev)->gen >= 4) {
7690                 u32 dpll_md = (crtc_state->pixel_multiplier - 1)
7691                         << DPLL_MD_UDI_MULTIPLIER_SHIFT;
7692                 crtc_state->dpll_hw_state.dpll_md = dpll_md;
7693         }
7694 }
7695
7696 static void i8xx_compute_dpll(struct intel_crtc *crtc,
7697                               struct intel_crtc_state *crtc_state,
7698                               struct dpll *reduced_clock)
7699 {
7700         struct drm_device *dev = crtc->base.dev;
7701         struct drm_i915_private *dev_priv = to_i915(dev);
7702         u32 dpll;
7703         struct dpll *clock = &crtc_state->dpll;
7704
7705         i9xx_update_pll_dividers(crtc, crtc_state, reduced_clock);
7706
7707         dpll = DPLL_VGA_MODE_DIS;
7708
7709         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS)) {
7710                 dpll |= (1 << (clock->p1 - 1)) << DPLL_FPA01_P1_POST_DIV_SHIFT;
7711         } else {
7712                 if (clock->p1 == 2)
7713                         dpll |= PLL_P1_DIVIDE_BY_TWO;
7714                 else
7715                         dpll |= (clock->p1 - 2) << DPLL_FPA01_P1_POST_DIV_SHIFT;
7716                 if (clock->p2 == 4)
7717                         dpll |= PLL_P2_DIVIDE_BY_4;
7718         }
7719
7720         if (!IS_I830(dev) && intel_crtc_has_type(crtc_state, INTEL_OUTPUT_DVO))
7721                 dpll |= DPLL_DVO_2X_MODE;
7722
7723         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS) &&
7724             intel_panel_use_ssc(dev_priv))
7725                 dpll |= PLLB_REF_INPUT_SPREADSPECTRUMIN;
7726         else
7727                 dpll |= PLL_REF_INPUT_DREFCLK;
7728
7729         dpll |= DPLL_VCO_ENABLE;
7730         crtc_state->dpll_hw_state.dpll = dpll;
7731 }
7732
7733 static void intel_set_pipe_timings(struct intel_crtc *intel_crtc)
7734 {
7735         struct drm_device *dev = intel_crtc->base.dev;
7736         struct drm_i915_private *dev_priv = to_i915(dev);
7737         enum pipe pipe = intel_crtc->pipe;
7738         enum transcoder cpu_transcoder = intel_crtc->config->cpu_transcoder;
7739         const struct drm_display_mode *adjusted_mode = &intel_crtc->config->base.adjusted_mode;
7740         uint32_t crtc_vtotal, crtc_vblank_end;
7741         int vsyncshift = 0;
7742
7743         /* We need to be careful not to changed the adjusted mode, for otherwise
7744          * the hw state checker will get angry at the mismatch. */
7745         crtc_vtotal = adjusted_mode->crtc_vtotal;
7746         crtc_vblank_end = adjusted_mode->crtc_vblank_end;
7747
7748         if (adjusted_mode->flags & DRM_MODE_FLAG_INTERLACE) {
7749                 /* the chip adds 2 halflines automatically */
7750                 crtc_vtotal -= 1;
7751                 crtc_vblank_end -= 1;
7752
7753                 if (intel_crtc_has_type(intel_crtc->config, INTEL_OUTPUT_SDVO))
7754                         vsyncshift = (adjusted_mode->crtc_htotal - 1) / 2;
7755                 else
7756                         vsyncshift = adjusted_mode->crtc_hsync_start -
7757                                 adjusted_mode->crtc_htotal / 2;
7758                 if (vsyncshift < 0)
7759                         vsyncshift += adjusted_mode->crtc_htotal;
7760         }
7761
7762         if (INTEL_INFO(dev)->gen > 3)
7763                 I915_WRITE(VSYNCSHIFT(cpu_transcoder), vsyncshift);
7764
7765         I915_WRITE(HTOTAL(cpu_transcoder),
7766                    (adjusted_mode->crtc_hdisplay - 1) |
7767                    ((adjusted_mode->crtc_htotal - 1) << 16));
7768         I915_WRITE(HBLANK(cpu_transcoder),
7769                    (adjusted_mode->crtc_hblank_start - 1) |
7770                    ((adjusted_mode->crtc_hblank_end - 1) << 16));
7771         I915_WRITE(HSYNC(cpu_transcoder),
7772                    (adjusted_mode->crtc_hsync_start - 1) |
7773                    ((adjusted_mode->crtc_hsync_end - 1) << 16));
7774
7775         I915_WRITE(VTOTAL(cpu_transcoder),
7776                    (adjusted_mode->crtc_vdisplay - 1) |
7777                    ((crtc_vtotal - 1) << 16));
7778         I915_WRITE(VBLANK(cpu_transcoder),
7779                    (adjusted_mode->crtc_vblank_start - 1) |
7780                    ((crtc_vblank_end - 1) << 16));
7781         I915_WRITE(VSYNC(cpu_transcoder),
7782                    (adjusted_mode->crtc_vsync_start - 1) |
7783                    ((adjusted_mode->crtc_vsync_end - 1) << 16));
7784
7785         /* Workaround: when the EDP input selection is B, the VTOTAL_B must be
7786          * programmed with the VTOTAL_EDP value. Same for VTOTAL_C. This is
7787          * documented on the DDI_FUNC_CTL register description, EDP Input Select
7788          * bits. */
7789         if (IS_HASWELL(dev) && cpu_transcoder == TRANSCODER_EDP &&
7790             (pipe == PIPE_B || pipe == PIPE_C))
7791                 I915_WRITE(VTOTAL(pipe), I915_READ(VTOTAL(cpu_transcoder)));
7792
7793 }
7794
7795 static void intel_set_pipe_src_size(struct intel_crtc *intel_crtc)
7796 {
7797         struct drm_device *dev = intel_crtc->base.dev;
7798         struct drm_i915_private *dev_priv = to_i915(dev);
7799         enum pipe pipe = intel_crtc->pipe;
7800
7801         /* pipesrc controls the size that is scaled from, which should
7802          * always be the user's requested size.
7803          */
7804         I915_WRITE(PIPESRC(pipe),
7805                    ((intel_crtc->config->pipe_src_w - 1) << 16) |
7806                    (intel_crtc->config->pipe_src_h - 1));
7807 }
7808
7809 static void intel_get_pipe_timings(struct intel_crtc *crtc,
7810                                    struct intel_crtc_state *pipe_config)
7811 {
7812         struct drm_device *dev = crtc->base.dev;
7813         struct drm_i915_private *dev_priv = to_i915(dev);
7814         enum transcoder cpu_transcoder = pipe_config->cpu_transcoder;
7815         uint32_t tmp;
7816
7817         tmp = I915_READ(HTOTAL(cpu_transcoder));
7818         pipe_config->base.adjusted_mode.crtc_hdisplay = (tmp & 0xffff) + 1;
7819         pipe_config->base.adjusted_mode.crtc_htotal = ((tmp >> 16) & 0xffff) + 1;
7820         tmp = I915_READ(HBLANK(cpu_transcoder));
7821         pipe_config->base.adjusted_mode.crtc_hblank_start = (tmp & 0xffff) + 1;
7822         pipe_config->base.adjusted_mode.crtc_hblank_end = ((tmp >> 16) & 0xffff) + 1;
7823         tmp = I915_READ(HSYNC(cpu_transcoder));
7824         pipe_config->base.adjusted_mode.crtc_hsync_start = (tmp & 0xffff) + 1;
7825         pipe_config->base.adjusted_mode.crtc_hsync_end = ((tmp >> 16) & 0xffff) + 1;
7826
7827         tmp = I915_READ(VTOTAL(cpu_transcoder));
7828         pipe_config->base.adjusted_mode.crtc_vdisplay = (tmp & 0xffff) + 1;
7829         pipe_config->base.adjusted_mode.crtc_vtotal = ((tmp >> 16) & 0xffff) + 1;
7830         tmp = I915_READ(VBLANK(cpu_transcoder));
7831         pipe_config->base.adjusted_mode.crtc_vblank_start = (tmp & 0xffff) + 1;
7832         pipe_config->base.adjusted_mode.crtc_vblank_end = ((tmp >> 16) & 0xffff) + 1;
7833         tmp = I915_READ(VSYNC(cpu_transcoder));
7834         pipe_config->base.adjusted_mode.crtc_vsync_start = (tmp & 0xffff) + 1;
7835         pipe_config->base.adjusted_mode.crtc_vsync_end = ((tmp >> 16) & 0xffff) + 1;
7836
7837         if (I915_READ(PIPECONF(cpu_transcoder)) & PIPECONF_INTERLACE_MASK) {
7838                 pipe_config->base.adjusted_mode.flags |= DRM_MODE_FLAG_INTERLACE;
7839                 pipe_config->base.adjusted_mode.crtc_vtotal += 1;
7840                 pipe_config->base.adjusted_mode.crtc_vblank_end += 1;
7841         }
7842 }
7843
7844 static void intel_get_pipe_src_size(struct intel_crtc *crtc,
7845                                     struct intel_crtc_state *pipe_config)
7846 {
7847         struct drm_device *dev = crtc->base.dev;
7848         struct drm_i915_private *dev_priv = to_i915(dev);
7849         u32 tmp;
7850
7851         tmp = I915_READ(PIPESRC(crtc->pipe));
7852         pipe_config->pipe_src_h = (tmp & 0xffff) + 1;
7853         pipe_config->pipe_src_w = ((tmp >> 16) & 0xffff) + 1;
7854
7855         pipe_config->base.mode.vdisplay = pipe_config->pipe_src_h;
7856         pipe_config->base.mode.hdisplay = pipe_config->pipe_src_w;
7857 }
7858
7859 void intel_mode_from_pipe_config(struct drm_display_mode *mode,
7860                                  struct intel_crtc_state *pipe_config)
7861 {
7862         mode->hdisplay = pipe_config->base.adjusted_mode.crtc_hdisplay;
7863         mode->htotal = pipe_config->base.adjusted_mode.crtc_htotal;
7864         mode->hsync_start = pipe_config->base.adjusted_mode.crtc_hsync_start;
7865         mode->hsync_end = pipe_config->base.adjusted_mode.crtc_hsync_end;
7866
7867         mode->vdisplay = pipe_config->base.adjusted_mode.crtc_vdisplay;
7868         mode->vtotal = pipe_config->base.adjusted_mode.crtc_vtotal;
7869         mode->vsync_start = pipe_config->base.adjusted_mode.crtc_vsync_start;
7870         mode->vsync_end = pipe_config->base.adjusted_mode.crtc_vsync_end;
7871
7872         mode->flags = pipe_config->base.adjusted_mode.flags;
7873         mode->type = DRM_MODE_TYPE_DRIVER;
7874
7875         mode->clock = pipe_config->base.adjusted_mode.crtc_clock;
7876         mode->flags |= pipe_config->base.adjusted_mode.flags;
7877
7878         mode->hsync = drm_mode_hsync(mode);
7879         mode->vrefresh = drm_mode_vrefresh(mode);
7880         drm_mode_set_name(mode);
7881 }
7882
7883 static void i9xx_set_pipeconf(struct intel_crtc *intel_crtc)
7884 {
7885         struct drm_device *dev = intel_crtc->base.dev;
7886         struct drm_i915_private *dev_priv = to_i915(dev);
7887         uint32_t pipeconf;
7888
7889         pipeconf = 0;
7890
7891         if ((intel_crtc->pipe == PIPE_A && dev_priv->quirks & QUIRK_PIPEA_FORCE) ||
7892             (intel_crtc->pipe == PIPE_B && dev_priv->quirks & QUIRK_PIPEB_FORCE))
7893                 pipeconf |= I915_READ(PIPECONF(intel_crtc->pipe)) & PIPECONF_ENABLE;
7894
7895         if (intel_crtc->config->double_wide)
7896                 pipeconf |= PIPECONF_DOUBLE_WIDE;
7897
7898         /* only g4x and later have fancy bpc/dither controls */
7899         if (IS_G4X(dev) || IS_VALLEYVIEW(dev) || IS_CHERRYVIEW(dev)) {
7900                 /* Bspec claims that we can't use dithering for 30bpp pipes. */
7901                 if (intel_crtc->config->dither && intel_crtc->config->pipe_bpp != 30)
7902                         pipeconf |= PIPECONF_DITHER_EN |
7903                                     PIPECONF_DITHER_TYPE_SP;
7904
7905                 switch (intel_crtc->config->pipe_bpp) {
7906                 case 18:
7907                         pipeconf |= PIPECONF_6BPC;
7908                         break;
7909                 case 24:
7910                         pipeconf |= PIPECONF_8BPC;
7911                         break;
7912                 case 30:
7913                         pipeconf |= PIPECONF_10BPC;
7914                         break;
7915                 default:
7916                         /* Case prevented by intel_choose_pipe_bpp_dither. */
7917                         BUG();
7918                 }
7919         }
7920
7921         if (HAS_PIPE_CXSR(dev)) {
7922                 if (intel_crtc->lowfreq_avail) {
7923                         DRM_DEBUG_KMS("enabling CxSR downclocking\n");
7924                         pipeconf |= PIPECONF_CXSR_DOWNCLOCK;
7925                 } else {
7926                         DRM_DEBUG_KMS("disabling CxSR downclocking\n");
7927                 }
7928         }
7929
7930         if (intel_crtc->config->base.adjusted_mode.flags & DRM_MODE_FLAG_INTERLACE) {
7931                 if (INTEL_INFO(dev)->gen < 4 ||
7932                     intel_crtc_has_type(intel_crtc->config, INTEL_OUTPUT_SDVO))
7933                         pipeconf |= PIPECONF_INTERLACE_W_FIELD_INDICATION;
7934                 else
7935                         pipeconf |= PIPECONF_INTERLACE_W_SYNC_SHIFT;
7936         } else
7937                 pipeconf |= PIPECONF_PROGRESSIVE;
7938
7939         if ((IS_VALLEYVIEW(dev) || IS_CHERRYVIEW(dev)) &&
7940              intel_crtc->config->limited_color_range)
7941                 pipeconf |= PIPECONF_COLOR_RANGE_SELECT;
7942
7943         I915_WRITE(PIPECONF(intel_crtc->pipe), pipeconf);
7944         POSTING_READ(PIPECONF(intel_crtc->pipe));
7945 }
7946
7947 static int i8xx_crtc_compute_clock(struct intel_crtc *crtc,
7948                                    struct intel_crtc_state *crtc_state)
7949 {
7950         struct drm_device *dev = crtc->base.dev;
7951         struct drm_i915_private *dev_priv = to_i915(dev);
7952         const struct intel_limit *limit;
7953         int refclk = 48000;
7954
7955         memset(&crtc_state->dpll_hw_state, 0,
7956                sizeof(crtc_state->dpll_hw_state));
7957
7958         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS)) {
7959                 if (intel_panel_use_ssc(dev_priv)) {
7960                         refclk = dev_priv->vbt.lvds_ssc_freq;
7961                         DRM_DEBUG_KMS("using SSC reference clock of %d kHz\n", refclk);
7962                 }
7963
7964                 limit = &intel_limits_i8xx_lvds;
7965         } else if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_DVO)) {
7966                 limit = &intel_limits_i8xx_dvo;
7967         } else {
7968                 limit = &intel_limits_i8xx_dac;
7969         }
7970
7971         if (!crtc_state->clock_set &&
7972             !i9xx_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
7973                                  refclk, NULL, &crtc_state->dpll)) {
7974                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
7975                 return -EINVAL;
7976         }
7977
7978         i8xx_compute_dpll(crtc, crtc_state, NULL);
7979
7980         return 0;
7981 }
7982
7983 static int g4x_crtc_compute_clock(struct intel_crtc *crtc,
7984                                   struct intel_crtc_state *crtc_state)
7985 {
7986         struct drm_device *dev = crtc->base.dev;
7987         struct drm_i915_private *dev_priv = to_i915(dev);
7988         const struct intel_limit *limit;
7989         int refclk = 96000;
7990
7991         memset(&crtc_state->dpll_hw_state, 0,
7992                sizeof(crtc_state->dpll_hw_state));
7993
7994         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS)) {
7995                 if (intel_panel_use_ssc(dev_priv)) {
7996                         refclk = dev_priv->vbt.lvds_ssc_freq;
7997                         DRM_DEBUG_KMS("using SSC reference clock of %d kHz\n", refclk);
7998                 }
7999
8000                 if (intel_is_dual_link_lvds(dev))
8001                         limit = &intel_limits_g4x_dual_channel_lvds;
8002                 else
8003                         limit = &intel_limits_g4x_single_channel_lvds;
8004         } else if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_HDMI) ||
8005                    intel_crtc_has_type(crtc_state, INTEL_OUTPUT_ANALOG)) {
8006                 limit = &intel_limits_g4x_hdmi;
8007         } else if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_SDVO)) {
8008                 limit = &intel_limits_g4x_sdvo;
8009         } else {
8010                 /* The option is for other outputs */
8011                 limit = &intel_limits_i9xx_sdvo;
8012         }
8013
8014         if (!crtc_state->clock_set &&
8015             !g4x_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
8016                                 refclk, NULL, &crtc_state->dpll)) {
8017                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
8018                 return -EINVAL;
8019         }
8020
8021         i9xx_compute_dpll(crtc, crtc_state, NULL);
8022
8023         return 0;
8024 }
8025
8026 static int pnv_crtc_compute_clock(struct intel_crtc *crtc,
8027                                   struct intel_crtc_state *crtc_state)
8028 {
8029         struct drm_device *dev = crtc->base.dev;
8030         struct drm_i915_private *dev_priv = to_i915(dev);
8031         const struct intel_limit *limit;
8032         int refclk = 96000;
8033
8034         memset(&crtc_state->dpll_hw_state, 0,
8035                sizeof(crtc_state->dpll_hw_state));
8036
8037         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS)) {
8038                 if (intel_panel_use_ssc(dev_priv)) {
8039                         refclk = dev_priv->vbt.lvds_ssc_freq;
8040                         DRM_DEBUG_KMS("using SSC reference clock of %d kHz\n", refclk);
8041                 }
8042
8043                 limit = &intel_limits_pineview_lvds;
8044         } else {
8045                 limit = &intel_limits_pineview_sdvo;
8046         }
8047
8048         if (!crtc_state->clock_set &&
8049             !pnv_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
8050                                 refclk, NULL, &crtc_state->dpll)) {
8051                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
8052                 return -EINVAL;
8053         }
8054
8055         i9xx_compute_dpll(crtc, crtc_state, NULL);
8056
8057         return 0;
8058 }
8059
8060 static int i9xx_crtc_compute_clock(struct intel_crtc *crtc,
8061                                    struct intel_crtc_state *crtc_state)
8062 {
8063         struct drm_device *dev = crtc->base.dev;
8064         struct drm_i915_private *dev_priv = to_i915(dev);
8065         const struct intel_limit *limit;
8066         int refclk = 96000;
8067
8068         memset(&crtc_state->dpll_hw_state, 0,
8069                sizeof(crtc_state->dpll_hw_state));
8070
8071         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS)) {
8072                 if (intel_panel_use_ssc(dev_priv)) {
8073                         refclk = dev_priv->vbt.lvds_ssc_freq;
8074                         DRM_DEBUG_KMS("using SSC reference clock of %d kHz\n", refclk);
8075                 }
8076
8077                 limit = &intel_limits_i9xx_lvds;
8078         } else {
8079                 limit = &intel_limits_i9xx_sdvo;
8080         }
8081
8082         if (!crtc_state->clock_set &&
8083             !i9xx_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
8084                                  refclk, NULL, &crtc_state->dpll)) {
8085                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
8086                 return -EINVAL;
8087         }
8088
8089         i9xx_compute_dpll(crtc, crtc_state, NULL);
8090
8091         return 0;
8092 }
8093
8094 static int chv_crtc_compute_clock(struct intel_crtc *crtc,
8095                                   struct intel_crtc_state *crtc_state)
8096 {
8097         int refclk = 100000;
8098         const struct intel_limit *limit = &intel_limits_chv;
8099
8100         memset(&crtc_state->dpll_hw_state, 0,
8101                sizeof(crtc_state->dpll_hw_state));
8102
8103         if (!crtc_state->clock_set &&
8104             !chv_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
8105                                 refclk, NULL, &crtc_state->dpll)) {
8106                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
8107                 return -EINVAL;
8108         }
8109
8110         chv_compute_dpll(crtc, crtc_state);
8111
8112         return 0;
8113 }
8114
8115 static int vlv_crtc_compute_clock(struct intel_crtc *crtc,
8116                                   struct intel_crtc_state *crtc_state)
8117 {
8118         int refclk = 100000;
8119         const struct intel_limit *limit = &intel_limits_vlv;
8120
8121         memset(&crtc_state->dpll_hw_state, 0,
8122                sizeof(crtc_state->dpll_hw_state));
8123
8124         if (!crtc_state->clock_set &&
8125             !vlv_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
8126                                 refclk, NULL, &crtc_state->dpll)) {
8127                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
8128                 return -EINVAL;
8129         }
8130
8131         vlv_compute_dpll(crtc, crtc_state);
8132
8133         return 0;
8134 }
8135
8136 static void i9xx_get_pfit_config(struct intel_crtc *crtc,
8137                                  struct intel_crtc_state *pipe_config)
8138 {
8139         struct drm_device *dev = crtc->base.dev;
8140         struct drm_i915_private *dev_priv = to_i915(dev);
8141         uint32_t tmp;
8142
8143         if (INTEL_INFO(dev)->gen <= 3 && (IS_I830(dev) || !IS_MOBILE(dev)))
8144                 return;
8145
8146         tmp = I915_READ(PFIT_CONTROL);
8147         if (!(tmp & PFIT_ENABLE))
8148                 return;
8149
8150         /* Check whether the pfit is attached to our pipe. */
8151         if (INTEL_INFO(dev)->gen < 4) {
8152                 if (crtc->pipe != PIPE_B)
8153                         return;
8154         } else {
8155                 if ((tmp & PFIT_PIPE_MASK) != (crtc->pipe << PFIT_PIPE_SHIFT))
8156                         return;
8157         }
8158
8159         pipe_config->gmch_pfit.control = tmp;
8160         pipe_config->gmch_pfit.pgm_ratios = I915_READ(PFIT_PGM_RATIOS);
8161 }
8162
8163 static void vlv_crtc_clock_get(struct intel_crtc *crtc,
8164                                struct intel_crtc_state *pipe_config)
8165 {
8166         struct drm_device *dev = crtc->base.dev;
8167         struct drm_i915_private *dev_priv = to_i915(dev);
8168         int pipe = pipe_config->cpu_transcoder;
8169         struct dpll clock;
8170         u32 mdiv;
8171         int refclk = 100000;
8172
8173         /* In case of DSI, DPLL will not be used */
8174         if ((pipe_config->dpll_hw_state.dpll & DPLL_VCO_ENABLE) == 0)
8175                 return;
8176
8177         mutex_lock(&dev_priv->sb_lock);
8178         mdiv = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW3(pipe));
8179         mutex_unlock(&dev_priv->sb_lock);
8180
8181         clock.m1 = (mdiv >> DPIO_M1DIV_SHIFT) & 7;
8182         clock.m2 = mdiv & DPIO_M2DIV_MASK;
8183         clock.n = (mdiv >> DPIO_N_SHIFT) & 0xf;
8184         clock.p1 = (mdiv >> DPIO_P1_SHIFT) & 7;
8185         clock.p2 = (mdiv >> DPIO_P2_SHIFT) & 0x1f;
8186
8187         pipe_config->port_clock = vlv_calc_dpll_params(refclk, &clock);
8188 }
8189
8190 static void
8191 i9xx_get_initial_plane_config(struct intel_crtc *crtc,
8192                               struct intel_initial_plane_config *plane_config)
8193 {
8194         struct drm_device *dev = crtc->base.dev;
8195         struct drm_i915_private *dev_priv = to_i915(dev);
8196         u32 val, base, offset;
8197         int pipe = crtc->pipe, plane = crtc->plane;
8198         int fourcc, pixel_format;
8199         unsigned int aligned_height;
8200         struct drm_framebuffer *fb;
8201         struct intel_framebuffer *intel_fb;
8202
8203         val = I915_READ(DSPCNTR(plane));
8204         if (!(val & DISPLAY_PLANE_ENABLE))
8205                 return;
8206
8207         intel_fb = kzalloc(sizeof(*intel_fb), GFP_KERNEL);
8208         if (!intel_fb) {
8209                 DRM_DEBUG_KMS("failed to alloc fb\n");
8210                 return;
8211         }
8212
8213         fb = &intel_fb->base;
8214
8215         if (INTEL_INFO(dev)->gen >= 4) {
8216                 if (val & DISPPLANE_TILED) {
8217                         plane_config->tiling = I915_TILING_X;
8218                         fb->modifier[0] = I915_FORMAT_MOD_X_TILED;
8219                 }
8220         }
8221
8222         pixel_format = val & DISPPLANE_PIXFORMAT_MASK;
8223         fourcc = i9xx_format_to_fourcc(pixel_format);
8224         fb->pixel_format = fourcc;
8225         fb->bits_per_pixel = drm_format_plane_cpp(fourcc, 0) * 8;
8226
8227         if (INTEL_INFO(dev)->gen >= 4) {
8228                 if (plane_config->tiling)
8229                         offset = I915_READ(DSPTILEOFF(plane));
8230                 else
8231                         offset = I915_READ(DSPLINOFF(plane));
8232                 base = I915_READ(DSPSURF(plane)) & 0xfffff000;
8233         } else {
8234                 base = I915_READ(DSPADDR(plane));
8235         }
8236         plane_config->base = base;
8237
8238         val = I915_READ(PIPESRC(pipe));
8239         fb->width = ((val >> 16) & 0xfff) + 1;
8240         fb->height = ((val >> 0) & 0xfff) + 1;
8241
8242         val = I915_READ(DSPSTRIDE(pipe));
8243         fb->pitches[0] = val & 0xffffffc0;
8244
8245         aligned_height = intel_fb_align_height(dev, fb->height,
8246                                                fb->pixel_format,
8247                                                fb->modifier[0]);
8248
8249         plane_config->size = fb->pitches[0] * aligned_height;
8250
8251         DRM_DEBUG_KMS("pipe/plane %c/%d with fb: size=%dx%d@%d, offset=%x, pitch %d, size 0x%x\n",
8252                       pipe_name(pipe), plane, fb->width, fb->height,
8253                       fb->bits_per_pixel, base, fb->pitches[0],
8254                       plane_config->size);
8255
8256         plane_config->fb = intel_fb;
8257 }
8258
8259 static void chv_crtc_clock_get(struct intel_crtc *crtc,
8260                                struct intel_crtc_state *pipe_config)
8261 {
8262         struct drm_device *dev = crtc->base.dev;
8263         struct drm_i915_private *dev_priv = to_i915(dev);
8264         int pipe = pipe_config->cpu_transcoder;
8265         enum dpio_channel port = vlv_pipe_to_channel(pipe);
8266         struct dpll clock;
8267         u32 cmn_dw13, pll_dw0, pll_dw1, pll_dw2, pll_dw3;
8268         int refclk = 100000;
8269
8270         /* In case of DSI, DPLL will not be used */
8271         if ((pipe_config->dpll_hw_state.dpll & DPLL_VCO_ENABLE) == 0)
8272                 return;
8273
8274         mutex_lock(&dev_priv->sb_lock);
8275         cmn_dw13 = vlv_dpio_read(dev_priv, pipe, CHV_CMN_DW13(port));
8276         pll_dw0 = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW0(port));
8277         pll_dw1 = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW1(port));
8278         pll_dw2 = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW2(port));
8279         pll_dw3 = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW3(port));
8280         mutex_unlock(&dev_priv->sb_lock);
8281
8282         clock.m1 = (pll_dw1 & 0x7) == DPIO_CHV_M1_DIV_BY_2 ? 2 : 0;
8283         clock.m2 = (pll_dw0 & 0xff) << 22;
8284         if (pll_dw3 & DPIO_CHV_FRAC_DIV_EN)
8285                 clock.m2 |= pll_dw2 & 0x3fffff;
8286         clock.n = (pll_dw1 >> DPIO_CHV_N_DIV_SHIFT) & 0xf;
8287         clock.p1 = (cmn_dw13 >> DPIO_CHV_P1_DIV_SHIFT) & 0x7;
8288         clock.p2 = (cmn_dw13 >> DPIO_CHV_P2_DIV_SHIFT) & 0x1f;
8289
8290         pipe_config->port_clock = chv_calc_dpll_params(refclk, &clock);
8291 }
8292
8293 static bool i9xx_get_pipe_config(struct intel_crtc *crtc,
8294                                  struct intel_crtc_state *pipe_config)
8295 {
8296         struct drm_device *dev = crtc->base.dev;
8297         struct drm_i915_private *dev_priv = to_i915(dev);
8298         enum intel_display_power_domain power_domain;
8299         uint32_t tmp;
8300         bool ret;
8301
8302         power_domain = POWER_DOMAIN_PIPE(crtc->pipe);
8303         if (!intel_display_power_get_if_enabled(dev_priv, power_domain))
8304                 return false;
8305
8306         pipe_config->cpu_transcoder = (enum transcoder) crtc->pipe;
8307         pipe_config->shared_dpll = NULL;
8308
8309         ret = false;
8310
8311         tmp = I915_READ(PIPECONF(crtc->pipe));
8312         if (!(tmp & PIPECONF_ENABLE))
8313                 goto out;
8314
8315         if (IS_G4X(dev) || IS_VALLEYVIEW(dev) || IS_CHERRYVIEW(dev)) {
8316                 switch (tmp & PIPECONF_BPC_MASK) {
8317                 case PIPECONF_6BPC:
8318                         pipe_config->pipe_bpp = 18;
8319                         break;
8320                 case PIPECONF_8BPC:
8321                         pipe_config->pipe_bpp = 24;
8322                         break;
8323                 case PIPECONF_10BPC:
8324                         pipe_config->pipe_bpp = 30;
8325                         break;
8326                 default:
8327                         break;
8328                 }
8329         }
8330
8331         if ((IS_VALLEYVIEW(dev) || IS_CHERRYVIEW(dev)) &&
8332             (tmp & PIPECONF_COLOR_RANGE_SELECT))
8333                 pipe_config->limited_color_range = true;
8334
8335         if (INTEL_INFO(dev)->gen < 4)
8336                 pipe_config->double_wide = tmp & PIPECONF_DOUBLE_WIDE;
8337
8338         intel_get_pipe_timings(crtc, pipe_config);
8339         intel_get_pipe_src_size(crtc, pipe_config);
8340
8341         i9xx_get_pfit_config(crtc, pipe_config);
8342
8343         if (INTEL_INFO(dev)->gen >= 4) {
8344                 /* No way to read it out on pipes B and C */
8345                 if (IS_CHERRYVIEW(dev) && crtc->pipe != PIPE_A)
8346                         tmp = dev_priv->chv_dpll_md[crtc->pipe];
8347                 else
8348                         tmp = I915_READ(DPLL_MD(crtc->pipe));
8349                 pipe_config->pixel_multiplier =
8350                         ((tmp & DPLL_MD_UDI_MULTIPLIER_MASK)
8351                          >> DPLL_MD_UDI_MULTIPLIER_SHIFT) + 1;
8352                 pipe_config->dpll_hw_state.dpll_md = tmp;
8353         } else if (IS_I945G(dev) || IS_I945GM(dev) || IS_G33(dev)) {
8354                 tmp = I915_READ(DPLL(crtc->pipe));
8355                 pipe_config->pixel_multiplier =
8356                         ((tmp & SDVO_MULTIPLIER_MASK)
8357                          >> SDVO_MULTIPLIER_SHIFT_HIRES) + 1;
8358         } else {
8359                 /* Note that on i915G/GM the pixel multiplier is in the sdvo
8360                  * port and will be fixed up in the encoder->get_config
8361                  * function. */
8362                 pipe_config->pixel_multiplier = 1;
8363         }
8364         pipe_config->dpll_hw_state.dpll = I915_READ(DPLL(crtc->pipe));
8365         if (!IS_VALLEYVIEW(dev) && !IS_CHERRYVIEW(dev)) {
8366                 /*
8367                  * DPLL_DVO_2X_MODE must be enabled for both DPLLs
8368                  * on 830. Filter it out here so that we don't
8369                  * report errors due to that.
8370                  */
8371                 if (IS_I830(dev))
8372                         pipe_config->dpll_hw_state.dpll &= ~DPLL_DVO_2X_MODE;
8373
8374                 pipe_config->dpll_hw_state.fp0 = I915_READ(FP0(crtc->pipe));
8375                 pipe_config->dpll_hw_state.fp1 = I915_READ(FP1(crtc->pipe));
8376         } else {
8377                 /* Mask out read-only status bits. */
8378                 pipe_config->dpll_hw_state.dpll &= ~(DPLL_LOCK_VLV |
8379                                                      DPLL_PORTC_READY_MASK |
8380                                                      DPLL_PORTB_READY_MASK);
8381         }
8382
8383         if (IS_CHERRYVIEW(dev))
8384                 chv_crtc_clock_get(crtc, pipe_config);
8385         else if (IS_VALLEYVIEW(dev))
8386                 vlv_crtc_clock_get(crtc, pipe_config);
8387         else
8388                 i9xx_crtc_clock_get(crtc, pipe_config);
8389
8390         /*
8391          * Normally the dotclock is filled in by the encoder .get_config()
8392          * but in case the pipe is enabled w/o any ports we need a sane
8393          * default.
8394          */
8395         pipe_config->base.adjusted_mode.crtc_clock =
8396                 pipe_config->port_clock / pipe_config->pixel_multiplier;
8397
8398         ret = true;
8399
8400 out:
8401         intel_display_power_put(dev_priv, power_domain);
8402
8403         return ret;
8404 }
8405
8406 static void ironlake_init_pch_refclk(struct drm_device *dev)
8407 {
8408         struct drm_i915_private *dev_priv = to_i915(dev);
8409         struct intel_encoder *encoder;
8410         int i;
8411         u32 val, final;
8412         bool has_lvds = false;
8413         bool has_cpu_edp = false;
8414         bool has_panel = false;
8415         bool has_ck505 = false;
8416         bool can_ssc = false;
8417         bool using_ssc_source = false;
8418
8419         /* We need to take the global config into account */
8420         for_each_intel_encoder(dev, encoder) {
8421                 switch (encoder->type) {
8422                 case INTEL_OUTPUT_LVDS:
8423                         has_panel = true;
8424                         has_lvds = true;
8425                         break;
8426                 case INTEL_OUTPUT_EDP:
8427                         has_panel = true;
8428                         if (enc_to_dig_port(&encoder->base)->port == PORT_A)
8429                                 has_cpu_edp = true;
8430                         break;
8431                 default:
8432                         break;
8433                 }
8434         }
8435
8436         if (HAS_PCH_IBX(dev)) {
8437                 has_ck505 = dev_priv->vbt.display_clock_mode;
8438                 can_ssc = has_ck505;
8439         } else {
8440                 has_ck505 = false;
8441                 can_ssc = true;
8442         }
8443
8444         /* Check if any DPLLs are using the SSC source */
8445         for (i = 0; i < dev_priv->num_shared_dpll; i++) {
8446                 u32 temp = I915_READ(PCH_DPLL(i));
8447
8448                 if (!(temp & DPLL_VCO_ENABLE))
8449                         continue;
8450
8451                 if ((temp & PLL_REF_INPUT_MASK) ==
8452                     PLLB_REF_INPUT_SPREADSPECTRUMIN) {
8453                         using_ssc_source = true;
8454                         break;
8455                 }
8456         }
8457
8458         DRM_DEBUG_KMS("has_panel %d has_lvds %d has_ck505 %d using_ssc_source %d\n",
8459                       has_panel, has_lvds, has_ck505, using_ssc_source);
8460
8461         /* Ironlake: try to setup display ref clock before DPLL
8462          * enabling. This is only under driver's control after
8463          * PCH B stepping, previous chipset stepping should be
8464          * ignoring this setting.
8465          */
8466         val = I915_READ(PCH_DREF_CONTROL);
8467
8468         /* As we must carefully and slowly disable/enable each source in turn,
8469          * compute the final state we want first and check if we need to
8470          * make any changes at all.
8471          */
8472         final = val;
8473         final &= ~DREF_NONSPREAD_SOURCE_MASK;
8474         if (has_ck505)
8475                 final |= DREF_NONSPREAD_CK505_ENABLE;
8476         else
8477                 final |= DREF_NONSPREAD_SOURCE_ENABLE;
8478
8479         final &= ~DREF_SSC_SOURCE_MASK;
8480         final &= ~DREF_CPU_SOURCE_OUTPUT_MASK;
8481         final &= ~DREF_SSC1_ENABLE;
8482
8483         if (has_panel) {
8484                 final |= DREF_SSC_SOURCE_ENABLE;
8485
8486                 if (intel_panel_use_ssc(dev_priv) && can_ssc)
8487                         final |= DREF_SSC1_ENABLE;
8488
8489                 if (has_cpu_edp) {
8490                         if (intel_panel_use_ssc(dev_priv) && can_ssc)
8491                                 final |= DREF_CPU_SOURCE_OUTPUT_DOWNSPREAD;
8492                         else
8493                                 final |= DREF_CPU_SOURCE_OUTPUT_NONSPREAD;
8494                 } else
8495                         final |= DREF_CPU_SOURCE_OUTPUT_DISABLE;
8496         } else if (using_ssc_source) {
8497                 final |= DREF_SSC_SOURCE_ENABLE;
8498                 final |= DREF_SSC1_ENABLE;
8499         }
8500
8501         if (final == val)
8502                 return;
8503
8504         /* Always enable nonspread source */
8505         val &= ~DREF_NONSPREAD_SOURCE_MASK;
8506
8507         if (has_ck505)
8508                 val |= DREF_NONSPREAD_CK505_ENABLE;
8509         else
8510                 val |= DREF_NONSPREAD_SOURCE_ENABLE;
8511
8512         if (has_panel) {
8513                 val &= ~DREF_SSC_SOURCE_MASK;
8514                 val |= DREF_SSC_SOURCE_ENABLE;
8515
8516                 /* SSC must be turned on before enabling the CPU output  */
8517                 if (intel_panel_use_ssc(dev_priv) && can_ssc) {
8518                         DRM_DEBUG_KMS("Using SSC on panel\n");
8519                         val |= DREF_SSC1_ENABLE;
8520                 } else
8521                         val &= ~DREF_SSC1_ENABLE;
8522
8523                 /* Get SSC going before enabling the outputs */
8524                 I915_WRITE(PCH_DREF_CONTROL, val);
8525                 POSTING_READ(PCH_DREF_CONTROL);
8526                 udelay(200);
8527
8528                 val &= ~DREF_CPU_SOURCE_OUTPUT_MASK;
8529
8530                 /* Enable CPU source on CPU attached eDP */
8531                 if (has_cpu_edp) {
8532                         if (intel_panel_use_ssc(dev_priv) && can_ssc) {
8533                                 DRM_DEBUG_KMS("Using SSC on eDP\n");
8534                                 val |= DREF_CPU_SOURCE_OUTPUT_DOWNSPREAD;
8535                         } else
8536                                 val |= DREF_CPU_SOURCE_OUTPUT_NONSPREAD;
8537                 } else
8538                         val |= DREF_CPU_SOURCE_OUTPUT_DISABLE;
8539
8540                 I915_WRITE(PCH_DREF_CONTROL, val);
8541                 POSTING_READ(PCH_DREF_CONTROL);
8542                 udelay(200);
8543         } else {
8544                 DRM_DEBUG_KMS("Disabling CPU source output\n");
8545
8546                 val &= ~DREF_CPU_SOURCE_OUTPUT_MASK;
8547
8548                 /* Turn off CPU output */
8549                 val |= DREF_CPU_SOURCE_OUTPUT_DISABLE;
8550
8551                 I915_WRITE(PCH_DREF_CONTROL, val);
8552                 POSTING_READ(PCH_DREF_CONTROL);
8553                 udelay(200);
8554
8555                 if (!using_ssc_source) {
8556                         DRM_DEBUG_KMS("Disabling SSC source\n");
8557
8558                         /* Turn off the SSC source */
8559                         val &= ~DREF_SSC_SOURCE_MASK;
8560                         val |= DREF_SSC_SOURCE_DISABLE;
8561
8562                         /* Turn off SSC1 */
8563                         val &= ~DREF_SSC1_ENABLE;
8564
8565                         I915_WRITE(PCH_DREF_CONTROL, val);
8566                         POSTING_READ(PCH_DREF_CONTROL);
8567                         udelay(200);
8568                 }
8569         }
8570
8571         BUG_ON(val != final);
8572 }
8573
8574 static void lpt_reset_fdi_mphy(struct drm_i915_private *dev_priv)
8575 {
8576         uint32_t tmp;
8577
8578         tmp = I915_READ(SOUTH_CHICKEN2);
8579         tmp |= FDI_MPHY_IOSFSB_RESET_CTL;
8580         I915_WRITE(SOUTH_CHICKEN2, tmp);
8581
8582         if (wait_for_us(I915_READ(SOUTH_CHICKEN2) &
8583                         FDI_MPHY_IOSFSB_RESET_STATUS, 100))
8584                 DRM_ERROR("FDI mPHY reset assert timeout\n");
8585
8586         tmp = I915_READ(SOUTH_CHICKEN2);
8587         tmp &= ~FDI_MPHY_IOSFSB_RESET_CTL;
8588         I915_WRITE(SOUTH_CHICKEN2, tmp);
8589
8590         if (wait_for_us((I915_READ(SOUTH_CHICKEN2) &
8591                          FDI_MPHY_IOSFSB_RESET_STATUS) == 0, 100))
8592                 DRM_ERROR("FDI mPHY reset de-assert timeout\n");
8593 }
8594
8595 /* WaMPhyProgramming:hsw */
8596 static void lpt_program_fdi_mphy(struct drm_i915_private *dev_priv)
8597 {
8598         uint32_t tmp;
8599
8600         tmp = intel_sbi_read(dev_priv, 0x8008, SBI_MPHY);
8601         tmp &= ~(0xFF << 24);
8602         tmp |= (0x12 << 24);
8603         intel_sbi_write(dev_priv, 0x8008, tmp, SBI_MPHY);
8604
8605         tmp = intel_sbi_read(dev_priv, 0x2008, SBI_MPHY);
8606         tmp |= (1 << 11);
8607         intel_sbi_write(dev_priv, 0x2008, tmp, SBI_MPHY);
8608
8609         tmp = intel_sbi_read(dev_priv, 0x2108, SBI_MPHY);
8610         tmp |= (1 << 11);
8611         intel_sbi_write(dev_priv, 0x2108, tmp, SBI_MPHY);
8612
8613         tmp = intel_sbi_read(dev_priv, 0x206C, SBI_MPHY);
8614         tmp |= (1 << 24) | (1 << 21) | (1 << 18);
8615         intel_sbi_write(dev_priv, 0x206C, tmp, SBI_MPHY);
8616
8617         tmp = intel_sbi_read(dev_priv, 0x216C, SBI_MPHY);
8618         tmp |= (1 << 24) | (1 << 21) | (1 << 18);
8619         intel_sbi_write(dev_priv, 0x216C, tmp, SBI_MPHY);
8620
8621         tmp = intel_sbi_read(dev_priv, 0x2080, SBI_MPHY);
8622         tmp &= ~(7 << 13);
8623         tmp |= (5 << 13);
8624         intel_sbi_write(dev_priv, 0x2080, tmp, SBI_MPHY);
8625
8626         tmp = intel_sbi_read(dev_priv, 0x2180, SBI_MPHY);
8627         tmp &= ~(7 << 13);
8628         tmp |= (5 << 13);
8629         intel_sbi_write(dev_priv, 0x2180, tmp, SBI_MPHY);
8630
8631         tmp = intel_sbi_read(dev_priv, 0x208C, SBI_MPHY);
8632         tmp &= ~0xFF;
8633         tmp |= 0x1C;
8634         intel_sbi_write(dev_priv, 0x208C, tmp, SBI_MPHY);
8635
8636         tmp = intel_sbi_read(dev_priv, 0x218C, SBI_MPHY);
8637         tmp &= ~0xFF;
8638         tmp |= 0x1C;
8639         intel_sbi_write(dev_priv, 0x218C, tmp, SBI_MPHY);
8640
8641         tmp = intel_sbi_read(dev_priv, 0x2098, SBI_MPHY);
8642         tmp &= ~(0xFF << 16);
8643         tmp |= (0x1C << 16);
8644         intel_sbi_write(dev_priv, 0x2098, tmp, SBI_MPHY);
8645
8646         tmp = intel_sbi_read(dev_priv, 0x2198, SBI_MPHY);
8647         tmp &= ~(0xFF << 16);
8648         tmp |= (0x1C << 16);
8649         intel_sbi_write(dev_priv, 0x2198, tmp, SBI_MPHY);
8650
8651         tmp = intel_sbi_read(dev_priv, 0x20C4, SBI_MPHY);
8652         tmp |= (1 << 27);
8653         intel_sbi_write(dev_priv, 0x20C4, tmp, SBI_MPHY);
8654
8655         tmp = intel_sbi_read(dev_priv, 0x21C4, SBI_MPHY);
8656         tmp |= (1 << 27);
8657         intel_sbi_write(dev_priv, 0x21C4, tmp, SBI_MPHY);
8658
8659         tmp = intel_sbi_read(dev_priv, 0x20EC, SBI_MPHY);
8660         tmp &= ~(0xF << 28);
8661         tmp |= (4 << 28);
8662         intel_sbi_write(dev_priv, 0x20EC, tmp, SBI_MPHY);
8663
8664         tmp = intel_sbi_read(dev_priv, 0x21EC, SBI_MPHY);
8665         tmp &= ~(0xF << 28);
8666         tmp |= (4 << 28);
8667         intel_sbi_write(dev_priv, 0x21EC, tmp, SBI_MPHY);
8668 }
8669
8670 /* Implements 3 different sequences from BSpec chapter "Display iCLK
8671  * Programming" based on the parameters passed:
8672  * - Sequence to enable CLKOUT_DP
8673  * - Sequence to enable CLKOUT_DP without spread
8674  * - Sequence to enable CLKOUT_DP for FDI usage and configure PCH FDI I/O
8675  */
8676 static void lpt_enable_clkout_dp(struct drm_device *dev, bool with_spread,
8677                                  bool with_fdi)
8678 {
8679         struct drm_i915_private *dev_priv = to_i915(dev);
8680         uint32_t reg, tmp;
8681
8682         if (WARN(with_fdi && !with_spread, "FDI requires downspread\n"))
8683                 with_spread = true;
8684         if (WARN(HAS_PCH_LPT_LP(dev) && with_fdi, "LP PCH doesn't have FDI\n"))
8685                 with_fdi = false;
8686
8687         mutex_lock(&dev_priv->sb_lock);
8688
8689         tmp = intel_sbi_read(dev_priv, SBI_SSCCTL, SBI_ICLK);
8690         tmp &= ~SBI_SSCCTL_DISABLE;
8691         tmp |= SBI_SSCCTL_PATHALT;
8692         intel_sbi_write(dev_priv, SBI_SSCCTL, tmp, SBI_ICLK);
8693
8694         udelay(24);
8695
8696         if (with_spread) {
8697                 tmp = intel_sbi_read(dev_priv, SBI_SSCCTL, SBI_ICLK);
8698                 tmp &= ~SBI_SSCCTL_PATHALT;
8699                 intel_sbi_write(dev_priv, SBI_SSCCTL, tmp, SBI_ICLK);
8700
8701                 if (with_fdi) {
8702                         lpt_reset_fdi_mphy(dev_priv);
8703                         lpt_program_fdi_mphy(dev_priv);
8704                 }
8705         }
8706
8707         reg = HAS_PCH_LPT_LP(dev) ? SBI_GEN0 : SBI_DBUFF0;
8708         tmp = intel_sbi_read(dev_priv, reg, SBI_ICLK);
8709         tmp |= SBI_GEN0_CFG_BUFFENABLE_DISABLE;
8710         intel_sbi_write(dev_priv, reg, tmp, SBI_ICLK);
8711
8712         mutex_unlock(&dev_priv->sb_lock);
8713 }
8714
8715 /* Sequence to disable CLKOUT_DP */
8716 static void lpt_disable_clkout_dp(struct drm_device *dev)
8717 {
8718         struct drm_i915_private *dev_priv = to_i915(dev);
8719         uint32_t reg, tmp;
8720
8721         mutex_lock(&dev_priv->sb_lock);
8722
8723         reg = HAS_PCH_LPT_LP(dev) ? SBI_GEN0 : SBI_DBUFF0;
8724         tmp = intel_sbi_read(dev_priv, reg, SBI_ICLK);
8725         tmp &= ~SBI_GEN0_CFG_BUFFENABLE_DISABLE;
8726         intel_sbi_write(dev_priv, reg, tmp, SBI_ICLK);
8727
8728         tmp = intel_sbi_read(dev_priv, SBI_SSCCTL, SBI_ICLK);
8729         if (!(tmp & SBI_SSCCTL_DISABLE)) {
8730                 if (!(tmp & SBI_SSCCTL_PATHALT)) {
8731                         tmp |= SBI_SSCCTL_PATHALT;
8732                         intel_sbi_write(dev_priv, SBI_SSCCTL, tmp, SBI_ICLK);
8733                         udelay(32);
8734                 }
8735                 tmp |= SBI_SSCCTL_DISABLE;
8736                 intel_sbi_write(dev_priv, SBI_SSCCTL, tmp, SBI_ICLK);
8737         }
8738
8739         mutex_unlock(&dev_priv->sb_lock);
8740 }
8741
8742 #define BEND_IDX(steps) ((50 + (steps)) / 5)
8743
8744 static const uint16_t sscdivintphase[] = {
8745         [BEND_IDX( 50)] = 0x3B23,
8746         [BEND_IDX( 45)] = 0x3B23,
8747         [BEND_IDX( 40)] = 0x3C23,
8748         [BEND_IDX( 35)] = 0x3C23,
8749         [BEND_IDX( 30)] = 0x3D23,
8750         [BEND_IDX( 25)] = 0x3D23,
8751         [BEND_IDX( 20)] = 0x3E23,
8752         [BEND_IDX( 15)] = 0x3E23,
8753         [BEND_IDX( 10)] = 0x3F23,
8754         [BEND_IDX(  5)] = 0x3F23,
8755         [BEND_IDX(  0)] = 0x0025,
8756         [BEND_IDX( -5)] = 0x0025,
8757         [BEND_IDX(-10)] = 0x0125,
8758         [BEND_IDX(-15)] = 0x0125,
8759         [BEND_IDX(-20)] = 0x0225,
8760         [BEND_IDX(-25)] = 0x0225,
8761         [BEND_IDX(-30)] = 0x0325,
8762         [BEND_IDX(-35)] = 0x0325,
8763         [BEND_IDX(-40)] = 0x0425,
8764         [BEND_IDX(-45)] = 0x0425,
8765         [BEND_IDX(-50)] = 0x0525,
8766 };
8767
8768 /*
8769  * Bend CLKOUT_DP
8770  * steps -50 to 50 inclusive, in steps of 5
8771  * < 0 slow down the clock, > 0 speed up the clock, 0 == no bend (135MHz)
8772  * change in clock period = -(steps / 10) * 5.787 ps
8773  */
8774 static void lpt_bend_clkout_dp(struct drm_i915_private *dev_priv, int steps)
8775 {
8776         uint32_t tmp;
8777         int idx = BEND_IDX(steps);
8778
8779         if (WARN_ON(steps % 5 != 0))
8780                 return;
8781
8782         if (WARN_ON(idx >= ARRAY_SIZE(sscdivintphase)))
8783                 return;
8784
8785         mutex_lock(&dev_priv->sb_lock);
8786
8787         if (steps % 10 != 0)
8788                 tmp = 0xAAAAAAAB;
8789         else
8790                 tmp = 0x00000000;
8791         intel_sbi_write(dev_priv, SBI_SSCDITHPHASE, tmp, SBI_ICLK);
8792
8793         tmp = intel_sbi_read(dev_priv, SBI_SSCDIVINTPHASE, SBI_ICLK);
8794         tmp &= 0xffff0000;
8795         tmp |= sscdivintphase[idx];
8796         intel_sbi_write(dev_priv, SBI_SSCDIVINTPHASE, tmp, SBI_ICLK);
8797
8798         mutex_unlock(&dev_priv->sb_lock);
8799 }
8800
8801 #undef BEND_IDX
8802
8803 static void lpt_init_pch_refclk(struct drm_device *dev)
8804 {
8805         struct intel_encoder *encoder;
8806         bool has_vga = false;
8807
8808         for_each_intel_encoder(dev, encoder) {
8809                 switch (encoder->type) {
8810                 case INTEL_OUTPUT_ANALOG:
8811                         has_vga = true;
8812                         break;
8813                 default:
8814                         break;
8815                 }
8816         }
8817
8818         if (has_vga) {
8819                 lpt_bend_clkout_dp(to_i915(dev), 0);
8820                 lpt_enable_clkout_dp(dev, true, true);
8821         } else {
8822                 lpt_disable_clkout_dp(dev);
8823         }
8824 }
8825
8826 /*
8827  * Initialize reference clocks when the driver loads
8828  */
8829 void intel_init_pch_refclk(struct drm_device *dev)
8830 {
8831         if (HAS_PCH_IBX(dev) || HAS_PCH_CPT(dev))
8832                 ironlake_init_pch_refclk(dev);
8833         else if (HAS_PCH_LPT(dev))
8834                 lpt_init_pch_refclk(dev);
8835 }
8836
8837 static void ironlake_set_pipeconf(struct drm_crtc *crtc)
8838 {
8839         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
8840         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
8841         int pipe = intel_crtc->pipe;
8842         uint32_t val;
8843
8844         val = 0;
8845
8846         switch (intel_crtc->config->pipe_bpp) {
8847         case 18:
8848                 val |= PIPECONF_6BPC;
8849                 break;
8850         case 24:
8851                 val |= PIPECONF_8BPC;
8852                 break;
8853         case 30:
8854                 val |= PIPECONF_10BPC;
8855                 break;
8856         case 36:
8857                 val |= PIPECONF_12BPC;
8858                 break;
8859         default:
8860                 /* Case prevented by intel_choose_pipe_bpp_dither. */
8861                 BUG();
8862         }
8863
8864         if (intel_crtc->config->dither)
8865                 val |= (PIPECONF_DITHER_EN | PIPECONF_DITHER_TYPE_SP);
8866
8867         if (intel_crtc->config->base.adjusted_mode.flags & DRM_MODE_FLAG_INTERLACE)
8868                 val |= PIPECONF_INTERLACED_ILK;
8869         else
8870                 val |= PIPECONF_PROGRESSIVE;
8871
8872         if (intel_crtc->config->limited_color_range)
8873                 val |= PIPECONF_COLOR_RANGE_SELECT;
8874
8875         I915_WRITE(PIPECONF(pipe), val);
8876         POSTING_READ(PIPECONF(pipe));
8877 }
8878
8879 static void haswell_set_pipeconf(struct drm_crtc *crtc)
8880 {
8881         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
8882         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
8883         enum transcoder cpu_transcoder = intel_crtc->config->cpu_transcoder;
8884         u32 val = 0;
8885
8886         if (IS_HASWELL(dev_priv) && intel_crtc->config->dither)
8887                 val |= (PIPECONF_DITHER_EN | PIPECONF_DITHER_TYPE_SP);
8888
8889         if (intel_crtc->config->base.adjusted_mode.flags & DRM_MODE_FLAG_INTERLACE)
8890                 val |= PIPECONF_INTERLACED_ILK;
8891         else
8892                 val |= PIPECONF_PROGRESSIVE;
8893
8894         I915_WRITE(PIPECONF(cpu_transcoder), val);
8895         POSTING_READ(PIPECONF(cpu_transcoder));
8896 }
8897
8898 static void haswell_set_pipemisc(struct drm_crtc *crtc)
8899 {
8900         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
8901         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
8902
8903         if (IS_BROADWELL(dev_priv) || INTEL_INFO(dev_priv)->gen >= 9) {
8904                 u32 val = 0;
8905
8906                 switch (intel_crtc->config->pipe_bpp) {
8907                 case 18:
8908                         val |= PIPEMISC_DITHER_6_BPC;
8909                         break;
8910                 case 24:
8911                         val |= PIPEMISC_DITHER_8_BPC;
8912                         break;
8913                 case 30:
8914                         val |= PIPEMISC_DITHER_10_BPC;
8915                         break;
8916                 case 36:
8917                         val |= PIPEMISC_DITHER_12_BPC;
8918                         break;
8919                 default:
8920                         /* Case prevented by pipe_config_set_bpp. */
8921                         BUG();
8922                 }
8923
8924                 if (intel_crtc->config->dither)
8925                         val |= PIPEMISC_DITHER_ENABLE | PIPEMISC_DITHER_TYPE_SP;
8926
8927                 I915_WRITE(PIPEMISC(intel_crtc->pipe), val);
8928         }
8929 }
8930
8931 int ironlake_get_lanes_required(int target_clock, int link_bw, int bpp)
8932 {
8933         /*
8934          * Account for spread spectrum to avoid
8935          * oversubscribing the link. Max center spread
8936          * is 2.5%; use 5% for safety's sake.
8937          */
8938         u32 bps = target_clock * bpp * 21 / 20;
8939         return DIV_ROUND_UP(bps, link_bw * 8);
8940 }
8941
8942 static bool ironlake_needs_fb_cb_tune(struct dpll *dpll, int factor)
8943 {
8944         return i9xx_dpll_compute_m(dpll) < factor * dpll->n;
8945 }
8946
8947 static void ironlake_compute_dpll(struct intel_crtc *intel_crtc,
8948                                   struct intel_crtc_state *crtc_state,
8949                                   struct dpll *reduced_clock)
8950 {
8951         struct drm_crtc *crtc = &intel_crtc->base;
8952         struct drm_device *dev = crtc->dev;
8953         struct drm_i915_private *dev_priv = to_i915(dev);
8954         u32 dpll, fp, fp2;
8955         int factor;
8956
8957         /* Enable autotuning of the PLL clock (if permissible) */
8958         factor = 21;
8959         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS)) {
8960                 if ((intel_panel_use_ssc(dev_priv) &&
8961                      dev_priv->vbt.lvds_ssc_freq == 100000) ||
8962                     (HAS_PCH_IBX(dev) && intel_is_dual_link_lvds(dev)))
8963                         factor = 25;
8964         } else if (crtc_state->sdvo_tv_clock)
8965                 factor = 20;
8966
8967         fp = i9xx_dpll_compute_fp(&crtc_state->dpll);
8968
8969         if (ironlake_needs_fb_cb_tune(&crtc_state->dpll, factor))
8970                 fp |= FP_CB_TUNE;
8971
8972         if (reduced_clock) {
8973                 fp2 = i9xx_dpll_compute_fp(reduced_clock);
8974
8975                 if (reduced_clock->m < factor * reduced_clock->n)
8976                         fp2 |= FP_CB_TUNE;
8977         } else {
8978                 fp2 = fp;
8979         }
8980
8981         dpll = 0;
8982
8983         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS))
8984                 dpll |= DPLLB_MODE_LVDS;
8985         else
8986                 dpll |= DPLLB_MODE_DAC_SERIAL;
8987
8988         dpll |= (crtc_state->pixel_multiplier - 1)
8989                 << PLL_REF_SDVO_HDMI_MULTIPLIER_SHIFT;
8990
8991         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_SDVO) ||
8992             intel_crtc_has_type(crtc_state, INTEL_OUTPUT_HDMI))
8993                 dpll |= DPLL_SDVO_HIGH_SPEED;
8994
8995         if (intel_crtc_has_dp_encoder(crtc_state))
8996                 dpll |= DPLL_SDVO_HIGH_SPEED;
8997
8998         /* compute bitmask from p1 value */
8999         dpll |= (1 << (crtc_state->dpll.p1 - 1)) << DPLL_FPA01_P1_POST_DIV_SHIFT;
9000         /* also FPA1 */
9001         dpll |= (1 << (crtc_state->dpll.p1 - 1)) << DPLL_FPA1_P1_POST_DIV_SHIFT;
9002
9003         switch (crtc_state->dpll.p2) {
9004         case 5:
9005                 dpll |= DPLL_DAC_SERIAL_P2_CLOCK_DIV_5;
9006                 break;
9007         case 7:
9008                 dpll |= DPLLB_LVDS_P2_CLOCK_DIV_7;
9009                 break;
9010         case 10:
9011                 dpll |= DPLL_DAC_SERIAL_P2_CLOCK_DIV_10;
9012                 break;
9013         case 14:
9014                 dpll |= DPLLB_LVDS_P2_CLOCK_DIV_14;
9015                 break;
9016         }
9017
9018         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS) &&
9019             intel_panel_use_ssc(dev_priv))
9020                 dpll |= PLLB_REF_INPUT_SPREADSPECTRUMIN;
9021         else
9022                 dpll |= PLL_REF_INPUT_DREFCLK;
9023
9024         dpll |= DPLL_VCO_ENABLE;
9025
9026         crtc_state->dpll_hw_state.dpll = dpll;
9027         crtc_state->dpll_hw_state.fp0 = fp;
9028         crtc_state->dpll_hw_state.fp1 = fp2;
9029 }
9030
9031 static int ironlake_crtc_compute_clock(struct intel_crtc *crtc,
9032                                        struct intel_crtc_state *crtc_state)
9033 {
9034         struct drm_device *dev = crtc->base.dev;
9035         struct drm_i915_private *dev_priv = to_i915(dev);
9036         struct dpll reduced_clock;
9037         bool has_reduced_clock = false;
9038         struct intel_shared_dpll *pll;
9039         const struct intel_limit *limit;
9040         int refclk = 120000;
9041
9042         memset(&crtc_state->dpll_hw_state, 0,
9043                sizeof(crtc_state->dpll_hw_state));
9044
9045         crtc->lowfreq_avail = false;
9046
9047         /* CPU eDP is the only output that doesn't need a PCH PLL of its own. */
9048         if (!crtc_state->has_pch_encoder)
9049                 return 0;
9050
9051         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS)) {
9052                 if (intel_panel_use_ssc(dev_priv)) {
9053                         DRM_DEBUG_KMS("using SSC reference clock of %d kHz\n",
9054                                       dev_priv->vbt.lvds_ssc_freq);
9055                         refclk = dev_priv->vbt.lvds_ssc_freq;
9056                 }
9057
9058                 if (intel_is_dual_link_lvds(dev)) {
9059                         if (refclk == 100000)
9060                                 limit = &intel_limits_ironlake_dual_lvds_100m;
9061                         else
9062                                 limit = &intel_limits_ironlake_dual_lvds;
9063                 } else {
9064                         if (refclk == 100000)
9065                                 limit = &intel_limits_ironlake_single_lvds_100m;
9066                         else
9067                                 limit = &intel_limits_ironlake_single_lvds;
9068                 }
9069         } else {
9070                 limit = &intel_limits_ironlake_dac;
9071         }
9072
9073         if (!crtc_state->clock_set &&
9074             !g4x_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
9075                                 refclk, NULL, &crtc_state->dpll)) {
9076                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
9077                 return -EINVAL;
9078         }
9079
9080         ironlake_compute_dpll(crtc, crtc_state,
9081                               has_reduced_clock ? &reduced_clock : NULL);
9082
9083         pll = intel_get_shared_dpll(crtc, crtc_state, NULL);
9084         if (pll == NULL) {
9085                 DRM_DEBUG_DRIVER("failed to find PLL for pipe %c\n",
9086                                  pipe_name(crtc->pipe));
9087                 return -EINVAL;
9088         }
9089
9090         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS) &&
9091             has_reduced_clock)
9092                 crtc->lowfreq_avail = true;
9093
9094         return 0;
9095 }
9096
9097 static void intel_pch_transcoder_get_m_n(struct intel_crtc *crtc,
9098                                          struct intel_link_m_n *m_n)
9099 {
9100         struct drm_device *dev = crtc->base.dev;
9101         struct drm_i915_private *dev_priv = to_i915(dev);
9102         enum pipe pipe = crtc->pipe;
9103
9104         m_n->link_m = I915_READ(PCH_TRANS_LINK_M1(pipe));
9105         m_n->link_n = I915_READ(PCH_TRANS_LINK_N1(pipe));
9106         m_n->gmch_m = I915_READ(PCH_TRANS_DATA_M1(pipe))
9107                 & ~TU_SIZE_MASK;
9108         m_n->gmch_n = I915_READ(PCH_TRANS_DATA_N1(pipe));
9109         m_n->tu = ((I915_READ(PCH_TRANS_DATA_M1(pipe))
9110                     & TU_SIZE_MASK) >> TU_SIZE_SHIFT) + 1;
9111 }
9112
9113 static void intel_cpu_transcoder_get_m_n(struct intel_crtc *crtc,
9114                                          enum transcoder transcoder,
9115                                          struct intel_link_m_n *m_n,
9116                                          struct intel_link_m_n *m2_n2)
9117 {
9118         struct drm_device *dev = crtc->base.dev;
9119         struct drm_i915_private *dev_priv = to_i915(dev);
9120         enum pipe pipe = crtc->pipe;
9121
9122         if (INTEL_INFO(dev)->gen >= 5) {
9123                 m_n->link_m = I915_READ(PIPE_LINK_M1(transcoder));
9124                 m_n->link_n = I915_READ(PIPE_LINK_N1(transcoder));
9125                 m_n->gmch_m = I915_READ(PIPE_DATA_M1(transcoder))
9126                         & ~TU_SIZE_MASK;
9127                 m_n->gmch_n = I915_READ(PIPE_DATA_N1(transcoder));
9128                 m_n->tu = ((I915_READ(PIPE_DATA_M1(transcoder))
9129                             & TU_SIZE_MASK) >> TU_SIZE_SHIFT) + 1;
9130                 /* Read M2_N2 registers only for gen < 8 (M2_N2 available for
9131                  * gen < 8) and if DRRS is supported (to make sure the
9132                  * registers are not unnecessarily read).
9133                  */
9134                 if (m2_n2 && INTEL_INFO(dev)->gen < 8 &&
9135                         crtc->config->has_drrs) {
9136                         m2_n2->link_m = I915_READ(PIPE_LINK_M2(transcoder));
9137                         m2_n2->link_n = I915_READ(PIPE_LINK_N2(transcoder));
9138                         m2_n2->gmch_m = I915_READ(PIPE_DATA_M2(transcoder))
9139                                         & ~TU_SIZE_MASK;
9140                         m2_n2->gmch_n = I915_READ(PIPE_DATA_N2(transcoder));
9141                         m2_n2->tu = ((I915_READ(PIPE_DATA_M2(transcoder))
9142                                         & TU_SIZE_MASK) >> TU_SIZE_SHIFT) + 1;
9143                 }
9144         } else {
9145                 m_n->link_m = I915_READ(PIPE_LINK_M_G4X(pipe));
9146                 m_n->link_n = I915_READ(PIPE_LINK_N_G4X(pipe));
9147                 m_n->gmch_m = I915_READ(PIPE_DATA_M_G4X(pipe))
9148                         & ~TU_SIZE_MASK;
9149                 m_n->gmch_n = I915_READ(PIPE_DATA_N_G4X(pipe));
9150                 m_n->tu = ((I915_READ(PIPE_DATA_M_G4X(pipe))
9151                             & TU_SIZE_MASK) >> TU_SIZE_SHIFT) + 1;
9152         }
9153 }
9154
9155 void intel_dp_get_m_n(struct intel_crtc *crtc,
9156                       struct intel_crtc_state *pipe_config)
9157 {
9158         if (pipe_config->has_pch_encoder)
9159                 intel_pch_transcoder_get_m_n(crtc, &pipe_config->dp_m_n);
9160         else
9161                 intel_cpu_transcoder_get_m_n(crtc, pipe_config->cpu_transcoder,
9162                                              &pipe_config->dp_m_n,
9163                                              &pipe_config->dp_m2_n2);
9164 }
9165
9166 static void ironlake_get_fdi_m_n_config(struct intel_crtc *crtc,
9167                                         struct intel_crtc_state *pipe_config)
9168 {
9169         intel_cpu_transcoder_get_m_n(crtc, pipe_config->cpu_transcoder,
9170                                      &pipe_config->fdi_m_n, NULL);
9171 }
9172
9173 static void skylake_get_pfit_config(struct intel_crtc *crtc,
9174                                     struct intel_crtc_state *pipe_config)
9175 {
9176         struct drm_device *dev = crtc->base.dev;
9177         struct drm_i915_private *dev_priv = to_i915(dev);
9178         struct intel_crtc_scaler_state *scaler_state = &pipe_config->scaler_state;
9179         uint32_t ps_ctrl = 0;
9180         int id = -1;
9181         int i;
9182
9183         /* find scaler attached to this pipe */
9184         for (i = 0; i < crtc->num_scalers; i++) {
9185                 ps_ctrl = I915_READ(SKL_PS_CTRL(crtc->pipe, i));
9186                 if (ps_ctrl & PS_SCALER_EN && !(ps_ctrl & PS_PLANE_SEL_MASK)) {
9187                         id = i;
9188                         pipe_config->pch_pfit.enabled = true;
9189                         pipe_config->pch_pfit.pos = I915_READ(SKL_PS_WIN_POS(crtc->pipe, i));
9190                         pipe_config->pch_pfit.size = I915_READ(SKL_PS_WIN_SZ(crtc->pipe, i));
9191                         break;
9192                 }
9193         }
9194
9195         scaler_state->scaler_id = id;
9196         if (id >= 0) {
9197                 scaler_state->scaler_users |= (1 << SKL_CRTC_INDEX);
9198         } else {
9199                 scaler_state->scaler_users &= ~(1 << SKL_CRTC_INDEX);
9200         }
9201 }
9202
9203 static void
9204 skylake_get_initial_plane_config(struct intel_crtc *crtc,
9205                                  struct intel_initial_plane_config *plane_config)
9206 {
9207         struct drm_device *dev = crtc->base.dev;
9208         struct drm_i915_private *dev_priv = to_i915(dev);
9209         u32 val, base, offset, stride_mult, tiling;
9210         int pipe = crtc->pipe;
9211         int fourcc, pixel_format;
9212         unsigned int aligned_height;
9213         struct drm_framebuffer *fb;
9214         struct intel_framebuffer *intel_fb;
9215
9216         intel_fb = kzalloc(sizeof(*intel_fb), GFP_KERNEL);
9217         if (!intel_fb) {
9218                 DRM_DEBUG_KMS("failed to alloc fb\n");
9219                 return;
9220         }
9221
9222         fb = &intel_fb->base;
9223
9224         val = I915_READ(PLANE_CTL(pipe, 0));
9225         if (!(val & PLANE_CTL_ENABLE))
9226                 goto error;
9227
9228         pixel_format = val & PLANE_CTL_FORMAT_MASK;
9229         fourcc = skl_format_to_fourcc(pixel_format,
9230                                       val & PLANE_CTL_ORDER_RGBX,
9231                                       val & PLANE_CTL_ALPHA_MASK);
9232         fb->pixel_format = fourcc;
9233         fb->bits_per_pixel = drm_format_plane_cpp(fourcc, 0) * 8;
9234
9235         tiling = val & PLANE_CTL_TILED_MASK;
9236         switch (tiling) {
9237         case PLANE_CTL_TILED_LINEAR:
9238                 fb->modifier[0] = DRM_FORMAT_MOD_NONE;
9239                 break;
9240         case PLANE_CTL_TILED_X:
9241                 plane_config->tiling = I915_TILING_X;
9242                 fb->modifier[0] = I915_FORMAT_MOD_X_TILED;
9243                 break;
9244         case PLANE_CTL_TILED_Y:
9245                 fb->modifier[0] = I915_FORMAT_MOD_Y_TILED;
9246                 break;
9247         case PLANE_CTL_TILED_YF:
9248                 fb->modifier[0] = I915_FORMAT_MOD_Yf_TILED;
9249                 break;
9250         default:
9251                 MISSING_CASE(tiling);
9252                 goto error;
9253         }
9254
9255         base = I915_READ(PLANE_SURF(pipe, 0)) & 0xfffff000;
9256         plane_config->base = base;
9257
9258         offset = I915_READ(PLANE_OFFSET(pipe, 0));
9259
9260         val = I915_READ(PLANE_SIZE(pipe, 0));
9261         fb->height = ((val >> 16) & 0xfff) + 1;
9262         fb->width = ((val >> 0) & 0x1fff) + 1;
9263
9264         val = I915_READ(PLANE_STRIDE(pipe, 0));
9265         stride_mult = intel_fb_stride_alignment(dev_priv, fb->modifier[0],
9266                                                 fb->pixel_format);
9267         fb->pitches[0] = (val & 0x3ff) * stride_mult;
9268
9269         aligned_height = intel_fb_align_height(dev, fb->height,
9270                                                fb->pixel_format,
9271                                                fb->modifier[0]);
9272
9273         plane_config->size = fb->pitches[0] * aligned_height;
9274
9275         DRM_DEBUG_KMS("pipe %c with fb: size=%dx%d@%d, offset=%x, pitch %d, size 0x%x\n",
9276                       pipe_name(pipe), fb->width, fb->height,
9277                       fb->bits_per_pixel, base, fb->pitches[0],
9278                       plane_config->size);
9279
9280         plane_config->fb = intel_fb;
9281         return;
9282
9283 error:
9284         kfree(fb);
9285 }
9286
9287 static void ironlake_get_pfit_config(struct intel_crtc *crtc,
9288                                      struct intel_crtc_state *pipe_config)
9289 {
9290         struct drm_device *dev = crtc->base.dev;
9291         struct drm_i915_private *dev_priv = to_i915(dev);
9292         uint32_t tmp;
9293
9294         tmp = I915_READ(PF_CTL(crtc->pipe));
9295
9296         if (tmp & PF_ENABLE) {
9297                 pipe_config->pch_pfit.enabled = true;
9298                 pipe_config->pch_pfit.pos = I915_READ(PF_WIN_POS(crtc->pipe));
9299                 pipe_config->pch_pfit.size = I915_READ(PF_WIN_SZ(crtc->pipe));
9300
9301                 /* We currently do not free assignements of panel fitters on
9302                  * ivb/hsw (since we don't use the higher upscaling modes which
9303                  * differentiates them) so just WARN about this case for now. */
9304                 if (IS_GEN7(dev)) {
9305                         WARN_ON((tmp & PF_PIPE_SEL_MASK_IVB) !=
9306                                 PF_PIPE_SEL_IVB(crtc->pipe));
9307                 }
9308         }
9309 }
9310
9311 static void
9312 ironlake_get_initial_plane_config(struct intel_crtc *crtc,
9313                                   struct intel_initial_plane_config *plane_config)
9314 {
9315         struct drm_device *dev = crtc->base.dev;
9316         struct drm_i915_private *dev_priv = to_i915(dev);
9317         u32 val, base, offset;
9318         int pipe = crtc->pipe;
9319         int fourcc, pixel_format;
9320         unsigned int aligned_height;
9321         struct drm_framebuffer *fb;
9322         struct intel_framebuffer *intel_fb;
9323
9324         val = I915_READ(DSPCNTR(pipe));
9325         if (!(val & DISPLAY_PLANE_ENABLE))
9326                 return;
9327
9328         intel_fb = kzalloc(sizeof(*intel_fb), GFP_KERNEL);
9329         if (!intel_fb) {
9330                 DRM_DEBUG_KMS("failed to alloc fb\n");
9331                 return;
9332         }
9333
9334         fb = &intel_fb->base;
9335
9336         if (INTEL_INFO(dev)->gen >= 4) {
9337                 if (val & DISPPLANE_TILED) {
9338                         plane_config->tiling = I915_TILING_X;
9339                         fb->modifier[0] = I915_FORMAT_MOD_X_TILED;
9340                 }
9341         }
9342
9343         pixel_format = val & DISPPLANE_PIXFORMAT_MASK;
9344         fourcc = i9xx_format_to_fourcc(pixel_format);
9345         fb->pixel_format = fourcc;
9346         fb->bits_per_pixel = drm_format_plane_cpp(fourcc, 0) * 8;
9347
9348         base = I915_READ(DSPSURF(pipe)) & 0xfffff000;
9349         if (IS_HASWELL(dev) || IS_BROADWELL(dev)) {
9350                 offset = I915_READ(DSPOFFSET(pipe));
9351         } else {
9352                 if (plane_config->tiling)
9353                         offset = I915_READ(DSPTILEOFF(pipe));
9354                 else
9355                         offset = I915_READ(DSPLINOFF(pipe));
9356         }
9357         plane_config->base = base;
9358
9359         val = I915_READ(PIPESRC(pipe));
9360         fb->width = ((val >> 16) & 0xfff) + 1;
9361         fb->height = ((val >> 0) & 0xfff) + 1;
9362
9363         val = I915_READ(DSPSTRIDE(pipe));
9364         fb->pitches[0] = val & 0xffffffc0;
9365
9366         aligned_height = intel_fb_align_height(dev, fb->height,
9367                                                fb->pixel_format,
9368                                                fb->modifier[0]);
9369
9370         plane_config->size = fb->pitches[0] * aligned_height;
9371
9372         DRM_DEBUG_KMS("pipe %c with fb: size=%dx%d@%d, offset=%x, pitch %d, size 0x%x\n",
9373                       pipe_name(pipe), fb->width, fb->height,
9374                       fb->bits_per_pixel, base, fb->pitches[0],
9375                       plane_config->size);
9376
9377         plane_config->fb = intel_fb;
9378 }
9379
9380 static bool ironlake_get_pipe_config(struct intel_crtc *crtc,
9381                                      struct intel_crtc_state *pipe_config)
9382 {
9383         struct drm_device *dev = crtc->base.dev;
9384         struct drm_i915_private *dev_priv = to_i915(dev);
9385         enum intel_display_power_domain power_domain;
9386         uint32_t tmp;
9387         bool ret;
9388
9389         power_domain = POWER_DOMAIN_PIPE(crtc->pipe);
9390         if (!intel_display_power_get_if_enabled(dev_priv, power_domain))
9391                 return false;
9392
9393         pipe_config->cpu_transcoder = (enum transcoder) crtc->pipe;
9394         pipe_config->shared_dpll = NULL;
9395
9396         ret = false;
9397         tmp = I915_READ(PIPECONF(crtc->pipe));
9398         if (!(tmp & PIPECONF_ENABLE))
9399                 goto out;
9400
9401         switch (tmp & PIPECONF_BPC_MASK) {
9402         case PIPECONF_6BPC:
9403                 pipe_config->pipe_bpp = 18;
9404                 break;
9405         case PIPECONF_8BPC:
9406                 pipe_config->pipe_bpp = 24;
9407                 break;
9408         case PIPECONF_10BPC:
9409                 pipe_config->pipe_bpp = 30;
9410                 break;
9411         case PIPECONF_12BPC:
9412                 pipe_config->pipe_bpp = 36;
9413                 break;
9414         default:
9415                 break;
9416         }
9417
9418         if (tmp & PIPECONF_COLOR_RANGE_SELECT)
9419                 pipe_config->limited_color_range = true;
9420
9421         if (I915_READ(PCH_TRANSCONF(crtc->pipe)) & TRANS_ENABLE) {
9422                 struct intel_shared_dpll *pll;
9423                 enum intel_dpll_id pll_id;
9424
9425                 pipe_config->has_pch_encoder = true;
9426
9427                 tmp = I915_READ(FDI_RX_CTL(crtc->pipe));
9428                 pipe_config->fdi_lanes = ((FDI_DP_PORT_WIDTH_MASK & tmp) >>
9429                                           FDI_DP_PORT_WIDTH_SHIFT) + 1;
9430
9431                 ironlake_get_fdi_m_n_config(crtc, pipe_config);
9432
9433                 if (HAS_PCH_IBX(dev_priv)) {
9434                         /*
9435                          * The pipe->pch transcoder and pch transcoder->pll
9436                          * mapping is fixed.
9437                          */
9438                         pll_id = (enum intel_dpll_id) crtc->pipe;
9439                 } else {
9440                         tmp = I915_READ(PCH_DPLL_SEL);
9441                         if (tmp & TRANS_DPLLB_SEL(crtc->pipe))
9442                                 pll_id = DPLL_ID_PCH_PLL_B;
9443                         else
9444                                 pll_id= DPLL_ID_PCH_PLL_A;
9445                 }
9446
9447                 pipe_config->shared_dpll =
9448                         intel_get_shared_dpll_by_id(dev_priv, pll_id);
9449                 pll = pipe_config->shared_dpll;
9450
9451                 WARN_ON(!pll->funcs.get_hw_state(dev_priv, pll,
9452                                                  &pipe_config->dpll_hw_state));
9453
9454                 tmp = pipe_config->dpll_hw_state.dpll;
9455                 pipe_config->pixel_multiplier =
9456                         ((tmp & PLL_REF_SDVO_HDMI_MULTIPLIER_MASK)
9457                          >> PLL_REF_SDVO_HDMI_MULTIPLIER_SHIFT) + 1;
9458
9459                 ironlake_pch_clock_get(crtc, pipe_config);
9460         } else {
9461                 pipe_config->pixel_multiplier = 1;
9462         }
9463
9464         intel_get_pipe_timings(crtc, pipe_config);
9465         intel_get_pipe_src_size(crtc, pipe_config);
9466
9467         ironlake_get_pfit_config(crtc, pipe_config);
9468
9469         ret = true;
9470
9471 out:
9472         intel_display_power_put(dev_priv, power_domain);
9473
9474         return ret;
9475 }
9476
9477 static void assert_can_disable_lcpll(struct drm_i915_private *dev_priv)
9478 {
9479         struct drm_device *dev = &dev_priv->drm;
9480         struct intel_crtc *crtc;
9481
9482         for_each_intel_crtc(dev, crtc)
9483                 I915_STATE_WARN(crtc->active, "CRTC for pipe %c enabled\n",
9484                      pipe_name(crtc->pipe));
9485
9486         I915_STATE_WARN(I915_READ(HSW_PWR_WELL_DRIVER), "Power well on\n");
9487         I915_STATE_WARN(I915_READ(SPLL_CTL) & SPLL_PLL_ENABLE, "SPLL enabled\n");
9488         I915_STATE_WARN(I915_READ(WRPLL_CTL(0)) & WRPLL_PLL_ENABLE, "WRPLL1 enabled\n");
9489         I915_STATE_WARN(I915_READ(WRPLL_CTL(1)) & WRPLL_PLL_ENABLE, "WRPLL2 enabled\n");
9490         I915_STATE_WARN(I915_READ(PCH_PP_STATUS) & PP_ON, "Panel power on\n");
9491         I915_STATE_WARN(I915_READ(BLC_PWM_CPU_CTL2) & BLM_PWM_ENABLE,
9492              "CPU PWM1 enabled\n");
9493         if (IS_HASWELL(dev))
9494                 I915_STATE_WARN(I915_READ(HSW_BLC_PWM2_CTL) & BLM_PWM_ENABLE,
9495                      "CPU PWM2 enabled\n");
9496         I915_STATE_WARN(I915_READ(BLC_PWM_PCH_CTL1) & BLM_PCH_PWM_ENABLE,
9497              "PCH PWM1 enabled\n");
9498         I915_STATE_WARN(I915_READ(UTIL_PIN_CTL) & UTIL_PIN_ENABLE,
9499              "Utility pin enabled\n");
9500         I915_STATE_WARN(I915_READ(PCH_GTC_CTL) & PCH_GTC_ENABLE, "PCH GTC enabled\n");
9501
9502         /*
9503          * In theory we can still leave IRQs enabled, as long as only the HPD
9504          * interrupts remain enabled. We used to check for that, but since it's
9505          * gen-specific and since we only disable LCPLL after we fully disable
9506          * the interrupts, the check below should be enough.
9507          */
9508         I915_STATE_WARN(intel_irqs_enabled(dev_priv), "IRQs enabled\n");
9509 }
9510
9511 static uint32_t hsw_read_dcomp(struct drm_i915_private *dev_priv)
9512 {
9513         struct drm_device *dev = &dev_priv->drm;
9514
9515         if (IS_HASWELL(dev))
9516                 return I915_READ(D_COMP_HSW);
9517         else
9518                 return I915_READ(D_COMP_BDW);
9519 }
9520
9521 static void hsw_write_dcomp(struct drm_i915_private *dev_priv, uint32_t val)
9522 {
9523         struct drm_device *dev = &dev_priv->drm;
9524
9525         if (IS_HASWELL(dev)) {
9526                 mutex_lock(&dev_priv->rps.hw_lock);
9527                 if (sandybridge_pcode_write(dev_priv, GEN6_PCODE_WRITE_D_COMP,
9528                                             val))
9529                         DRM_ERROR("Failed to write to D_COMP\n");
9530                 mutex_unlock(&dev_priv->rps.hw_lock);
9531         } else {
9532                 I915_WRITE(D_COMP_BDW, val);
9533                 POSTING_READ(D_COMP_BDW);
9534         }
9535 }
9536
9537 /*
9538  * This function implements pieces of two sequences from BSpec:
9539  * - Sequence for display software to disable LCPLL
9540  * - Sequence for display software to allow package C8+
9541  * The steps implemented here are just the steps that actually touch the LCPLL
9542  * register. Callers should take care of disabling all the display engine
9543  * functions, doing the mode unset, fixing interrupts, etc.
9544  */
9545 static void hsw_disable_lcpll(struct drm_i915_private *dev_priv,
9546                               bool switch_to_fclk, bool allow_power_down)
9547 {
9548         uint32_t val;
9549
9550         assert_can_disable_lcpll(dev_priv);
9551
9552         val = I915_READ(LCPLL_CTL);
9553
9554         if (switch_to_fclk) {
9555                 val |= LCPLL_CD_SOURCE_FCLK;
9556                 I915_WRITE(LCPLL_CTL, val);
9557
9558                 if (wait_for_us(I915_READ(LCPLL_CTL) &
9559                                 LCPLL_CD_SOURCE_FCLK_DONE, 1))
9560                         DRM_ERROR("Switching to FCLK failed\n");
9561
9562                 val = I915_READ(LCPLL_CTL);
9563         }
9564
9565         val |= LCPLL_PLL_DISABLE;
9566         I915_WRITE(LCPLL_CTL, val);
9567         POSTING_READ(LCPLL_CTL);
9568
9569         if (intel_wait_for_register(dev_priv, LCPLL_CTL, LCPLL_PLL_LOCK, 0, 1))
9570                 DRM_ERROR("LCPLL still locked\n");
9571
9572         val = hsw_read_dcomp(dev_priv);
9573         val |= D_COMP_COMP_DISABLE;
9574         hsw_write_dcomp(dev_priv, val);
9575         ndelay(100);
9576
9577         if (wait_for((hsw_read_dcomp(dev_priv) & D_COMP_RCOMP_IN_PROGRESS) == 0,
9578                      1))
9579                 DRM_ERROR("D_COMP RCOMP still in progress\n");
9580
9581         if (allow_power_down) {
9582                 val = I915_READ(LCPLL_CTL);
9583                 val |= LCPLL_POWER_DOWN_ALLOW;
9584                 I915_WRITE(LCPLL_CTL, val);
9585                 POSTING_READ(LCPLL_CTL);
9586         }
9587 }
9588
9589 /*
9590  * Fully restores LCPLL, disallowing power down and switching back to LCPLL
9591  * source.
9592  */
9593 static void hsw_restore_lcpll(struct drm_i915_private *dev_priv)
9594 {
9595         uint32_t val;
9596
9597         val = I915_READ(LCPLL_CTL);
9598
9599         if ((val & (LCPLL_PLL_LOCK | LCPLL_PLL_DISABLE | LCPLL_CD_SOURCE_FCLK |
9600                     LCPLL_POWER_DOWN_ALLOW)) == LCPLL_PLL_LOCK)
9601                 return;
9602
9603         /*
9604          * Make sure we're not on PC8 state before disabling PC8, otherwise
9605          * we'll hang the machine. To prevent PC8 state, just enable force_wake.
9606          */
9607         intel_uncore_forcewake_get(dev_priv, FORCEWAKE_ALL);
9608
9609         if (val & LCPLL_POWER_DOWN_ALLOW) {
9610                 val &= ~LCPLL_POWER_DOWN_ALLOW;
9611                 I915_WRITE(LCPLL_CTL, val);
9612                 POSTING_READ(LCPLL_CTL);
9613         }
9614
9615         val = hsw_read_dcomp(dev_priv);
9616         val |= D_COMP_COMP_FORCE;
9617         val &= ~D_COMP_COMP_DISABLE;
9618         hsw_write_dcomp(dev_priv, val);
9619
9620         val = I915_READ(LCPLL_CTL);
9621         val &= ~LCPLL_PLL_DISABLE;
9622         I915_WRITE(LCPLL_CTL, val);
9623
9624         if (intel_wait_for_register(dev_priv,
9625                                     LCPLL_CTL, LCPLL_PLL_LOCK, LCPLL_PLL_LOCK,
9626                                     5))
9627                 DRM_ERROR("LCPLL not locked yet\n");
9628
9629         if (val & LCPLL_CD_SOURCE_FCLK) {
9630                 val = I915_READ(LCPLL_CTL);
9631                 val &= ~LCPLL_CD_SOURCE_FCLK;
9632                 I915_WRITE(LCPLL_CTL, val);
9633
9634                 if (wait_for_us((I915_READ(LCPLL_CTL) &
9635                                  LCPLL_CD_SOURCE_FCLK_DONE) == 0, 1))
9636                         DRM_ERROR("Switching back to LCPLL failed\n");
9637         }
9638
9639         intel_uncore_forcewake_put(dev_priv, FORCEWAKE_ALL);
9640         intel_update_cdclk(&dev_priv->drm);
9641 }
9642
9643 /*
9644  * Package states C8 and deeper are really deep PC states that can only be
9645  * reached when all the devices on the system allow it, so even if the graphics
9646  * device allows PC8+, it doesn't mean the system will actually get to these
9647  * states. Our driver only allows PC8+ when going into runtime PM.
9648  *
9649  * The requirements for PC8+ are that all the outputs are disabled, the power
9650  * well is disabled and most interrupts are disabled, and these are also
9651  * requirements for runtime PM. When these conditions are met, we manually do
9652  * the other conditions: disable the interrupts, clocks and switch LCPLL refclk
9653  * to Fclk. If we're in PC8+ and we get an non-hotplug interrupt, we can hard
9654  * hang the machine.
9655  *
9656  * When we really reach PC8 or deeper states (not just when we allow it) we lose
9657  * the state of some registers, so when we come back from PC8+ we need to
9658  * restore this state. We don't get into PC8+ if we're not in RC6, so we don't
9659  * need to take care of the registers kept by RC6. Notice that this happens even
9660  * if we don't put the device in PCI D3 state (which is what currently happens
9661  * because of the runtime PM support).
9662  *
9663  * For more, read "Display Sequences for Package C8" on the hardware
9664  * documentation.
9665  */
9666 void hsw_enable_pc8(struct drm_i915_private *dev_priv)
9667 {
9668         struct drm_device *dev = &dev_priv->drm;
9669         uint32_t val;
9670
9671         DRM_DEBUG_KMS("Enabling package C8+\n");
9672
9673         if (HAS_PCH_LPT_LP(dev)) {
9674                 val = I915_READ(SOUTH_DSPCLK_GATE_D);
9675                 val &= ~PCH_LP_PARTITION_LEVEL_DISABLE;
9676                 I915_WRITE(SOUTH_DSPCLK_GATE_D, val);
9677         }
9678
9679         lpt_disable_clkout_dp(dev);
9680         hsw_disable_lcpll(dev_priv, true, true);
9681 }
9682
9683 void hsw_disable_pc8(struct drm_i915_private *dev_priv)
9684 {
9685         struct drm_device *dev = &dev_priv->drm;
9686         uint32_t val;
9687
9688         DRM_DEBUG_KMS("Disabling package C8+\n");
9689
9690         hsw_restore_lcpll(dev_priv);
9691         lpt_init_pch_refclk(dev);
9692
9693         if (HAS_PCH_LPT_LP(dev)) {
9694                 val = I915_READ(SOUTH_DSPCLK_GATE_D);
9695                 val |= PCH_LP_PARTITION_LEVEL_DISABLE;
9696                 I915_WRITE(SOUTH_DSPCLK_GATE_D, val);
9697         }
9698 }
9699
9700 static void bxt_modeset_commit_cdclk(struct drm_atomic_state *old_state)
9701 {
9702         struct drm_device *dev = old_state->dev;
9703         struct intel_atomic_state *old_intel_state =
9704                 to_intel_atomic_state(old_state);
9705         unsigned int req_cdclk = old_intel_state->dev_cdclk;
9706
9707         bxt_set_cdclk(to_i915(dev), req_cdclk);
9708 }
9709
9710 /* compute the max rate for new configuration */
9711 static int ilk_max_pixel_rate(struct drm_atomic_state *state)
9712 {
9713         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
9714         struct drm_i915_private *dev_priv = to_i915(state->dev);
9715         struct drm_crtc *crtc;
9716         struct drm_crtc_state *cstate;
9717         struct intel_crtc_state *crtc_state;
9718         unsigned max_pixel_rate = 0, i;
9719         enum pipe pipe;
9720
9721         memcpy(intel_state->min_pixclk, dev_priv->min_pixclk,
9722                sizeof(intel_state->min_pixclk));
9723
9724         for_each_crtc_in_state(state, crtc, cstate, i) {
9725                 int pixel_rate;
9726
9727                 crtc_state = to_intel_crtc_state(cstate);
9728                 if (!crtc_state->base.enable) {
9729                         intel_state->min_pixclk[i] = 0;
9730                         continue;
9731                 }
9732
9733                 pixel_rate = ilk_pipe_pixel_rate(crtc_state);
9734
9735                 /* pixel rate mustn't exceed 95% of cdclk with IPS on BDW */
9736                 if (IS_BROADWELL(dev_priv) && crtc_state->ips_enabled)
9737                         pixel_rate = DIV_ROUND_UP(pixel_rate * 100, 95);
9738
9739                 intel_state->min_pixclk[i] = pixel_rate;
9740         }
9741
9742         for_each_pipe(dev_priv, pipe)
9743                 max_pixel_rate = max(intel_state->min_pixclk[pipe], max_pixel_rate);
9744
9745         return max_pixel_rate;
9746 }
9747
9748 static void broadwell_set_cdclk(struct drm_device *dev, int cdclk)
9749 {
9750         struct drm_i915_private *dev_priv = to_i915(dev);
9751         uint32_t val, data;
9752         int ret;
9753
9754         if (WARN((I915_READ(LCPLL_CTL) &
9755                   (LCPLL_PLL_DISABLE | LCPLL_PLL_LOCK |
9756                    LCPLL_CD_CLOCK_DISABLE | LCPLL_ROOT_CD_CLOCK_DISABLE |
9757                    LCPLL_CD2X_CLOCK_DISABLE | LCPLL_POWER_DOWN_ALLOW |
9758                    LCPLL_CD_SOURCE_FCLK)) != LCPLL_PLL_LOCK,
9759                  "trying to change cdclk frequency with cdclk not enabled\n"))
9760                 return;
9761
9762         mutex_lock(&dev_priv->rps.hw_lock);
9763         ret = sandybridge_pcode_write(dev_priv,
9764                                       BDW_PCODE_DISPLAY_FREQ_CHANGE_REQ, 0x0);
9765         mutex_unlock(&dev_priv->rps.hw_lock);
9766         if (ret) {
9767                 DRM_ERROR("failed to inform pcode about cdclk change\n");
9768                 return;
9769         }
9770
9771         val = I915_READ(LCPLL_CTL);
9772         val |= LCPLL_CD_SOURCE_FCLK;
9773         I915_WRITE(LCPLL_CTL, val);
9774
9775         if (wait_for_us(I915_READ(LCPLL_CTL) &
9776                         LCPLL_CD_SOURCE_FCLK_DONE, 1))
9777                 DRM_ERROR("Switching to FCLK failed\n");
9778
9779         val = I915_READ(LCPLL_CTL);
9780         val &= ~LCPLL_CLK_FREQ_MASK;
9781
9782         switch (cdclk) {
9783         case 450000:
9784                 val |= LCPLL_CLK_FREQ_450;
9785                 data = 0;
9786                 break;
9787         case 540000:
9788                 val |= LCPLL_CLK_FREQ_54O_BDW;
9789                 data = 1;
9790                 break;
9791         case 337500:
9792                 val |= LCPLL_CLK_FREQ_337_5_BDW;
9793                 data = 2;
9794                 break;
9795         case 675000:
9796                 val |= LCPLL_CLK_FREQ_675_BDW;
9797                 data = 3;
9798                 break;
9799         default:
9800                 WARN(1, "invalid cdclk frequency\n");
9801                 return;
9802         }
9803
9804         I915_WRITE(LCPLL_CTL, val);
9805
9806         val = I915_READ(LCPLL_CTL);
9807         val &= ~LCPLL_CD_SOURCE_FCLK;
9808         I915_WRITE(LCPLL_CTL, val);
9809
9810         if (wait_for_us((I915_READ(LCPLL_CTL) &
9811                         LCPLL_CD_SOURCE_FCLK_DONE) == 0, 1))
9812                 DRM_ERROR("Switching back to LCPLL failed\n");
9813
9814         mutex_lock(&dev_priv->rps.hw_lock);
9815         sandybridge_pcode_write(dev_priv, HSW_PCODE_DE_WRITE_FREQ_REQ, data);
9816         mutex_unlock(&dev_priv->rps.hw_lock);
9817
9818         I915_WRITE(CDCLK_FREQ, DIV_ROUND_CLOSEST(cdclk, 1000) - 1);
9819
9820         intel_update_cdclk(dev);
9821
9822         WARN(cdclk != dev_priv->cdclk_freq,
9823              "cdclk requested %d kHz but got %d kHz\n",
9824              cdclk, dev_priv->cdclk_freq);
9825 }
9826
9827 static int broadwell_calc_cdclk(int max_pixclk)
9828 {
9829         if (max_pixclk > 540000)
9830                 return 675000;
9831         else if (max_pixclk > 450000)
9832                 return 540000;
9833         else if (max_pixclk > 337500)
9834                 return 450000;
9835         else
9836                 return 337500;
9837 }
9838
9839 static int broadwell_modeset_calc_cdclk(struct drm_atomic_state *state)
9840 {
9841         struct drm_i915_private *dev_priv = to_i915(state->dev);
9842         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
9843         int max_pixclk = ilk_max_pixel_rate(state);
9844         int cdclk;
9845
9846         /*
9847          * FIXME should also account for plane ratio
9848          * once 64bpp pixel formats are supported.
9849          */
9850         cdclk = broadwell_calc_cdclk(max_pixclk);
9851
9852         if (cdclk > dev_priv->max_cdclk_freq) {
9853                 DRM_DEBUG_KMS("requested cdclk (%d kHz) exceeds max (%d kHz)\n",
9854                               cdclk, dev_priv->max_cdclk_freq);
9855                 return -EINVAL;
9856         }
9857
9858         intel_state->cdclk = intel_state->dev_cdclk = cdclk;
9859         if (!intel_state->active_crtcs)
9860                 intel_state->dev_cdclk = broadwell_calc_cdclk(0);
9861
9862         return 0;
9863 }
9864
9865 static void broadwell_modeset_commit_cdclk(struct drm_atomic_state *old_state)
9866 {
9867         struct drm_device *dev = old_state->dev;
9868         struct intel_atomic_state *old_intel_state =
9869                 to_intel_atomic_state(old_state);
9870         unsigned req_cdclk = old_intel_state->dev_cdclk;
9871
9872         broadwell_set_cdclk(dev, req_cdclk);
9873 }
9874
9875 static int skl_modeset_calc_cdclk(struct drm_atomic_state *state)
9876 {
9877         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
9878         struct drm_i915_private *dev_priv = to_i915(state->dev);
9879         const int max_pixclk = ilk_max_pixel_rate(state);
9880         int vco = intel_state->cdclk_pll_vco;
9881         int cdclk;
9882
9883         /*
9884          * FIXME should also account for plane ratio
9885          * once 64bpp pixel formats are supported.
9886          */
9887         cdclk = skl_calc_cdclk(max_pixclk, vco);
9888
9889         /*
9890          * FIXME move the cdclk caclulation to
9891          * compute_config() so we can fail gracegully.
9892          */
9893         if (cdclk > dev_priv->max_cdclk_freq) {
9894                 DRM_ERROR("requested cdclk (%d kHz) exceeds max (%d kHz)\n",
9895                           cdclk, dev_priv->max_cdclk_freq);
9896                 cdclk = dev_priv->max_cdclk_freq;
9897         }
9898
9899         intel_state->cdclk = intel_state->dev_cdclk = cdclk;
9900         if (!intel_state->active_crtcs)
9901                 intel_state->dev_cdclk = skl_calc_cdclk(0, vco);
9902
9903         return 0;
9904 }
9905
9906 static void skl_modeset_commit_cdclk(struct drm_atomic_state *old_state)
9907 {
9908         struct drm_i915_private *dev_priv = to_i915(old_state->dev);
9909         struct intel_atomic_state *intel_state = to_intel_atomic_state(old_state);
9910         unsigned int req_cdclk = intel_state->dev_cdclk;
9911         unsigned int req_vco = intel_state->cdclk_pll_vco;
9912
9913         skl_set_cdclk(dev_priv, req_cdclk, req_vco);
9914 }
9915
9916 static int haswell_crtc_compute_clock(struct intel_crtc *crtc,
9917                                       struct intel_crtc_state *crtc_state)
9918 {
9919         if (!intel_crtc_has_type(crtc_state, INTEL_OUTPUT_DSI)) {
9920                 if (!intel_ddi_pll_select(crtc, crtc_state))
9921                         return -EINVAL;
9922         }
9923
9924         crtc->lowfreq_avail = false;
9925
9926         return 0;
9927 }
9928
9929 static void bxt_get_ddi_pll(struct drm_i915_private *dev_priv,
9930                                 enum port port,
9931                                 struct intel_crtc_state *pipe_config)
9932 {
9933         enum intel_dpll_id id;
9934
9935         switch (port) {
9936         case PORT_A:
9937                 pipe_config->ddi_pll_sel = SKL_DPLL0;
9938                 id = DPLL_ID_SKL_DPLL0;
9939                 break;
9940         case PORT_B:
9941                 pipe_config->ddi_pll_sel = SKL_DPLL1;
9942                 id = DPLL_ID_SKL_DPLL1;
9943                 break;
9944         case PORT_C:
9945                 pipe_config->ddi_pll_sel = SKL_DPLL2;
9946                 id = DPLL_ID_SKL_DPLL2;
9947                 break;
9948         default:
9949                 DRM_ERROR("Incorrect port type\n");
9950                 return;
9951         }
9952
9953         pipe_config->shared_dpll = intel_get_shared_dpll_by_id(dev_priv, id);
9954 }
9955
9956 static void skylake_get_ddi_pll(struct drm_i915_private *dev_priv,
9957                                 enum port port,
9958                                 struct intel_crtc_state *pipe_config)
9959 {
9960         enum intel_dpll_id id;
9961         u32 temp;
9962
9963         temp = I915_READ(DPLL_CTRL2) & DPLL_CTRL2_DDI_CLK_SEL_MASK(port);
9964         pipe_config->ddi_pll_sel = temp >> (port * 3 + 1);
9965
9966         switch (pipe_config->ddi_pll_sel) {
9967         case SKL_DPLL0:
9968                 id = DPLL_ID_SKL_DPLL0;
9969                 break;
9970         case SKL_DPLL1:
9971                 id = DPLL_ID_SKL_DPLL1;
9972                 break;
9973         case SKL_DPLL2:
9974                 id = DPLL_ID_SKL_DPLL2;
9975                 break;
9976         case SKL_DPLL3:
9977                 id = DPLL_ID_SKL_DPLL3;
9978                 break;
9979         default:
9980                 MISSING_CASE(pipe_config->ddi_pll_sel);
9981                 return;
9982         }
9983
9984         pipe_config->shared_dpll = intel_get_shared_dpll_by_id(dev_priv, id);
9985 }
9986
9987 static void haswell_get_ddi_pll(struct drm_i915_private *dev_priv,
9988                                 enum port port,
9989                                 struct intel_crtc_state *pipe_config)
9990 {
9991         enum intel_dpll_id id;
9992
9993         pipe_config->ddi_pll_sel = I915_READ(PORT_CLK_SEL(port));
9994
9995         switch (pipe_config->ddi_pll_sel) {
9996         case PORT_CLK_SEL_WRPLL1:
9997                 id = DPLL_ID_WRPLL1;
9998                 break;
9999         case PORT_CLK_SEL_WRPLL2:
10000                 id = DPLL_ID_WRPLL2;
10001                 break;
10002         case PORT_CLK_SEL_SPLL:
10003                 id = DPLL_ID_SPLL;
10004                 break;
10005         case PORT_CLK_SEL_LCPLL_810:
10006                 id = DPLL_ID_LCPLL_810;
10007                 break;
10008         case PORT_CLK_SEL_LCPLL_1350:
10009                 id = DPLL_ID_LCPLL_1350;
10010                 break;
10011         case PORT_CLK_SEL_LCPLL_2700:
10012                 id = DPLL_ID_LCPLL_2700;
10013                 break;
10014         default:
10015                 MISSING_CASE(pipe_config->ddi_pll_sel);
10016                 /* fall through */
10017         case PORT_CLK_SEL_NONE:
10018                 return;
10019         }
10020
10021         pipe_config->shared_dpll = intel_get_shared_dpll_by_id(dev_priv, id);
10022 }
10023
10024 static bool hsw_get_transcoder_state(struct intel_crtc *crtc,
10025                                      struct intel_crtc_state *pipe_config,
10026                                      unsigned long *power_domain_mask)
10027 {
10028         struct drm_device *dev = crtc->base.dev;
10029         struct drm_i915_private *dev_priv = to_i915(dev);
10030         enum intel_display_power_domain power_domain;
10031         u32 tmp;
10032
10033         /*
10034          * The pipe->transcoder mapping is fixed with the exception of the eDP
10035          * transcoder handled below.
10036          */
10037         pipe_config->cpu_transcoder = (enum transcoder) crtc->pipe;
10038
10039         /*
10040          * XXX: Do intel_display_power_get_if_enabled before reading this (for
10041          * consistency and less surprising code; it's in always on power).
10042          */
10043         tmp = I915_READ(TRANS_DDI_FUNC_CTL(TRANSCODER_EDP));
10044         if (tmp & TRANS_DDI_FUNC_ENABLE) {
10045                 enum pipe trans_edp_pipe;
10046                 switch (tmp & TRANS_DDI_EDP_INPUT_MASK) {
10047                 default:
10048                         WARN(1, "unknown pipe linked to edp transcoder\n");
10049                 case TRANS_DDI_EDP_INPUT_A_ONOFF:
10050                 case TRANS_DDI_EDP_INPUT_A_ON:
10051                         trans_edp_pipe = PIPE_A;
10052                         break;
10053                 case TRANS_DDI_EDP_INPUT_B_ONOFF:
10054                         trans_edp_pipe = PIPE_B;
10055                         break;
10056                 case TRANS_DDI_EDP_INPUT_C_ONOFF:
10057                         trans_edp_pipe = PIPE_C;
10058                         break;
10059                 }
10060
10061                 if (trans_edp_pipe == crtc->pipe)
10062                         pipe_config->cpu_transcoder = TRANSCODER_EDP;
10063         }
10064
10065         power_domain = POWER_DOMAIN_TRANSCODER(pipe_config->cpu_transcoder);
10066         if (!intel_display_power_get_if_enabled(dev_priv, power_domain))
10067                 return false;
10068         *power_domain_mask |= BIT(power_domain);
10069
10070         tmp = I915_READ(PIPECONF(pipe_config->cpu_transcoder));
10071
10072         return tmp & PIPECONF_ENABLE;
10073 }
10074
10075 static bool bxt_get_dsi_transcoder_state(struct intel_crtc *crtc,
10076                                          struct intel_crtc_state *pipe_config,
10077                                          unsigned long *power_domain_mask)
10078 {
10079         struct drm_device *dev = crtc->base.dev;
10080         struct drm_i915_private *dev_priv = to_i915(dev);
10081         enum intel_display_power_domain power_domain;
10082         enum port port;
10083         enum transcoder cpu_transcoder;
10084         u32 tmp;
10085
10086         for_each_port_masked(port, BIT(PORT_A) | BIT(PORT_C)) {
10087                 if (port == PORT_A)
10088                         cpu_transcoder = TRANSCODER_DSI_A;
10089                 else
10090                         cpu_transcoder = TRANSCODER_DSI_C;
10091
10092                 power_domain = POWER_DOMAIN_TRANSCODER(cpu_transcoder);
10093                 if (!intel_display_power_get_if_enabled(dev_priv, power_domain))
10094                         continue;
10095                 *power_domain_mask |= BIT(power_domain);
10096
10097                 /*
10098                  * The PLL needs to be enabled with a valid divider
10099                  * configuration, otherwise accessing DSI registers will hang
10100                  * the machine. See BSpec North Display Engine
10101                  * registers/MIPI[BXT]. We can break out here early, since we
10102                  * need the same DSI PLL to be enabled for both DSI ports.
10103                  */
10104                 if (!intel_dsi_pll_is_enabled(dev_priv))
10105                         break;
10106
10107                 /* XXX: this works for video mode only */
10108                 tmp = I915_READ(BXT_MIPI_PORT_CTRL(port));
10109                 if (!(tmp & DPI_ENABLE))
10110                         continue;
10111
10112                 tmp = I915_READ(MIPI_CTRL(port));
10113                 if ((tmp & BXT_PIPE_SELECT_MASK) != BXT_PIPE_SELECT(crtc->pipe))
10114                         continue;
10115
10116                 pipe_config->cpu_transcoder = cpu_transcoder;
10117                 break;
10118         }
10119
10120         return transcoder_is_dsi(pipe_config->cpu_transcoder);
10121 }
10122
10123 static void haswell_get_ddi_port_state(struct intel_crtc *crtc,
10124                                        struct intel_crtc_state *pipe_config)
10125 {
10126         struct drm_device *dev = crtc->base.dev;
10127         struct drm_i915_private *dev_priv = to_i915(dev);
10128         struct intel_shared_dpll *pll;
10129         enum port port;
10130         uint32_t tmp;
10131
10132         tmp = I915_READ(TRANS_DDI_FUNC_CTL(pipe_config->cpu_transcoder));
10133
10134         port = (tmp & TRANS_DDI_PORT_MASK) >> TRANS_DDI_PORT_SHIFT;
10135
10136         if (IS_SKYLAKE(dev) || IS_KABYLAKE(dev))
10137                 skylake_get_ddi_pll(dev_priv, port, pipe_config);
10138         else if (IS_BROXTON(dev))
10139                 bxt_get_ddi_pll(dev_priv, port, pipe_config);
10140         else
10141                 haswell_get_ddi_pll(dev_priv, port, pipe_config);
10142
10143         pll = pipe_config->shared_dpll;
10144         if (pll) {
10145                 WARN_ON(!pll->funcs.get_hw_state(dev_priv, pll,
10146                                                  &pipe_config->dpll_hw_state));
10147         }
10148
10149         /*
10150          * Haswell has only FDI/PCH transcoder A. It is which is connected to
10151          * DDI E. So just check whether this pipe is wired to DDI E and whether
10152          * the PCH transcoder is on.
10153          */
10154         if (INTEL_INFO(dev)->gen < 9 &&
10155             (port == PORT_E) && I915_READ(LPT_TRANSCONF) & TRANS_ENABLE) {
10156                 pipe_config->has_pch_encoder = true;
10157
10158                 tmp = I915_READ(FDI_RX_CTL(PIPE_A));
10159                 pipe_config->fdi_lanes = ((FDI_DP_PORT_WIDTH_MASK & tmp) >>
10160                                           FDI_DP_PORT_WIDTH_SHIFT) + 1;
10161
10162                 ironlake_get_fdi_m_n_config(crtc, pipe_config);
10163         }
10164 }
10165
10166 static bool haswell_get_pipe_config(struct intel_crtc *crtc,
10167                                     struct intel_crtc_state *pipe_config)
10168 {
10169         struct drm_device *dev = crtc->base.dev;
10170         struct drm_i915_private *dev_priv = to_i915(dev);
10171         enum intel_display_power_domain power_domain;
10172         unsigned long power_domain_mask;
10173         bool active;
10174
10175         power_domain = POWER_DOMAIN_PIPE(crtc->pipe);
10176         if (!intel_display_power_get_if_enabled(dev_priv, power_domain))
10177                 return false;
10178         power_domain_mask = BIT(power_domain);
10179
10180         pipe_config->shared_dpll = NULL;
10181
10182         active = hsw_get_transcoder_state(crtc, pipe_config, &power_domain_mask);
10183
10184         if (IS_BROXTON(dev_priv) &&
10185             bxt_get_dsi_transcoder_state(crtc, pipe_config, &power_domain_mask)) {
10186                 WARN_ON(active);
10187                 active = true;
10188         }
10189
10190         if (!active)
10191                 goto out;
10192
10193         if (!transcoder_is_dsi(pipe_config->cpu_transcoder)) {
10194                 haswell_get_ddi_port_state(crtc, pipe_config);
10195                 intel_get_pipe_timings(crtc, pipe_config);
10196         }
10197
10198         intel_get_pipe_src_size(crtc, pipe_config);
10199
10200         pipe_config->gamma_mode =
10201                 I915_READ(GAMMA_MODE(crtc->pipe)) & GAMMA_MODE_MODE_MASK;
10202
10203         if (INTEL_INFO(dev)->gen >= 9) {
10204                 skl_init_scalers(dev, crtc, pipe_config);
10205         }
10206
10207         if (INTEL_INFO(dev)->gen >= 9) {
10208                 pipe_config->scaler_state.scaler_id = -1;
10209                 pipe_config->scaler_state.scaler_users &= ~(1 << SKL_CRTC_INDEX);
10210         }
10211
10212         power_domain = POWER_DOMAIN_PIPE_PANEL_FITTER(crtc->pipe);
10213         if (intel_display_power_get_if_enabled(dev_priv, power_domain)) {
10214                 power_domain_mask |= BIT(power_domain);
10215                 if (INTEL_INFO(dev)->gen >= 9)
10216                         skylake_get_pfit_config(crtc, pipe_config);
10217                 else
10218                         ironlake_get_pfit_config(crtc, pipe_config);
10219         }
10220
10221         if (IS_HASWELL(dev))
10222                 pipe_config->ips_enabled = hsw_crtc_supports_ips(crtc) &&
10223                         (I915_READ(IPS_CTL) & IPS_ENABLE);
10224
10225         if (pipe_config->cpu_transcoder != TRANSCODER_EDP &&
10226             !transcoder_is_dsi(pipe_config->cpu_transcoder)) {
10227                 pipe_config->pixel_multiplier =
10228                         I915_READ(PIPE_MULT(pipe_config->cpu_transcoder)) + 1;
10229         } else {
10230                 pipe_config->pixel_multiplier = 1;
10231         }
10232
10233 out:
10234         for_each_power_domain(power_domain, power_domain_mask)
10235                 intel_display_power_put(dev_priv, power_domain);
10236
10237         return active;
10238 }
10239
10240 static void i845_update_cursor(struct drm_crtc *crtc, u32 base,
10241                                const struct intel_plane_state *plane_state)
10242 {
10243         struct drm_device *dev = crtc->dev;
10244         struct drm_i915_private *dev_priv = to_i915(dev);
10245         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
10246         uint32_t cntl = 0, size = 0;
10247
10248         if (plane_state && plane_state->visible) {
10249                 unsigned int width = plane_state->base.crtc_w;
10250                 unsigned int height = plane_state->base.crtc_h;
10251                 unsigned int stride = roundup_pow_of_two(width) * 4;
10252
10253                 switch (stride) {
10254                 default:
10255                         WARN_ONCE(1, "Invalid cursor width/stride, width=%u, stride=%u\n",
10256                                   width, stride);
10257                         stride = 256;
10258                         /* fallthrough */
10259                 case 256:
10260                 case 512:
10261                 case 1024:
10262                 case 2048:
10263                         break;
10264                 }
10265
10266                 cntl |= CURSOR_ENABLE |
10267                         CURSOR_GAMMA_ENABLE |
10268                         CURSOR_FORMAT_ARGB |
10269                         CURSOR_STRIDE(stride);
10270
10271                 size = (height << 12) | width;
10272         }
10273
10274         if (intel_crtc->cursor_cntl != 0 &&
10275             (intel_crtc->cursor_base != base ||
10276              intel_crtc->cursor_size != size ||
10277              intel_crtc->cursor_cntl != cntl)) {
10278                 /* On these chipsets we can only modify the base/size/stride
10279                  * whilst the cursor is disabled.
10280                  */
10281                 I915_WRITE(CURCNTR(PIPE_A), 0);
10282                 POSTING_READ(CURCNTR(PIPE_A));
10283                 intel_crtc->cursor_cntl = 0;
10284         }
10285
10286         if (intel_crtc->cursor_base != base) {
10287                 I915_WRITE(CURBASE(PIPE_A), base);
10288                 intel_crtc->cursor_base = base;
10289         }
10290
10291         if (intel_crtc->cursor_size != size) {
10292                 I915_WRITE(CURSIZE, size);
10293                 intel_crtc->cursor_size = size;
10294         }
10295
10296         if (intel_crtc->cursor_cntl != cntl) {
10297                 I915_WRITE(CURCNTR(PIPE_A), cntl);
10298                 POSTING_READ(CURCNTR(PIPE_A));
10299                 intel_crtc->cursor_cntl = cntl;
10300         }
10301 }
10302
10303 static void i9xx_update_cursor(struct drm_crtc *crtc, u32 base,
10304                                const struct intel_plane_state *plane_state)
10305 {
10306         struct drm_device *dev = crtc->dev;
10307         struct drm_i915_private *dev_priv = to_i915(dev);
10308         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
10309         int pipe = intel_crtc->pipe;
10310         uint32_t cntl = 0;
10311
10312         if (plane_state && plane_state->visible) {
10313                 cntl = MCURSOR_GAMMA_ENABLE;
10314                 switch (plane_state->base.crtc_w) {
10315                         case 64:
10316                                 cntl |= CURSOR_MODE_64_ARGB_AX;
10317                                 break;
10318                         case 128:
10319                                 cntl |= CURSOR_MODE_128_ARGB_AX;
10320                                 break;
10321                         case 256:
10322                                 cntl |= CURSOR_MODE_256_ARGB_AX;
10323                                 break;
10324                         default:
10325                                 MISSING_CASE(plane_state->base.crtc_w);
10326                                 return;
10327                 }
10328                 cntl |= pipe << 28; /* Connect to correct pipe */
10329
10330                 if (HAS_DDI(dev))
10331                         cntl |= CURSOR_PIPE_CSC_ENABLE;
10332
10333                 if (plane_state->base.rotation == BIT(DRM_ROTATE_180))
10334                         cntl |= CURSOR_ROTATE_180;
10335         }
10336
10337         if (intel_crtc->cursor_cntl != cntl) {
10338                 I915_WRITE(CURCNTR(pipe), cntl);
10339                 POSTING_READ(CURCNTR(pipe));
10340                 intel_crtc->cursor_cntl = cntl;
10341         }
10342
10343         /* and commit changes on next vblank */
10344         I915_WRITE(CURBASE(pipe), base);
10345         POSTING_READ(CURBASE(pipe));
10346
10347         intel_crtc->cursor_base = base;
10348 }
10349
10350 /* If no-part of the cursor is visible on the framebuffer, then the GPU may hang... */
10351 static void intel_crtc_update_cursor(struct drm_crtc *crtc,
10352                                      const struct intel_plane_state *plane_state)
10353 {
10354         struct drm_device *dev = crtc->dev;
10355         struct drm_i915_private *dev_priv = to_i915(dev);
10356         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
10357         int pipe = intel_crtc->pipe;
10358         u32 base = intel_crtc->cursor_addr;
10359         u32 pos = 0;
10360
10361         if (plane_state) {
10362                 int x = plane_state->base.crtc_x;
10363                 int y = plane_state->base.crtc_y;
10364
10365                 if (x < 0) {
10366                         pos |= CURSOR_POS_SIGN << CURSOR_X_SHIFT;
10367                         x = -x;
10368                 }
10369                 pos |= x << CURSOR_X_SHIFT;
10370
10371                 if (y < 0) {
10372                         pos |= CURSOR_POS_SIGN << CURSOR_Y_SHIFT;
10373                         y = -y;
10374                 }
10375                 pos |= y << CURSOR_Y_SHIFT;
10376
10377                 /* ILK+ do this automagically */
10378                 if (HAS_GMCH_DISPLAY(dev) &&
10379                     plane_state->base.rotation == BIT(DRM_ROTATE_180)) {
10380                         base += (plane_state->base.crtc_h *
10381                                  plane_state->base.crtc_w - 1) * 4;
10382                 }
10383         }
10384
10385         I915_WRITE(CURPOS(pipe), pos);
10386
10387         if (IS_845G(dev) || IS_I865G(dev))
10388                 i845_update_cursor(crtc, base, plane_state);
10389         else
10390                 i9xx_update_cursor(crtc, base, plane_state);
10391 }
10392
10393 static bool cursor_size_ok(struct drm_device *dev,
10394                            uint32_t width, uint32_t height)
10395 {
10396         if (width == 0 || height == 0)
10397                 return false;
10398
10399         /*
10400          * 845g/865g are special in that they are only limited by
10401          * the width of their cursors, the height is arbitrary up to
10402          * the precision of the register. Everything else requires
10403          * square cursors, limited to a few power-of-two sizes.
10404          */
10405         if (IS_845G(dev) || IS_I865G(dev)) {
10406                 if ((width & 63) != 0)
10407                         return false;
10408
10409                 if (width > (IS_845G(dev) ? 64 : 512))
10410                         return false;
10411
10412                 if (height > 1023)
10413                         return false;
10414         } else {
10415                 switch (width | height) {
10416                 case 256:
10417                 case 128:
10418                         if (IS_GEN2(dev))
10419                                 return false;
10420                 case 64:
10421                         break;
10422                 default:
10423                         return false;
10424                 }
10425         }
10426
10427         return true;
10428 }
10429
10430 /* VESA 640x480x72Hz mode to set on the pipe */
10431 static struct drm_display_mode load_detect_mode = {
10432         DRM_MODE("640x480", DRM_MODE_TYPE_DEFAULT, 31500, 640, 664,
10433                  704, 832, 0, 480, 489, 491, 520, 0, DRM_MODE_FLAG_NHSYNC | DRM_MODE_FLAG_NVSYNC),
10434 };
10435
10436 struct drm_framebuffer *
10437 __intel_framebuffer_create(struct drm_device *dev,
10438                            struct drm_mode_fb_cmd2 *mode_cmd,
10439                            struct drm_i915_gem_object *obj)
10440 {
10441         struct intel_framebuffer *intel_fb;
10442         int ret;
10443
10444         intel_fb = kzalloc(sizeof(*intel_fb), GFP_KERNEL);
10445         if (!intel_fb)
10446                 return ERR_PTR(-ENOMEM);
10447
10448         ret = intel_framebuffer_init(dev, intel_fb, mode_cmd, obj);
10449         if (ret)
10450                 goto err;
10451
10452         return &intel_fb->base;
10453
10454 err:
10455         kfree(intel_fb);
10456         return ERR_PTR(ret);
10457 }
10458
10459 static struct drm_framebuffer *
10460 intel_framebuffer_create(struct drm_device *dev,
10461                          struct drm_mode_fb_cmd2 *mode_cmd,
10462                          struct drm_i915_gem_object *obj)
10463 {
10464         struct drm_framebuffer *fb;
10465         int ret;
10466
10467         ret = i915_mutex_lock_interruptible(dev);
10468         if (ret)
10469                 return ERR_PTR(ret);
10470         fb = __intel_framebuffer_create(dev, mode_cmd, obj);
10471         mutex_unlock(&dev->struct_mutex);
10472
10473         return fb;
10474 }
10475
10476 static u32
10477 intel_framebuffer_pitch_for_width(int width, int bpp)
10478 {
10479         u32 pitch = DIV_ROUND_UP(width * bpp, 8);
10480         return ALIGN(pitch, 64);
10481 }
10482
10483 static u32
10484 intel_framebuffer_size_for_mode(struct drm_display_mode *mode, int bpp)
10485 {
10486         u32 pitch = intel_framebuffer_pitch_for_width(mode->hdisplay, bpp);
10487         return PAGE_ALIGN(pitch * mode->vdisplay);
10488 }
10489
10490 static struct drm_framebuffer *
10491 intel_framebuffer_create_for_mode(struct drm_device *dev,
10492                                   struct drm_display_mode *mode,
10493                                   int depth, int bpp)
10494 {
10495         struct drm_framebuffer *fb;
10496         struct drm_i915_gem_object *obj;
10497         struct drm_mode_fb_cmd2 mode_cmd = { 0 };
10498
10499         obj = i915_gem_object_create(dev,
10500                                     intel_framebuffer_size_for_mode(mode, bpp));
10501         if (IS_ERR(obj))
10502                 return ERR_CAST(obj);
10503
10504         mode_cmd.width = mode->hdisplay;
10505         mode_cmd.height = mode->vdisplay;
10506         mode_cmd.pitches[0] = intel_framebuffer_pitch_for_width(mode_cmd.width,
10507                                                                 bpp);
10508         mode_cmd.pixel_format = drm_mode_legacy_fb_format(bpp, depth);
10509
10510         fb = intel_framebuffer_create(dev, &mode_cmd, obj);
10511         if (IS_ERR(fb))
10512                 drm_gem_object_unreference_unlocked(&obj->base);
10513
10514         return fb;
10515 }
10516
10517 static struct drm_framebuffer *
10518 mode_fits_in_fbdev(struct drm_device *dev,
10519                    struct drm_display_mode *mode)
10520 {
10521 #ifdef CONFIG_DRM_FBDEV_EMULATION
10522         struct drm_i915_private *dev_priv = to_i915(dev);
10523         struct drm_i915_gem_object *obj;
10524         struct drm_framebuffer *fb;
10525
10526         if (!dev_priv->fbdev)
10527                 return NULL;
10528
10529         if (!dev_priv->fbdev->fb)
10530                 return NULL;
10531
10532         obj = dev_priv->fbdev->fb->obj;
10533         BUG_ON(!obj);
10534
10535         fb = &dev_priv->fbdev->fb->base;
10536         if (fb->pitches[0] < intel_framebuffer_pitch_for_width(mode->hdisplay,
10537                                                                fb->bits_per_pixel))
10538                 return NULL;
10539
10540         if (obj->base.size < mode->vdisplay * fb->pitches[0])
10541                 return NULL;
10542
10543         drm_framebuffer_reference(fb);
10544         return fb;
10545 #else
10546         return NULL;
10547 #endif
10548 }
10549
10550 static int intel_modeset_setup_plane_state(struct drm_atomic_state *state,
10551                                            struct drm_crtc *crtc,
10552                                            struct drm_display_mode *mode,
10553                                            struct drm_framebuffer *fb,
10554                                            int x, int y)
10555 {
10556         struct drm_plane_state *plane_state;
10557         int hdisplay, vdisplay;
10558         int ret;
10559
10560         plane_state = drm_atomic_get_plane_state(state, crtc->primary);
10561         if (IS_ERR(plane_state))
10562                 return PTR_ERR(plane_state);
10563
10564         if (mode)
10565                 drm_crtc_get_hv_timing(mode, &hdisplay, &vdisplay);
10566         else
10567                 hdisplay = vdisplay = 0;
10568
10569         ret = drm_atomic_set_crtc_for_plane(plane_state, fb ? crtc : NULL);
10570         if (ret)
10571                 return ret;
10572         drm_atomic_set_fb_for_plane(plane_state, fb);
10573         plane_state->crtc_x = 0;
10574         plane_state->crtc_y = 0;
10575         plane_state->crtc_w = hdisplay;
10576         plane_state->crtc_h = vdisplay;
10577         plane_state->src_x = x << 16;
10578         plane_state->src_y = y << 16;
10579         plane_state->src_w = hdisplay << 16;
10580         plane_state->src_h = vdisplay << 16;
10581
10582         return 0;
10583 }
10584
10585 bool intel_get_load_detect_pipe(struct drm_connector *connector,
10586                                 struct drm_display_mode *mode,
10587                                 struct intel_load_detect_pipe *old,
10588                                 struct drm_modeset_acquire_ctx *ctx)
10589 {
10590         struct intel_crtc *intel_crtc;
10591         struct intel_encoder *intel_encoder =
10592                 intel_attached_encoder(connector);
10593         struct drm_crtc *possible_crtc;
10594         struct drm_encoder *encoder = &intel_encoder->base;
10595         struct drm_crtc *crtc = NULL;
10596         struct drm_device *dev = encoder->dev;
10597         struct drm_framebuffer *fb;
10598         struct drm_mode_config *config = &dev->mode_config;
10599         struct drm_atomic_state *state = NULL, *restore_state = NULL;
10600         struct drm_connector_state *connector_state;
10601         struct intel_crtc_state *crtc_state;
10602         int ret, i = -1;
10603
10604         DRM_DEBUG_KMS("[CONNECTOR:%d:%s], [ENCODER:%d:%s]\n",
10605                       connector->base.id, connector->name,
10606                       encoder->base.id, encoder->name);
10607
10608         old->restore_state = NULL;
10609
10610 retry:
10611         ret = drm_modeset_lock(&config->connection_mutex, ctx);
10612         if (ret)
10613                 goto fail;
10614
10615         /*
10616          * Algorithm gets a little messy:
10617          *
10618          *   - if the connector already has an assigned crtc, use it (but make
10619          *     sure it's on first)
10620          *
10621          *   - try to find the first unused crtc that can drive this connector,
10622          *     and use that if we find one
10623          */
10624
10625         /* See if we already have a CRTC for this connector */
10626         if (connector->state->crtc) {
10627                 crtc = connector->state->crtc;
10628
10629                 ret = drm_modeset_lock(&crtc->mutex, ctx);
10630                 if (ret)
10631                         goto fail;
10632
10633                 /* Make sure the crtc and connector are running */
10634                 goto found;
10635         }
10636
10637         /* Find an unused one (if possible) */
10638         for_each_crtc(dev, possible_crtc) {
10639                 i++;
10640                 if (!(encoder->possible_crtcs & (1 << i)))
10641                         continue;
10642
10643                 ret = drm_modeset_lock(&possible_crtc->mutex, ctx);
10644                 if (ret)
10645                         goto fail;
10646
10647                 if (possible_crtc->state->enable) {
10648                         drm_modeset_unlock(&possible_crtc->mutex);
10649                         continue;
10650                 }
10651
10652                 crtc = possible_crtc;
10653                 break;
10654         }
10655
10656         /*
10657          * If we didn't find an unused CRTC, don't use any.
10658          */
10659         if (!crtc) {
10660                 DRM_DEBUG_KMS("no pipe available for load-detect\n");
10661                 goto fail;
10662         }
10663
10664 found:
10665         intel_crtc = to_intel_crtc(crtc);
10666
10667         ret = drm_modeset_lock(&crtc->primary->mutex, ctx);
10668         if (ret)
10669                 goto fail;
10670
10671         state = drm_atomic_state_alloc(dev);
10672         restore_state = drm_atomic_state_alloc(dev);
10673         if (!state || !restore_state) {
10674                 ret = -ENOMEM;
10675                 goto fail;
10676         }
10677
10678         state->acquire_ctx = ctx;
10679         restore_state->acquire_ctx = ctx;
10680
10681         connector_state = drm_atomic_get_connector_state(state, connector);
10682         if (IS_ERR(connector_state)) {
10683                 ret = PTR_ERR(connector_state);
10684                 goto fail;
10685         }
10686
10687         ret = drm_atomic_set_crtc_for_connector(connector_state, crtc);
10688         if (ret)
10689                 goto fail;
10690
10691         crtc_state = intel_atomic_get_crtc_state(state, intel_crtc);
10692         if (IS_ERR(crtc_state)) {
10693                 ret = PTR_ERR(crtc_state);
10694                 goto fail;
10695         }
10696
10697         crtc_state->base.active = crtc_state->base.enable = true;
10698
10699         if (!mode)
10700                 mode = &load_detect_mode;
10701
10702         /* We need a framebuffer large enough to accommodate all accesses
10703          * that the plane may generate whilst we perform load detection.
10704          * We can not rely on the fbcon either being present (we get called
10705          * during its initialisation to detect all boot displays, or it may
10706          * not even exist) or that it is large enough to satisfy the
10707          * requested mode.
10708          */
10709         fb = mode_fits_in_fbdev(dev, mode);
10710         if (fb == NULL) {
10711                 DRM_DEBUG_KMS("creating tmp fb for load-detection\n");
10712                 fb = intel_framebuffer_create_for_mode(dev, mode, 24, 32);
10713         } else
10714                 DRM_DEBUG_KMS("reusing fbdev for load-detection framebuffer\n");
10715         if (IS_ERR(fb)) {
10716                 DRM_DEBUG_KMS("failed to allocate framebuffer for load-detection\n");
10717                 goto fail;
10718         }
10719
10720         ret = intel_modeset_setup_plane_state(state, crtc, mode, fb, 0, 0);
10721         if (ret)
10722                 goto fail;
10723
10724         drm_framebuffer_unreference(fb);
10725
10726         ret = drm_atomic_set_mode_for_crtc(&crtc_state->base, mode);
10727         if (ret)
10728                 goto fail;
10729
10730         ret = PTR_ERR_OR_ZERO(drm_atomic_get_connector_state(restore_state, connector));
10731         if (!ret)
10732                 ret = PTR_ERR_OR_ZERO(drm_atomic_get_crtc_state(restore_state, crtc));
10733         if (!ret)
10734                 ret = PTR_ERR_OR_ZERO(drm_atomic_get_plane_state(restore_state, crtc->primary));
10735         if (ret) {
10736                 DRM_DEBUG_KMS("Failed to create a copy of old state to restore: %i\n", ret);
10737                 goto fail;
10738         }
10739
10740         ret = drm_atomic_commit(state);
10741         if (ret) {
10742                 DRM_DEBUG_KMS("failed to set mode on load-detect pipe\n");
10743                 goto fail;
10744         }
10745
10746         old->restore_state = restore_state;
10747
10748         /* let the connector get through one full cycle before testing */
10749         intel_wait_for_vblank(dev, intel_crtc->pipe);
10750         return true;
10751
10752 fail:
10753         drm_atomic_state_free(state);
10754         drm_atomic_state_free(restore_state);
10755         restore_state = state = NULL;
10756
10757         if (ret == -EDEADLK) {
10758                 drm_modeset_backoff(ctx);
10759                 goto retry;
10760         }
10761
10762         return false;
10763 }
10764
10765 void intel_release_load_detect_pipe(struct drm_connector *connector,
10766                                     struct intel_load_detect_pipe *old,
10767                                     struct drm_modeset_acquire_ctx *ctx)
10768 {
10769         struct intel_encoder *intel_encoder =
10770                 intel_attached_encoder(connector);
10771         struct drm_encoder *encoder = &intel_encoder->base;
10772         struct drm_atomic_state *state = old->restore_state;
10773         int ret;
10774
10775         DRM_DEBUG_KMS("[CONNECTOR:%d:%s], [ENCODER:%d:%s]\n",
10776                       connector->base.id, connector->name,
10777                       encoder->base.id, encoder->name);
10778
10779         if (!state)
10780                 return;
10781
10782         ret = drm_atomic_commit(state);
10783         if (ret) {
10784                 DRM_DEBUG_KMS("Couldn't release load detect pipe: %i\n", ret);
10785                 drm_atomic_state_free(state);
10786         }
10787 }
10788
10789 static int i9xx_pll_refclk(struct drm_device *dev,
10790                            const struct intel_crtc_state *pipe_config)
10791 {
10792         struct drm_i915_private *dev_priv = to_i915(dev);
10793         u32 dpll = pipe_config->dpll_hw_state.dpll;
10794
10795         if ((dpll & PLL_REF_INPUT_MASK) == PLLB_REF_INPUT_SPREADSPECTRUMIN)
10796                 return dev_priv->vbt.lvds_ssc_freq;
10797         else if (HAS_PCH_SPLIT(dev))
10798                 return 120000;
10799         else if (!IS_GEN2(dev))
10800                 return 96000;
10801         else
10802                 return 48000;
10803 }
10804
10805 /* Returns the clock of the currently programmed mode of the given pipe. */
10806 static void i9xx_crtc_clock_get(struct intel_crtc *crtc,
10807                                 struct intel_crtc_state *pipe_config)
10808 {
10809         struct drm_device *dev = crtc->base.dev;
10810         struct drm_i915_private *dev_priv = to_i915(dev);
10811         int pipe = pipe_config->cpu_transcoder;
10812         u32 dpll = pipe_config->dpll_hw_state.dpll;
10813         u32 fp;
10814         struct dpll clock;
10815         int port_clock;
10816         int refclk = i9xx_pll_refclk(dev, pipe_config);
10817
10818         if ((dpll & DISPLAY_RATE_SELECT_FPA1) == 0)
10819                 fp = pipe_config->dpll_hw_state.fp0;
10820         else
10821                 fp = pipe_config->dpll_hw_state.fp1;
10822
10823         clock.m1 = (fp & FP_M1_DIV_MASK) >> FP_M1_DIV_SHIFT;
10824         if (IS_PINEVIEW(dev)) {
10825                 clock.n = ffs((fp & FP_N_PINEVIEW_DIV_MASK) >> FP_N_DIV_SHIFT) - 1;
10826                 clock.m2 = (fp & FP_M2_PINEVIEW_DIV_MASK) >> FP_M2_DIV_SHIFT;
10827         } else {
10828                 clock.n = (fp & FP_N_DIV_MASK) >> FP_N_DIV_SHIFT;
10829                 clock.m2 = (fp & FP_M2_DIV_MASK) >> FP_M2_DIV_SHIFT;
10830         }
10831
10832         if (!IS_GEN2(dev)) {
10833                 if (IS_PINEVIEW(dev))
10834                         clock.p1 = ffs((dpll & DPLL_FPA01_P1_POST_DIV_MASK_PINEVIEW) >>
10835                                 DPLL_FPA01_P1_POST_DIV_SHIFT_PINEVIEW);
10836                 else
10837                         clock.p1 = ffs((dpll & DPLL_FPA01_P1_POST_DIV_MASK) >>
10838                                DPLL_FPA01_P1_POST_DIV_SHIFT);
10839
10840                 switch (dpll & DPLL_MODE_MASK) {
10841                 case DPLLB_MODE_DAC_SERIAL:
10842                         clock.p2 = dpll & DPLL_DAC_SERIAL_P2_CLOCK_DIV_5 ?
10843                                 5 : 10;
10844                         break;
10845                 case DPLLB_MODE_LVDS:
10846                         clock.p2 = dpll & DPLLB_LVDS_P2_CLOCK_DIV_7 ?
10847                                 7 : 14;
10848                         break;
10849                 default:
10850                         DRM_DEBUG_KMS("Unknown DPLL mode %08x in programmed "
10851                                   "mode\n", (int)(dpll & DPLL_MODE_MASK));
10852                         return;
10853                 }
10854
10855                 if (IS_PINEVIEW(dev))
10856                         port_clock = pnv_calc_dpll_params(refclk, &clock);
10857                 else
10858                         port_clock = i9xx_calc_dpll_params(refclk, &clock);
10859         } else {
10860                 u32 lvds = IS_I830(dev) ? 0 : I915_READ(LVDS);
10861                 bool is_lvds = (pipe == 1) && (lvds & LVDS_PORT_EN);
10862
10863                 if (is_lvds) {
10864                         clock.p1 = ffs((dpll & DPLL_FPA01_P1_POST_DIV_MASK_I830_LVDS) >>
10865                                        DPLL_FPA01_P1_POST_DIV_SHIFT);
10866
10867                         if (lvds & LVDS_CLKB_POWER_UP)
10868                                 clock.p2 = 7;
10869                         else
10870                                 clock.p2 = 14;
10871                 } else {
10872                         if (dpll & PLL_P1_DIVIDE_BY_TWO)
10873                                 clock.p1 = 2;
10874                         else {
10875                                 clock.p1 = ((dpll & DPLL_FPA01_P1_POST_DIV_MASK_I830) >>
10876                                             DPLL_FPA01_P1_POST_DIV_SHIFT) + 2;
10877                         }
10878                         if (dpll & PLL_P2_DIVIDE_BY_4)
10879                                 clock.p2 = 4;
10880                         else
10881                                 clock.p2 = 2;
10882                 }
10883
10884                 port_clock = i9xx_calc_dpll_params(refclk, &clock);
10885         }
10886
10887         /*
10888          * This value includes pixel_multiplier. We will use
10889          * port_clock to compute adjusted_mode.crtc_clock in the
10890          * encoder's get_config() function.
10891          */
10892         pipe_config->port_clock = port_clock;
10893 }
10894
10895 int intel_dotclock_calculate(int link_freq,
10896                              const struct intel_link_m_n *m_n)
10897 {
10898         /*
10899          * The calculation for the data clock is:
10900          * pixel_clock = ((m/n)*(link_clock * nr_lanes))/bpp
10901          * But we want to avoid losing precison if possible, so:
10902          * pixel_clock = ((m * link_clock * nr_lanes)/(n*bpp))
10903          *
10904          * and the link clock is simpler:
10905          * link_clock = (m * link_clock) / n
10906          */
10907
10908         if (!m_n->link_n)
10909                 return 0;
10910
10911         return div_u64((u64)m_n->link_m * link_freq, m_n->link_n);
10912 }
10913
10914 static void ironlake_pch_clock_get(struct intel_crtc *crtc,
10915                                    struct intel_crtc_state *pipe_config)
10916 {
10917         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
10918
10919         /* read out port_clock from the DPLL */
10920         i9xx_crtc_clock_get(crtc, pipe_config);
10921
10922         /*
10923          * In case there is an active pipe without active ports,
10924          * we may need some idea for the dotclock anyway.
10925          * Calculate one based on the FDI configuration.
10926          */
10927         pipe_config->base.adjusted_mode.crtc_clock =
10928                 intel_dotclock_calculate(intel_fdi_link_freq(dev_priv, pipe_config),
10929                                          &pipe_config->fdi_m_n);
10930 }
10931
10932 /** Returns the currently programmed mode of the given pipe. */
10933 struct drm_display_mode *intel_crtc_mode_get(struct drm_device *dev,
10934                                              struct drm_crtc *crtc)
10935 {
10936         struct drm_i915_private *dev_priv = to_i915(dev);
10937         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
10938         enum transcoder cpu_transcoder = intel_crtc->config->cpu_transcoder;
10939         struct drm_display_mode *mode;
10940         struct intel_crtc_state *pipe_config;
10941         int htot = I915_READ(HTOTAL(cpu_transcoder));
10942         int hsync = I915_READ(HSYNC(cpu_transcoder));
10943         int vtot = I915_READ(VTOTAL(cpu_transcoder));
10944         int vsync = I915_READ(VSYNC(cpu_transcoder));
10945         enum pipe pipe = intel_crtc->pipe;
10946
10947         mode = kzalloc(sizeof(*mode), GFP_KERNEL);
10948         if (!mode)
10949                 return NULL;
10950
10951         pipe_config = kzalloc(sizeof(*pipe_config), GFP_KERNEL);
10952         if (!pipe_config) {
10953                 kfree(mode);
10954                 return NULL;
10955         }
10956
10957         /*
10958          * Construct a pipe_config sufficient for getting the clock info
10959          * back out of crtc_clock_get.
10960          *
10961          * Note, if LVDS ever uses a non-1 pixel multiplier, we'll need
10962          * to use a real value here instead.
10963          */
10964         pipe_config->cpu_transcoder = (enum transcoder) pipe;
10965         pipe_config->pixel_multiplier = 1;
10966         pipe_config->dpll_hw_state.dpll = I915_READ(DPLL(pipe));
10967         pipe_config->dpll_hw_state.fp0 = I915_READ(FP0(pipe));
10968         pipe_config->dpll_hw_state.fp1 = I915_READ(FP1(pipe));
10969         i9xx_crtc_clock_get(intel_crtc, pipe_config);
10970
10971         mode->clock = pipe_config->port_clock / pipe_config->pixel_multiplier;
10972         mode->hdisplay = (htot & 0xffff) + 1;
10973         mode->htotal = ((htot & 0xffff0000) >> 16) + 1;
10974         mode->hsync_start = (hsync & 0xffff) + 1;
10975         mode->hsync_end = ((hsync & 0xffff0000) >> 16) + 1;
10976         mode->vdisplay = (vtot & 0xffff) + 1;
10977         mode->vtotal = ((vtot & 0xffff0000) >> 16) + 1;
10978         mode->vsync_start = (vsync & 0xffff) + 1;
10979         mode->vsync_end = ((vsync & 0xffff0000) >> 16) + 1;
10980
10981         drm_mode_set_name(mode);
10982
10983         kfree(pipe_config);
10984
10985         return mode;
10986 }
10987
10988 static void intel_crtc_destroy(struct drm_crtc *crtc)
10989 {
10990         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
10991         struct drm_device *dev = crtc->dev;
10992         struct intel_flip_work *work;
10993
10994         spin_lock_irq(&dev->event_lock);
10995         work = intel_crtc->flip_work;
10996         intel_crtc->flip_work = NULL;
10997         spin_unlock_irq(&dev->event_lock);
10998
10999         if (work) {
11000                 cancel_work_sync(&work->mmio_work);
11001                 cancel_work_sync(&work->unpin_work);
11002                 kfree(work);
11003         }
11004
11005         drm_crtc_cleanup(crtc);
11006
11007         kfree(intel_crtc);
11008 }
11009
11010 static void intel_unpin_work_fn(struct work_struct *__work)
11011 {
11012         struct intel_flip_work *work =
11013                 container_of(__work, struct intel_flip_work, unpin_work);
11014         struct intel_crtc *crtc = to_intel_crtc(work->crtc);
11015         struct drm_device *dev = crtc->base.dev;
11016         struct drm_plane *primary = crtc->base.primary;
11017
11018         if (is_mmio_work(work))
11019                 flush_work(&work->mmio_work);
11020
11021         mutex_lock(&dev->struct_mutex);
11022         intel_unpin_fb_obj(work->old_fb, primary->state->rotation);
11023         drm_gem_object_unreference(&work->pending_flip_obj->base);
11024
11025         if (work->flip_queued_req)
11026                 i915_gem_request_assign(&work->flip_queued_req, NULL);
11027         mutex_unlock(&dev->struct_mutex);
11028
11029         intel_frontbuffer_flip_complete(dev, to_intel_plane(primary)->frontbuffer_bit);
11030         intel_fbc_post_update(crtc);
11031         drm_framebuffer_unreference(work->old_fb);
11032
11033         BUG_ON(atomic_read(&crtc->unpin_work_count) == 0);
11034         atomic_dec(&crtc->unpin_work_count);
11035
11036         kfree(work);
11037 }
11038
11039 /* Is 'a' after or equal to 'b'? */
11040 static bool g4x_flip_count_after_eq(u32 a, u32 b)
11041 {
11042         return !((a - b) & 0x80000000);
11043 }
11044
11045 static bool __pageflip_finished_cs(struct intel_crtc *crtc,
11046                                    struct intel_flip_work *work)
11047 {
11048         struct drm_device *dev = crtc->base.dev;
11049         struct drm_i915_private *dev_priv = to_i915(dev);
11050         unsigned reset_counter;
11051
11052         reset_counter = i915_reset_counter(&dev_priv->gpu_error);
11053         if (crtc->reset_counter != reset_counter)
11054                 return true;
11055
11056         /*
11057          * The relevant registers doen't exist on pre-ctg.
11058          * As the flip done interrupt doesn't trigger for mmio
11059          * flips on gmch platforms, a flip count check isn't
11060          * really needed there. But since ctg has the registers,
11061          * include it in the check anyway.
11062          */
11063         if (INTEL_INFO(dev)->gen < 5 && !IS_G4X(dev))
11064                 return true;
11065
11066         /*
11067          * BDW signals flip done immediately if the plane
11068          * is disabled, even if the plane enable is already
11069          * armed to occur at the next vblank :(
11070          */
11071
11072         /*
11073          * A DSPSURFLIVE check isn't enough in case the mmio and CS flips
11074          * used the same base address. In that case the mmio flip might
11075          * have completed, but the CS hasn't even executed the flip yet.
11076          *
11077          * A flip count check isn't enough as the CS might have updated
11078          * the base address just after start of vblank, but before we
11079          * managed to process the interrupt. This means we'd complete the
11080          * CS flip too soon.
11081          *
11082          * Combining both checks should get us a good enough result. It may
11083          * still happen that the CS flip has been executed, but has not
11084          * yet actually completed. But in case the base address is the same
11085          * anyway, we don't really care.
11086          */
11087         return (I915_READ(DSPSURFLIVE(crtc->plane)) & ~0xfff) ==
11088                 crtc->flip_work->gtt_offset &&
11089                 g4x_flip_count_after_eq(I915_READ(PIPE_FLIPCOUNT_G4X(crtc->pipe)),
11090                                     crtc->flip_work->flip_count);
11091 }
11092
11093 static bool
11094 __pageflip_finished_mmio(struct intel_crtc *crtc,
11095                                struct intel_flip_work *work)
11096 {
11097         /*
11098          * MMIO work completes when vblank is different from
11099          * flip_queued_vblank.
11100          *
11101          * Reset counter value doesn't matter, this is handled by
11102          * i915_wait_request finishing early, so no need to handle
11103          * reset here.
11104          */
11105         return intel_crtc_get_vblank_counter(crtc) != work->flip_queued_vblank;
11106 }
11107
11108
11109 static bool pageflip_finished(struct intel_crtc *crtc,
11110                               struct intel_flip_work *work)
11111 {
11112         if (!atomic_read(&work->pending))
11113                 return false;
11114
11115         smp_rmb();
11116
11117         if (is_mmio_work(work))
11118                 return __pageflip_finished_mmio(crtc, work);
11119         else
11120                 return __pageflip_finished_cs(crtc, work);
11121 }
11122
11123 void intel_finish_page_flip_cs(struct drm_i915_private *dev_priv, int pipe)
11124 {
11125         struct drm_device *dev = &dev_priv->drm;
11126         struct drm_crtc *crtc = dev_priv->pipe_to_crtc_mapping[pipe];
11127         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
11128         struct intel_flip_work *work;
11129         unsigned long flags;
11130
11131         /* Ignore early vblank irqs */
11132         if (!crtc)
11133                 return;
11134
11135         /*
11136          * This is called both by irq handlers and the reset code (to complete
11137          * lost pageflips) so needs the full irqsave spinlocks.
11138          */
11139         spin_lock_irqsave(&dev->event_lock, flags);
11140         work = intel_crtc->flip_work;
11141
11142         if (work != NULL &&
11143             !is_mmio_work(work) &&
11144             pageflip_finished(intel_crtc, work))
11145                 page_flip_completed(intel_crtc);
11146
11147         spin_unlock_irqrestore(&dev->event_lock, flags);
11148 }
11149
11150 void intel_finish_page_flip_mmio(struct drm_i915_private *dev_priv, int pipe)
11151 {
11152         struct drm_device *dev = &dev_priv->drm;
11153         struct drm_crtc *crtc = dev_priv->pipe_to_crtc_mapping[pipe];
11154         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
11155         struct intel_flip_work *work;
11156         unsigned long flags;
11157
11158         /* Ignore early vblank irqs */
11159         if (!crtc)
11160                 return;
11161
11162         /*
11163          * This is called both by irq handlers and the reset code (to complete
11164          * lost pageflips) so needs the full irqsave spinlocks.
11165          */
11166         spin_lock_irqsave(&dev->event_lock, flags);
11167         work = intel_crtc->flip_work;
11168
11169         if (work != NULL &&
11170             is_mmio_work(work) &&
11171             pageflip_finished(intel_crtc, work))
11172                 page_flip_completed(intel_crtc);
11173
11174         spin_unlock_irqrestore(&dev->event_lock, flags);
11175 }
11176
11177 static inline void intel_mark_page_flip_active(struct intel_crtc *crtc,
11178                                                struct intel_flip_work *work)
11179 {
11180         work->flip_queued_vblank = intel_crtc_get_vblank_counter(crtc);
11181
11182         /* Ensure that the work item is consistent when activating it ... */
11183         smp_mb__before_atomic();
11184         atomic_set(&work->pending, 1);
11185 }
11186
11187 static int intel_gen2_queue_flip(struct drm_device *dev,
11188                                  struct drm_crtc *crtc,
11189                                  struct drm_framebuffer *fb,
11190                                  struct drm_i915_gem_object *obj,
11191                                  struct drm_i915_gem_request *req,
11192                                  uint32_t flags)
11193 {
11194         struct intel_engine_cs *engine = req->engine;
11195         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
11196         u32 flip_mask;
11197         int ret;
11198
11199         ret = intel_ring_begin(req, 6);
11200         if (ret)
11201                 return ret;
11202
11203         /* Can't queue multiple flips, so wait for the previous
11204          * one to finish before executing the next.
11205          */
11206         if (intel_crtc->plane)
11207                 flip_mask = MI_WAIT_FOR_PLANE_B_FLIP;
11208         else
11209                 flip_mask = MI_WAIT_FOR_PLANE_A_FLIP;
11210         intel_ring_emit(engine, MI_WAIT_FOR_EVENT | flip_mask);
11211         intel_ring_emit(engine, MI_NOOP);
11212         intel_ring_emit(engine, MI_DISPLAY_FLIP |
11213                         MI_DISPLAY_FLIP_PLANE(intel_crtc->plane));
11214         intel_ring_emit(engine, fb->pitches[0]);
11215         intel_ring_emit(engine, intel_crtc->flip_work->gtt_offset);
11216         intel_ring_emit(engine, 0); /* aux display base address, unused */
11217
11218         return 0;
11219 }
11220
11221 static int intel_gen3_queue_flip(struct drm_device *dev,
11222                                  struct drm_crtc *crtc,
11223                                  struct drm_framebuffer *fb,
11224                                  struct drm_i915_gem_object *obj,
11225                                  struct drm_i915_gem_request *req,
11226                                  uint32_t flags)
11227 {
11228         struct intel_engine_cs *engine = req->engine;
11229         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
11230         u32 flip_mask;
11231         int ret;
11232
11233         ret = intel_ring_begin(req, 6);
11234         if (ret)
11235                 return ret;
11236
11237         if (intel_crtc->plane)
11238                 flip_mask = MI_WAIT_FOR_PLANE_B_FLIP;
11239         else
11240                 flip_mask = MI_WAIT_FOR_PLANE_A_FLIP;
11241         intel_ring_emit(engine, MI_WAIT_FOR_EVENT | flip_mask);
11242         intel_ring_emit(engine, MI_NOOP);
11243         intel_ring_emit(engine, MI_DISPLAY_FLIP_I915 |
11244                         MI_DISPLAY_FLIP_PLANE(intel_crtc->plane));
11245         intel_ring_emit(engine, fb->pitches[0]);
11246         intel_ring_emit(engine, intel_crtc->flip_work->gtt_offset);
11247         intel_ring_emit(engine, MI_NOOP);
11248
11249         return 0;
11250 }
11251
11252 static int intel_gen4_queue_flip(struct drm_device *dev,
11253                                  struct drm_crtc *crtc,
11254                                  struct drm_framebuffer *fb,
11255                                  struct drm_i915_gem_object *obj,
11256                                  struct drm_i915_gem_request *req,
11257                                  uint32_t flags)
11258 {
11259         struct intel_engine_cs *engine = req->engine;
11260         struct drm_i915_private *dev_priv = to_i915(dev);
11261         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
11262         uint32_t pf, pipesrc;
11263         int ret;
11264
11265         ret = intel_ring_begin(req, 4);
11266         if (ret)
11267                 return ret;
11268
11269         /* i965+ uses the linear or tiled offsets from the
11270          * Display Registers (which do not change across a page-flip)
11271          * so we need only reprogram the base address.
11272          */
11273         intel_ring_emit(engine, MI_DISPLAY_FLIP |
11274                         MI_DISPLAY_FLIP_PLANE(intel_crtc->plane));
11275         intel_ring_emit(engine, fb->pitches[0]);
11276         intel_ring_emit(engine, intel_crtc->flip_work->gtt_offset |
11277                         obj->tiling_mode);
11278
11279         /* XXX Enabling the panel-fitter across page-flip is so far
11280          * untested on non-native modes, so ignore it for now.
11281          * pf = I915_READ(pipe == 0 ? PFA_CTL_1 : PFB_CTL_1) & PF_ENABLE;
11282          */
11283         pf = 0;
11284         pipesrc = I915_READ(PIPESRC(intel_crtc->pipe)) & 0x0fff0fff;
11285         intel_ring_emit(engine, pf | pipesrc);
11286
11287         return 0;
11288 }
11289
11290 static int intel_gen6_queue_flip(struct drm_device *dev,
11291                                  struct drm_crtc *crtc,
11292                                  struct drm_framebuffer *fb,
11293                                  struct drm_i915_gem_object *obj,
11294                                  struct drm_i915_gem_request *req,
11295                                  uint32_t flags)
11296 {
11297         struct intel_engine_cs *engine = req->engine;
11298         struct drm_i915_private *dev_priv = to_i915(dev);
11299         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
11300         uint32_t pf, pipesrc;
11301         int ret;
11302
11303         ret = intel_ring_begin(req, 4);
11304         if (ret)
11305                 return ret;
11306
11307         intel_ring_emit(engine, MI_DISPLAY_FLIP |
11308                         MI_DISPLAY_FLIP_PLANE(intel_crtc->plane));
11309         intel_ring_emit(engine, fb->pitches[0] | obj->tiling_mode);
11310         intel_ring_emit(engine, intel_crtc->flip_work->gtt_offset);
11311
11312         /* Contrary to the suggestions in the documentation,
11313          * "Enable Panel Fitter" does not seem to be required when page
11314          * flipping with a non-native mode, and worse causes a normal
11315          * modeset to fail.
11316          * pf = I915_READ(PF_CTL(intel_crtc->pipe)) & PF_ENABLE;
11317          */
11318         pf = 0;
11319         pipesrc = I915_READ(PIPESRC(intel_crtc->pipe)) & 0x0fff0fff;
11320         intel_ring_emit(engine, pf | pipesrc);
11321
11322         return 0;
11323 }
11324
11325 static int intel_gen7_queue_flip(struct drm_device *dev,
11326                                  struct drm_crtc *crtc,
11327                                  struct drm_framebuffer *fb,
11328                                  struct drm_i915_gem_object *obj,
11329                                  struct drm_i915_gem_request *req,
11330                                  uint32_t flags)
11331 {
11332         struct intel_engine_cs *engine = req->engine;
11333         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
11334         uint32_t plane_bit = 0;
11335         int len, ret;
11336
11337         switch (intel_crtc->plane) {
11338         case PLANE_A:
11339                 plane_bit = MI_DISPLAY_FLIP_IVB_PLANE_A;
11340                 break;
11341         case PLANE_B:
11342                 plane_bit = MI_DISPLAY_FLIP_IVB_PLANE_B;
11343                 break;
11344         case PLANE_C:
11345                 plane_bit = MI_DISPLAY_FLIP_IVB_PLANE_C;
11346                 break;
11347         default:
11348                 WARN_ONCE(1, "unknown plane in flip command\n");
11349                 return -ENODEV;
11350         }
11351
11352         len = 4;
11353         if (engine->id == RCS) {
11354                 len += 6;
11355                 /*
11356                  * On Gen 8, SRM is now taking an extra dword to accommodate
11357                  * 48bits addresses, and we need a NOOP for the batch size to
11358                  * stay even.
11359                  */
11360                 if (IS_GEN8(dev))
11361                         len += 2;
11362         }
11363
11364         /*
11365          * BSpec MI_DISPLAY_FLIP for IVB:
11366          * "The full packet must be contained within the same cache line."
11367          *
11368          * Currently the LRI+SRM+MI_DISPLAY_FLIP all fit within the same
11369          * cacheline, if we ever start emitting more commands before
11370          * the MI_DISPLAY_FLIP we may need to first emit everything else,
11371          * then do the cacheline alignment, and finally emit the
11372          * MI_DISPLAY_FLIP.
11373          */
11374         ret = intel_ring_cacheline_align(req);
11375         if (ret)
11376                 return ret;
11377
11378         ret = intel_ring_begin(req, len);
11379         if (ret)
11380                 return ret;
11381
11382         /* Unmask the flip-done completion message. Note that the bspec says that
11383          * we should do this for both the BCS and RCS, and that we must not unmask
11384          * more than one flip event at any time (or ensure that one flip message
11385          * can be sent by waiting for flip-done prior to queueing new flips).
11386          * Experimentation says that BCS works despite DERRMR masking all
11387          * flip-done completion events and that unmasking all planes at once
11388          * for the RCS also doesn't appear to drop events. Setting the DERRMR
11389          * to zero does lead to lockups within MI_DISPLAY_FLIP.
11390          */
11391         if (engine->id == RCS) {
11392                 intel_ring_emit(engine, MI_LOAD_REGISTER_IMM(1));
11393                 intel_ring_emit_reg(engine, DERRMR);
11394                 intel_ring_emit(engine, ~(DERRMR_PIPEA_PRI_FLIP_DONE |
11395                                           DERRMR_PIPEB_PRI_FLIP_DONE |
11396                                           DERRMR_PIPEC_PRI_FLIP_DONE));
11397                 if (IS_GEN8(dev))
11398                         intel_ring_emit(engine, MI_STORE_REGISTER_MEM_GEN8 |
11399                                               MI_SRM_LRM_GLOBAL_GTT);
11400                 else
11401                         intel_ring_emit(engine, MI_STORE_REGISTER_MEM |
11402                                               MI_SRM_LRM_GLOBAL_GTT);
11403                 intel_ring_emit_reg(engine, DERRMR);
11404                 intel_ring_emit(engine, engine->scratch.gtt_offset + 256);
11405                 if (IS_GEN8(dev)) {
11406                         intel_ring_emit(engine, 0);
11407                         intel_ring_emit(engine, MI_NOOP);
11408                 }
11409         }
11410
11411         intel_ring_emit(engine, MI_DISPLAY_FLIP_I915 | plane_bit);
11412         intel_ring_emit(engine, (fb->pitches[0] | obj->tiling_mode));
11413         intel_ring_emit(engine, intel_crtc->flip_work->gtt_offset);
11414         intel_ring_emit(engine, (MI_NOOP));
11415
11416         return 0;
11417 }
11418
11419 static bool use_mmio_flip(struct intel_engine_cs *engine,
11420                           struct drm_i915_gem_object *obj)
11421 {
11422         struct reservation_object *resv;
11423
11424         /*
11425          * This is not being used for older platforms, because
11426          * non-availability of flip done interrupt forces us to use
11427          * CS flips. Older platforms derive flip done using some clever
11428          * tricks involving the flip_pending status bits and vblank irqs.
11429          * So using MMIO flips there would disrupt this mechanism.
11430          */
11431
11432         if (engine == NULL)
11433                 return true;
11434
11435         if (INTEL_GEN(engine->i915) < 5)
11436                 return false;
11437
11438         if (i915.use_mmio_flip < 0)
11439                 return false;
11440         else if (i915.use_mmio_flip > 0)
11441                 return true;
11442         else if (i915.enable_execlists)
11443                 return true;
11444
11445         resv = i915_gem_object_get_dmabuf_resv(obj);
11446         if (resv && !reservation_object_test_signaled_rcu(resv, false))
11447                 return true;
11448
11449         return engine != i915_gem_request_get_engine(obj->last_write_req);
11450 }
11451
11452 static void skl_do_mmio_flip(struct intel_crtc *intel_crtc,
11453                              unsigned int rotation,
11454                              struct intel_flip_work *work)
11455 {
11456         struct drm_device *dev = intel_crtc->base.dev;
11457         struct drm_i915_private *dev_priv = to_i915(dev);
11458         struct drm_framebuffer *fb = intel_crtc->base.primary->fb;
11459         const enum pipe pipe = intel_crtc->pipe;
11460         u32 ctl, stride, tile_height;
11461
11462         ctl = I915_READ(PLANE_CTL(pipe, 0));
11463         ctl &= ~PLANE_CTL_TILED_MASK;
11464         switch (fb->modifier[0]) {
11465         case DRM_FORMAT_MOD_NONE:
11466                 break;
11467         case I915_FORMAT_MOD_X_TILED:
11468                 ctl |= PLANE_CTL_TILED_X;
11469                 break;
11470         case I915_FORMAT_MOD_Y_TILED:
11471                 ctl |= PLANE_CTL_TILED_Y;
11472                 break;
11473         case I915_FORMAT_MOD_Yf_TILED:
11474                 ctl |= PLANE_CTL_TILED_YF;
11475                 break;
11476         default:
11477                 MISSING_CASE(fb->modifier[0]);
11478         }
11479
11480         /*
11481          * The stride is either expressed as a multiple of 64 bytes chunks for
11482          * linear buffers or in number of tiles for tiled buffers.
11483          */
11484         if (intel_rotation_90_or_270(rotation)) {
11485                 /* stride = Surface height in tiles */
11486                 tile_height = intel_tile_height(dev_priv, fb->modifier[0], 0);
11487                 stride = DIV_ROUND_UP(fb->height, tile_height);
11488         } else {
11489                 stride = fb->pitches[0] /
11490                         intel_fb_stride_alignment(dev_priv, fb->modifier[0],
11491                                                   fb->pixel_format);
11492         }
11493
11494         /*
11495          * Both PLANE_CTL and PLANE_STRIDE are not updated on vblank but on
11496          * PLANE_SURF updates, the update is then guaranteed to be atomic.
11497          */
11498         I915_WRITE(PLANE_CTL(pipe, 0), ctl);
11499         I915_WRITE(PLANE_STRIDE(pipe, 0), stride);
11500
11501         I915_WRITE(PLANE_SURF(pipe, 0), work->gtt_offset);
11502         POSTING_READ(PLANE_SURF(pipe, 0));
11503 }
11504
11505 static void ilk_do_mmio_flip(struct intel_crtc *intel_crtc,
11506                              struct intel_flip_work *work)
11507 {
11508         struct drm_device *dev = intel_crtc->base.dev;
11509         struct drm_i915_private *dev_priv = to_i915(dev);
11510         struct intel_framebuffer *intel_fb =
11511                 to_intel_framebuffer(intel_crtc->base.primary->fb);
11512         struct drm_i915_gem_object *obj = intel_fb->obj;
11513         i915_reg_t reg = DSPCNTR(intel_crtc->plane);
11514         u32 dspcntr;
11515
11516         dspcntr = I915_READ(reg);
11517
11518         if (obj->tiling_mode != I915_TILING_NONE)
11519                 dspcntr |= DISPPLANE_TILED;
11520         else
11521                 dspcntr &= ~DISPPLANE_TILED;
11522
11523         I915_WRITE(reg, dspcntr);
11524
11525         I915_WRITE(DSPSURF(intel_crtc->plane), work->gtt_offset);
11526         POSTING_READ(DSPSURF(intel_crtc->plane));
11527 }
11528
11529 static void intel_mmio_flip_work_func(struct work_struct *w)
11530 {
11531         struct intel_flip_work *work =
11532                 container_of(w, struct intel_flip_work, mmio_work);
11533         struct intel_crtc *crtc = to_intel_crtc(work->crtc);
11534         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
11535         struct intel_framebuffer *intel_fb =
11536                 to_intel_framebuffer(crtc->base.primary->fb);
11537         struct drm_i915_gem_object *obj = intel_fb->obj;
11538         struct reservation_object *resv;
11539
11540         if (work->flip_queued_req)
11541                 WARN_ON(__i915_wait_request(work->flip_queued_req,
11542                                             false, NULL,
11543                                             &dev_priv->rps.mmioflips));
11544
11545         /* For framebuffer backed by dmabuf, wait for fence */
11546         resv = i915_gem_object_get_dmabuf_resv(obj);
11547         if (resv)
11548                 WARN_ON(reservation_object_wait_timeout_rcu(resv, false, false,
11549                                                             MAX_SCHEDULE_TIMEOUT) < 0);
11550
11551         intel_pipe_update_start(crtc);
11552
11553         if (INTEL_GEN(dev_priv) >= 9)
11554                 skl_do_mmio_flip(crtc, work->rotation, work);
11555         else
11556                 /* use_mmio_flip() retricts MMIO flips to ilk+ */
11557                 ilk_do_mmio_flip(crtc, work);
11558
11559         intel_pipe_update_end(crtc, work);
11560 }
11561
11562 static int intel_default_queue_flip(struct drm_device *dev,
11563                                     struct drm_crtc *crtc,
11564                                     struct drm_framebuffer *fb,
11565                                     struct drm_i915_gem_object *obj,
11566                                     struct drm_i915_gem_request *req,
11567                                     uint32_t flags)
11568 {
11569         return -ENODEV;
11570 }
11571
11572 static bool __pageflip_stall_check_cs(struct drm_i915_private *dev_priv,
11573                                       struct intel_crtc *intel_crtc,
11574                                       struct intel_flip_work *work)
11575 {
11576         u32 addr, vblank;
11577
11578         if (!atomic_read(&work->pending))
11579                 return false;
11580
11581         smp_rmb();
11582
11583         vblank = intel_crtc_get_vblank_counter(intel_crtc);
11584         if (work->flip_ready_vblank == 0) {
11585                 if (work->flip_queued_req &&
11586                     !i915_gem_request_completed(work->flip_queued_req))
11587                         return false;
11588
11589                 work->flip_ready_vblank = vblank;
11590         }
11591
11592         if (vblank - work->flip_ready_vblank < 3)
11593                 return false;
11594
11595         /* Potential stall - if we see that the flip has happened,
11596          * assume a missed interrupt. */
11597         if (INTEL_GEN(dev_priv) >= 4)
11598                 addr = I915_HI_DISPBASE(I915_READ(DSPSURF(intel_crtc->plane)));
11599         else
11600                 addr = I915_READ(DSPADDR(intel_crtc->plane));
11601
11602         /* There is a potential issue here with a false positive after a flip
11603          * to the same address. We could address this by checking for a
11604          * non-incrementing frame counter.
11605          */
11606         return addr == work->gtt_offset;
11607 }
11608
11609 void intel_check_page_flip(struct drm_i915_private *dev_priv, int pipe)
11610 {
11611         struct drm_device *dev = &dev_priv->drm;
11612         struct drm_crtc *crtc = dev_priv->pipe_to_crtc_mapping[pipe];
11613         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
11614         struct intel_flip_work *work;
11615
11616         WARN_ON(!in_interrupt());
11617
11618         if (crtc == NULL)
11619                 return;
11620
11621         spin_lock(&dev->event_lock);
11622         work = intel_crtc->flip_work;
11623
11624         if (work != NULL && !is_mmio_work(work) &&
11625             __pageflip_stall_check_cs(dev_priv, intel_crtc, work)) {
11626                 WARN_ONCE(1,
11627                           "Kicking stuck page flip: queued at %d, now %d\n",
11628                         work->flip_queued_vblank, intel_crtc_get_vblank_counter(intel_crtc));
11629                 page_flip_completed(intel_crtc);
11630                 work = NULL;
11631         }
11632
11633         if (work != NULL && !is_mmio_work(work) &&
11634             intel_crtc_get_vblank_counter(intel_crtc) - work->flip_queued_vblank > 1)
11635                 intel_queue_rps_boost_for_request(work->flip_queued_req);
11636         spin_unlock(&dev->event_lock);
11637 }
11638
11639 static int intel_crtc_page_flip(struct drm_crtc *crtc,
11640                                 struct drm_framebuffer *fb,
11641                                 struct drm_pending_vblank_event *event,
11642                                 uint32_t page_flip_flags)
11643 {
11644         struct drm_device *dev = crtc->dev;
11645         struct drm_i915_private *dev_priv = to_i915(dev);
11646         struct drm_framebuffer *old_fb = crtc->primary->fb;
11647         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
11648         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
11649         struct drm_plane *primary = crtc->primary;
11650         enum pipe pipe = intel_crtc->pipe;
11651         struct intel_flip_work *work;
11652         struct intel_engine_cs *engine;
11653         bool mmio_flip;
11654         struct drm_i915_gem_request *request = NULL;
11655         int ret;
11656
11657         /*
11658          * drm_mode_page_flip_ioctl() should already catch this, but double
11659          * check to be safe.  In the future we may enable pageflipping from
11660          * a disabled primary plane.
11661          */
11662         if (WARN_ON(intel_fb_obj(old_fb) == NULL))
11663                 return -EBUSY;
11664
11665         /* Can't change pixel format via MI display flips. */
11666         if (fb->pixel_format != crtc->primary->fb->pixel_format)
11667                 return -EINVAL;
11668
11669         /*
11670          * TILEOFF/LINOFF registers can't be changed via MI display flips.
11671          * Note that pitch changes could also affect these register.
11672          */
11673         if (INTEL_INFO(dev)->gen > 3 &&
11674             (fb->offsets[0] != crtc->primary->fb->offsets[0] ||
11675              fb->pitches[0] != crtc->primary->fb->pitches[0]))
11676                 return -EINVAL;
11677
11678         if (i915_terminally_wedged(&dev_priv->gpu_error))
11679                 goto out_hang;
11680
11681         work = kzalloc(sizeof(*work), GFP_KERNEL);
11682         if (work == NULL)
11683                 return -ENOMEM;
11684
11685         work->event = event;
11686         work->crtc = crtc;
11687         work->old_fb = old_fb;
11688         INIT_WORK(&work->unpin_work, intel_unpin_work_fn);
11689
11690         ret = drm_crtc_vblank_get(crtc);
11691         if (ret)
11692                 goto free_work;
11693
11694         /* We borrow the event spin lock for protecting flip_work */
11695         spin_lock_irq(&dev->event_lock);
11696         if (intel_crtc->flip_work) {
11697                 /* Before declaring the flip queue wedged, check if
11698                  * the hardware completed the operation behind our backs.
11699                  */
11700                 if (pageflip_finished(intel_crtc, intel_crtc->flip_work)) {
11701                         DRM_DEBUG_DRIVER("flip queue: previous flip completed, continuing\n");
11702                         page_flip_completed(intel_crtc);
11703                 } else {
11704                         DRM_DEBUG_DRIVER("flip queue: crtc already busy\n");
11705                         spin_unlock_irq(&dev->event_lock);
11706
11707                         drm_crtc_vblank_put(crtc);
11708                         kfree(work);
11709                         return -EBUSY;
11710                 }
11711         }
11712         intel_crtc->flip_work = work;
11713         spin_unlock_irq(&dev->event_lock);
11714
11715         if (atomic_read(&intel_crtc->unpin_work_count) >= 2)
11716                 flush_workqueue(dev_priv->wq);
11717
11718         /* Reference the objects for the scheduled work. */
11719         drm_framebuffer_reference(work->old_fb);
11720         drm_gem_object_reference(&obj->base);
11721
11722         crtc->primary->fb = fb;
11723         update_state_fb(crtc->primary);
11724
11725         intel_fbc_pre_update(intel_crtc, intel_crtc->config,
11726                              to_intel_plane_state(primary->state));
11727
11728         work->pending_flip_obj = obj;
11729
11730         ret = i915_mutex_lock_interruptible(dev);
11731         if (ret)
11732                 goto cleanup;
11733
11734         intel_crtc->reset_counter = i915_reset_counter(&dev_priv->gpu_error);
11735         if (__i915_reset_in_progress_or_wedged(intel_crtc->reset_counter)) {
11736                 ret = -EIO;
11737                 goto cleanup;
11738         }
11739
11740         atomic_inc(&intel_crtc->unpin_work_count);
11741
11742         if (INTEL_INFO(dev)->gen >= 5 || IS_G4X(dev))
11743                 work->flip_count = I915_READ(PIPE_FLIPCOUNT_G4X(pipe)) + 1;
11744
11745         if (IS_VALLEYVIEW(dev) || IS_CHERRYVIEW(dev)) {
11746                 engine = &dev_priv->engine[BCS];
11747                 if (obj->tiling_mode != intel_fb_obj(work->old_fb)->tiling_mode)
11748                         /* vlv: DISPLAY_FLIP fails to change tiling */
11749                         engine = NULL;
11750         } else if (IS_IVYBRIDGE(dev) || IS_HASWELL(dev)) {
11751                 engine = &dev_priv->engine[BCS];
11752         } else if (INTEL_INFO(dev)->gen >= 7) {
11753                 engine = i915_gem_request_get_engine(obj->last_write_req);
11754                 if (engine == NULL || engine->id != RCS)
11755                         engine = &dev_priv->engine[BCS];
11756         } else {
11757                 engine = &dev_priv->engine[RCS];
11758         }
11759
11760         mmio_flip = use_mmio_flip(engine, obj);
11761
11762         /* When using CS flips, we want to emit semaphores between rings.
11763          * However, when using mmio flips we will create a task to do the
11764          * synchronisation, so all we want here is to pin the framebuffer
11765          * into the display plane and skip any waits.
11766          */
11767         if (!mmio_flip) {
11768                 ret = i915_gem_object_sync(obj, engine, &request);
11769                 if (!ret && !request) {
11770                         request = i915_gem_request_alloc(engine, NULL);
11771                         ret = PTR_ERR_OR_ZERO(request);
11772                 }
11773
11774                 if (ret)
11775                         goto cleanup_pending;
11776         }
11777
11778         ret = intel_pin_and_fence_fb_obj(fb, primary->state->rotation);
11779         if (ret)
11780                 goto cleanup_pending;
11781
11782         work->gtt_offset = intel_plane_obj_offset(to_intel_plane(primary),
11783                                                   obj, 0);
11784         work->gtt_offset += intel_crtc->dspaddr_offset;
11785         work->rotation = crtc->primary->state->rotation;
11786
11787         if (mmio_flip) {
11788                 INIT_WORK(&work->mmio_work, intel_mmio_flip_work_func);
11789
11790                 i915_gem_request_assign(&work->flip_queued_req,
11791                                         obj->last_write_req);
11792
11793                 schedule_work(&work->mmio_work);
11794         } else {
11795                 i915_gem_request_assign(&work->flip_queued_req, request);
11796                 ret = dev_priv->display.queue_flip(dev, crtc, fb, obj, request,
11797                                                    page_flip_flags);
11798                 if (ret)
11799                         goto cleanup_unpin;
11800
11801                 intel_mark_page_flip_active(intel_crtc, work);
11802
11803                 i915_add_request_no_flush(request);
11804         }
11805
11806         i915_gem_track_fb(intel_fb_obj(old_fb), obj,
11807                           to_intel_plane(primary)->frontbuffer_bit);
11808         mutex_unlock(&dev->struct_mutex);
11809
11810         intel_frontbuffer_flip_prepare(dev,
11811                                        to_intel_plane(primary)->frontbuffer_bit);
11812
11813         trace_i915_flip_request(intel_crtc->plane, obj);
11814
11815         return 0;
11816
11817 cleanup_unpin:
11818         intel_unpin_fb_obj(fb, crtc->primary->state->rotation);
11819 cleanup_pending:
11820         if (!IS_ERR_OR_NULL(request))
11821                 i915_add_request_no_flush(request);
11822         atomic_dec(&intel_crtc->unpin_work_count);
11823         mutex_unlock(&dev->struct_mutex);
11824 cleanup:
11825         crtc->primary->fb = old_fb;
11826         update_state_fb(crtc->primary);
11827
11828         drm_gem_object_unreference_unlocked(&obj->base);
11829         drm_framebuffer_unreference(work->old_fb);
11830
11831         spin_lock_irq(&dev->event_lock);
11832         intel_crtc->flip_work = NULL;
11833         spin_unlock_irq(&dev->event_lock);
11834
11835         drm_crtc_vblank_put(crtc);
11836 free_work:
11837         kfree(work);
11838
11839         if (ret == -EIO) {
11840                 struct drm_atomic_state *state;
11841                 struct drm_plane_state *plane_state;
11842
11843 out_hang:
11844                 state = drm_atomic_state_alloc(dev);
11845                 if (!state)
11846                         return -ENOMEM;
11847                 state->acquire_ctx = drm_modeset_legacy_acquire_ctx(crtc);
11848
11849 retry:
11850                 plane_state = drm_atomic_get_plane_state(state, primary);
11851                 ret = PTR_ERR_OR_ZERO(plane_state);
11852                 if (!ret) {
11853                         drm_atomic_set_fb_for_plane(plane_state, fb);
11854
11855                         ret = drm_atomic_set_crtc_for_plane(plane_state, crtc);
11856                         if (!ret)
11857                                 ret = drm_atomic_commit(state);
11858                 }
11859
11860                 if (ret == -EDEADLK) {
11861                         drm_modeset_backoff(state->acquire_ctx);
11862                         drm_atomic_state_clear(state);
11863                         goto retry;
11864                 }
11865
11866                 if (ret)
11867                         drm_atomic_state_free(state);
11868
11869                 if (ret == 0 && event) {
11870                         spin_lock_irq(&dev->event_lock);
11871                         drm_crtc_send_vblank_event(crtc, event);
11872                         spin_unlock_irq(&dev->event_lock);
11873                 }
11874         }
11875         return ret;
11876 }
11877
11878
11879 /**
11880  * intel_wm_need_update - Check whether watermarks need updating
11881  * @plane: drm plane
11882  * @state: new plane state
11883  *
11884  * Check current plane state versus the new one to determine whether
11885  * watermarks need to be recalculated.
11886  *
11887  * Returns true or false.
11888  */
11889 static bool intel_wm_need_update(struct drm_plane *plane,
11890                                  struct drm_plane_state *state)
11891 {
11892         struct intel_plane_state *new = to_intel_plane_state(state);
11893         struct intel_plane_state *cur = to_intel_plane_state(plane->state);
11894
11895         /* Update watermarks on tiling or size changes. */
11896         if (new->visible != cur->visible)
11897                 return true;
11898
11899         if (!cur->base.fb || !new->base.fb)
11900                 return false;
11901
11902         if (cur->base.fb->modifier[0] != new->base.fb->modifier[0] ||
11903             cur->base.rotation != new->base.rotation ||
11904             drm_rect_width(&new->src) != drm_rect_width(&cur->src) ||
11905             drm_rect_height(&new->src) != drm_rect_height(&cur->src) ||
11906             drm_rect_width(&new->dst) != drm_rect_width(&cur->dst) ||
11907             drm_rect_height(&new->dst) != drm_rect_height(&cur->dst))
11908                 return true;
11909
11910         return false;
11911 }
11912
11913 static bool needs_scaling(struct intel_plane_state *state)
11914 {
11915         int src_w = drm_rect_width(&state->src) >> 16;
11916         int src_h = drm_rect_height(&state->src) >> 16;
11917         int dst_w = drm_rect_width(&state->dst);
11918         int dst_h = drm_rect_height(&state->dst);
11919
11920         return (src_w != dst_w || src_h != dst_h);
11921 }
11922
11923 int intel_plane_atomic_calc_changes(struct drm_crtc_state *crtc_state,
11924                                     struct drm_plane_state *plane_state)
11925 {
11926         struct intel_crtc_state *pipe_config = to_intel_crtc_state(crtc_state);
11927         struct drm_crtc *crtc = crtc_state->crtc;
11928         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
11929         struct drm_plane *plane = plane_state->plane;
11930         struct drm_device *dev = crtc->dev;
11931         struct drm_i915_private *dev_priv = to_i915(dev);
11932         struct intel_plane_state *old_plane_state =
11933                 to_intel_plane_state(plane->state);
11934         bool mode_changed = needs_modeset(crtc_state);
11935         bool was_crtc_enabled = crtc->state->active;
11936         bool is_crtc_enabled = crtc_state->active;
11937         bool turn_off, turn_on, visible, was_visible;
11938         struct drm_framebuffer *fb = plane_state->fb;
11939         int ret;
11940
11941         if (INTEL_GEN(dev) >= 9 && plane->type != DRM_PLANE_TYPE_CURSOR) {
11942                 ret = skl_update_scaler_plane(
11943                         to_intel_crtc_state(crtc_state),
11944                         to_intel_plane_state(plane_state));
11945                 if (ret)
11946                         return ret;
11947         }
11948
11949         was_visible = old_plane_state->visible;
11950         visible = to_intel_plane_state(plane_state)->visible;
11951
11952         if (!was_crtc_enabled && WARN_ON(was_visible))
11953                 was_visible = false;
11954
11955         /*
11956          * Visibility is calculated as if the crtc was on, but
11957          * after scaler setup everything depends on it being off
11958          * when the crtc isn't active.
11959          *
11960          * FIXME this is wrong for watermarks. Watermarks should also
11961          * be computed as if the pipe would be active. Perhaps move
11962          * per-plane wm computation to the .check_plane() hook, and
11963          * only combine the results from all planes in the current place?
11964          */
11965         if (!is_crtc_enabled)
11966                 to_intel_plane_state(plane_state)->visible = visible = false;
11967
11968         if (!was_visible && !visible)
11969                 return 0;
11970
11971         if (fb != old_plane_state->base.fb)
11972                 pipe_config->fb_changed = true;
11973
11974         turn_off = was_visible && (!visible || mode_changed);
11975         turn_on = visible && (!was_visible || mode_changed);
11976
11977         DRM_DEBUG_ATOMIC("[CRTC:%d:%s] has [PLANE:%d:%s] with fb %i\n",
11978                          intel_crtc->base.base.id,
11979                          intel_crtc->base.name,
11980                          plane->base.id, plane->name,
11981                          fb ? fb->base.id : -1);
11982
11983         DRM_DEBUG_ATOMIC("[PLANE:%d:%s] visible %i -> %i, off %i, on %i, ms %i\n",
11984                          plane->base.id, plane->name,
11985                          was_visible, visible,
11986                          turn_off, turn_on, mode_changed);
11987
11988         if (turn_on) {
11989                 pipe_config->update_wm_pre = true;
11990
11991                 /* must disable cxsr around plane enable/disable */
11992                 if (plane->type != DRM_PLANE_TYPE_CURSOR)
11993                         pipe_config->disable_cxsr = true;
11994         } else if (turn_off) {
11995                 pipe_config->update_wm_post = true;
11996
11997                 /* must disable cxsr around plane enable/disable */
11998                 if (plane->type != DRM_PLANE_TYPE_CURSOR)
11999                         pipe_config->disable_cxsr = true;
12000         } else if (intel_wm_need_update(plane, plane_state)) {
12001                 /* FIXME bollocks */
12002                 pipe_config->update_wm_pre = true;
12003                 pipe_config->update_wm_post = true;
12004         }
12005
12006         /* Pre-gen9 platforms need two-step watermark updates */
12007         if ((pipe_config->update_wm_pre || pipe_config->update_wm_post) &&
12008             INTEL_INFO(dev)->gen < 9 && dev_priv->display.optimize_watermarks)
12009                 to_intel_crtc_state(crtc_state)->wm.need_postvbl_update = true;
12010
12011         if (visible || was_visible)
12012                 pipe_config->fb_bits |= to_intel_plane(plane)->frontbuffer_bit;
12013
12014         /*
12015          * WaCxSRDisabledForSpriteScaling:ivb
12016          *
12017          * cstate->update_wm was already set above, so this flag will
12018          * take effect when we commit and program watermarks.
12019          */
12020         if (plane->type == DRM_PLANE_TYPE_OVERLAY && IS_IVYBRIDGE(dev) &&
12021             needs_scaling(to_intel_plane_state(plane_state)) &&
12022             !needs_scaling(old_plane_state))
12023                 pipe_config->disable_lp_wm = true;
12024
12025         return 0;
12026 }
12027
12028 static bool encoders_cloneable(const struct intel_encoder *a,
12029                                const struct intel_encoder *b)
12030 {
12031         /* masks could be asymmetric, so check both ways */
12032         return a == b || (a->cloneable & (1 << b->type) &&
12033                           b->cloneable & (1 << a->type));
12034 }
12035
12036 static bool check_single_encoder_cloning(struct drm_atomic_state *state,
12037                                          struct intel_crtc *crtc,
12038                                          struct intel_encoder *encoder)
12039 {
12040         struct intel_encoder *source_encoder;
12041         struct drm_connector *connector;
12042         struct drm_connector_state *connector_state;
12043         int i;
12044
12045         for_each_connector_in_state(state, connector, connector_state, i) {
12046                 if (connector_state->crtc != &crtc->base)
12047                         continue;
12048
12049                 source_encoder =
12050                         to_intel_encoder(connector_state->best_encoder);
12051                 if (!encoders_cloneable(encoder, source_encoder))
12052                         return false;
12053         }
12054
12055         return true;
12056 }
12057
12058 static int intel_crtc_atomic_check(struct drm_crtc *crtc,
12059                                    struct drm_crtc_state *crtc_state)
12060 {
12061         struct drm_device *dev = crtc->dev;
12062         struct drm_i915_private *dev_priv = to_i915(dev);
12063         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
12064         struct intel_crtc_state *pipe_config =
12065                 to_intel_crtc_state(crtc_state);
12066         struct drm_atomic_state *state = crtc_state->state;
12067         int ret;
12068         bool mode_changed = needs_modeset(crtc_state);
12069
12070         if (mode_changed && !crtc_state->active)
12071                 pipe_config->update_wm_post = true;
12072
12073         if (mode_changed && crtc_state->enable &&
12074             dev_priv->display.crtc_compute_clock &&
12075             !WARN_ON(pipe_config->shared_dpll)) {
12076                 ret = dev_priv->display.crtc_compute_clock(intel_crtc,
12077                                                            pipe_config);
12078                 if (ret)
12079                         return ret;
12080         }
12081
12082         if (crtc_state->color_mgmt_changed) {
12083                 ret = intel_color_check(crtc, crtc_state);
12084                 if (ret)
12085                         return ret;
12086
12087                 /*
12088                  * Changing color management on Intel hardware is
12089                  * handled as part of planes update.
12090                  */
12091                 crtc_state->planes_changed = true;
12092         }
12093
12094         ret = 0;
12095         if (dev_priv->display.compute_pipe_wm) {
12096                 ret = dev_priv->display.compute_pipe_wm(pipe_config);
12097                 if (ret) {
12098                         DRM_DEBUG_KMS("Target pipe watermarks are invalid\n");
12099                         return ret;
12100                 }
12101         }
12102
12103         if (dev_priv->display.compute_intermediate_wm &&
12104             !to_intel_atomic_state(state)->skip_intermediate_wm) {
12105                 if (WARN_ON(!dev_priv->display.compute_pipe_wm))
12106                         return 0;
12107
12108                 /*
12109                  * Calculate 'intermediate' watermarks that satisfy both the
12110                  * old state and the new state.  We can program these
12111                  * immediately.
12112                  */
12113                 ret = dev_priv->display.compute_intermediate_wm(crtc->dev,
12114                                                                 intel_crtc,
12115                                                                 pipe_config);
12116                 if (ret) {
12117                         DRM_DEBUG_KMS("No valid intermediate pipe watermarks are possible\n");
12118                         return ret;
12119                 }
12120         } else if (dev_priv->display.compute_intermediate_wm) {
12121                 if (HAS_PCH_SPLIT(dev_priv) && INTEL_GEN(dev_priv) < 9)
12122                         pipe_config->wm.ilk.intermediate = pipe_config->wm.ilk.optimal;
12123         }
12124
12125         if (INTEL_INFO(dev)->gen >= 9) {
12126                 if (mode_changed)
12127                         ret = skl_update_scaler_crtc(pipe_config);
12128
12129                 if (!ret)
12130                         ret = intel_atomic_setup_scalers(dev, intel_crtc,
12131                                                          pipe_config);
12132         }
12133
12134         return ret;
12135 }
12136
12137 static const struct drm_crtc_helper_funcs intel_helper_funcs = {
12138         .mode_set_base_atomic = intel_pipe_set_base_atomic,
12139         .atomic_begin = intel_begin_crtc_commit,
12140         .atomic_flush = intel_finish_crtc_commit,
12141         .atomic_check = intel_crtc_atomic_check,
12142 };
12143
12144 static void intel_modeset_update_connector_atomic_state(struct drm_device *dev)
12145 {
12146         struct intel_connector *connector;
12147
12148         for_each_intel_connector(dev, connector) {
12149                 if (connector->base.state->crtc)
12150                         drm_connector_unreference(&connector->base);
12151
12152                 if (connector->base.encoder) {
12153                         connector->base.state->best_encoder =
12154                                 connector->base.encoder;
12155                         connector->base.state->crtc =
12156                                 connector->base.encoder->crtc;
12157
12158                         drm_connector_reference(&connector->base);
12159                 } else {
12160                         connector->base.state->best_encoder = NULL;
12161                         connector->base.state->crtc = NULL;
12162                 }
12163         }
12164 }
12165
12166 static void
12167 connected_sink_compute_bpp(struct intel_connector *connector,
12168                            struct intel_crtc_state *pipe_config)
12169 {
12170         int bpp = pipe_config->pipe_bpp;
12171
12172         DRM_DEBUG_KMS("[CONNECTOR:%d:%s] checking for sink bpp constrains\n",
12173                 connector->base.base.id,
12174                 connector->base.name);
12175
12176         /* Don't use an invalid EDID bpc value */
12177         if (connector->base.display_info.bpc &&
12178             connector->base.display_info.bpc * 3 < bpp) {
12179                 DRM_DEBUG_KMS("clamping display bpp (was %d) to EDID reported max of %d\n",
12180                               bpp, connector->base.display_info.bpc*3);
12181                 pipe_config->pipe_bpp = connector->base.display_info.bpc*3;
12182         }
12183
12184         /* Clamp bpp to 8 on screens without EDID 1.4 */
12185         if (connector->base.display_info.bpc == 0 && bpp > 24) {
12186                 DRM_DEBUG_KMS("clamping display bpp (was %d) to default limit of 24\n",
12187                               bpp);
12188                 pipe_config->pipe_bpp = 24;
12189         }
12190 }
12191
12192 static int
12193 compute_baseline_pipe_bpp(struct intel_crtc *crtc,
12194                           struct intel_crtc_state *pipe_config)
12195 {
12196         struct drm_device *dev = crtc->base.dev;
12197         struct drm_atomic_state *state;
12198         struct drm_connector *connector;
12199         struct drm_connector_state *connector_state;
12200         int bpp, i;
12201
12202         if ((IS_G4X(dev) || IS_VALLEYVIEW(dev) || IS_CHERRYVIEW(dev)))
12203                 bpp = 10*3;
12204         else if (INTEL_INFO(dev)->gen >= 5)
12205                 bpp = 12*3;
12206         else
12207                 bpp = 8*3;
12208
12209
12210         pipe_config->pipe_bpp = bpp;
12211
12212         state = pipe_config->base.state;
12213
12214         /* Clamp display bpp to EDID value */
12215         for_each_connector_in_state(state, connector, connector_state, i) {
12216                 if (connector_state->crtc != &crtc->base)
12217                         continue;
12218
12219                 connected_sink_compute_bpp(to_intel_connector(connector),
12220                                            pipe_config);
12221         }
12222
12223         return bpp;
12224 }
12225
12226 static void intel_dump_crtc_timings(const struct drm_display_mode *mode)
12227 {
12228         DRM_DEBUG_KMS("crtc timings: %d %d %d %d %d %d %d %d %d, "
12229                         "type: 0x%x flags: 0x%x\n",
12230                 mode->crtc_clock,
12231                 mode->crtc_hdisplay, mode->crtc_hsync_start,
12232                 mode->crtc_hsync_end, mode->crtc_htotal,
12233                 mode->crtc_vdisplay, mode->crtc_vsync_start,
12234                 mode->crtc_vsync_end, mode->crtc_vtotal, mode->type, mode->flags);
12235 }
12236
12237 static void intel_dump_pipe_config(struct intel_crtc *crtc,
12238                                    struct intel_crtc_state *pipe_config,
12239                                    const char *context)
12240 {
12241         struct drm_device *dev = crtc->base.dev;
12242         struct drm_plane *plane;
12243         struct intel_plane *intel_plane;
12244         struct intel_plane_state *state;
12245         struct drm_framebuffer *fb;
12246
12247         DRM_DEBUG_KMS("[CRTC:%d:%s]%s config %p for pipe %c\n",
12248                       crtc->base.base.id, crtc->base.name,
12249                       context, pipe_config, pipe_name(crtc->pipe));
12250
12251         DRM_DEBUG_KMS("cpu_transcoder: %s\n", transcoder_name(pipe_config->cpu_transcoder));
12252         DRM_DEBUG_KMS("pipe bpp: %i, dithering: %i\n",
12253                       pipe_config->pipe_bpp, pipe_config->dither);
12254         DRM_DEBUG_KMS("fdi/pch: %i, lanes: %i, gmch_m: %u, gmch_n: %u, link_m: %u, link_n: %u, tu: %u\n",
12255                       pipe_config->has_pch_encoder,
12256                       pipe_config->fdi_lanes,
12257                       pipe_config->fdi_m_n.gmch_m, pipe_config->fdi_m_n.gmch_n,
12258                       pipe_config->fdi_m_n.link_m, pipe_config->fdi_m_n.link_n,
12259                       pipe_config->fdi_m_n.tu);
12260         DRM_DEBUG_KMS("dp: %i, lanes: %i, gmch_m: %u, gmch_n: %u, link_m: %u, link_n: %u, tu: %u\n",
12261                       intel_crtc_has_dp_encoder(pipe_config),
12262                       pipe_config->lane_count,
12263                       pipe_config->dp_m_n.gmch_m, pipe_config->dp_m_n.gmch_n,
12264                       pipe_config->dp_m_n.link_m, pipe_config->dp_m_n.link_n,
12265                       pipe_config->dp_m_n.tu);
12266
12267         DRM_DEBUG_KMS("dp: %i, lanes: %i, gmch_m2: %u, gmch_n2: %u, link_m2: %u, link_n2: %u, tu2: %u\n",
12268                       intel_crtc_has_dp_encoder(pipe_config),
12269                       pipe_config->lane_count,
12270                       pipe_config->dp_m2_n2.gmch_m,
12271                       pipe_config->dp_m2_n2.gmch_n,
12272                       pipe_config->dp_m2_n2.link_m,
12273                       pipe_config->dp_m2_n2.link_n,
12274                       pipe_config->dp_m2_n2.tu);
12275
12276         DRM_DEBUG_KMS("audio: %i, infoframes: %i\n",
12277                       pipe_config->has_audio,
12278                       pipe_config->has_infoframe);
12279
12280         DRM_DEBUG_KMS("requested mode:\n");
12281         drm_mode_debug_printmodeline(&pipe_config->base.mode);
12282         DRM_DEBUG_KMS("adjusted mode:\n");
12283         drm_mode_debug_printmodeline(&pipe_config->base.adjusted_mode);
12284         intel_dump_crtc_timings(&pipe_config->base.adjusted_mode);
12285         DRM_DEBUG_KMS("port clock: %d\n", pipe_config->port_clock);
12286         DRM_DEBUG_KMS("pipe src size: %dx%d\n",
12287                       pipe_config->pipe_src_w, pipe_config->pipe_src_h);
12288         DRM_DEBUG_KMS("num_scalers: %d, scaler_users: 0x%x, scaler_id: %d\n",
12289                       crtc->num_scalers,
12290                       pipe_config->scaler_state.scaler_users,
12291                       pipe_config->scaler_state.scaler_id);
12292         DRM_DEBUG_KMS("gmch pfit: control: 0x%08x, ratios: 0x%08x, lvds border: 0x%08x\n",
12293                       pipe_config->gmch_pfit.control,
12294                       pipe_config->gmch_pfit.pgm_ratios,
12295                       pipe_config->gmch_pfit.lvds_border_bits);
12296         DRM_DEBUG_KMS("pch pfit: pos: 0x%08x, size: 0x%08x, %s\n",
12297                       pipe_config->pch_pfit.pos,
12298                       pipe_config->pch_pfit.size,
12299                       pipe_config->pch_pfit.enabled ? "enabled" : "disabled");
12300         DRM_DEBUG_KMS("ips: %i\n", pipe_config->ips_enabled);
12301         DRM_DEBUG_KMS("double wide: %i\n", pipe_config->double_wide);
12302
12303         if (IS_BROXTON(dev)) {
12304                 DRM_DEBUG_KMS("ddi_pll_sel: %u; dpll_hw_state: ebb0: 0x%x, ebb4: 0x%x,"
12305                               "pll0: 0x%x, pll1: 0x%x, pll2: 0x%x, pll3: 0x%x, "
12306                               "pll6: 0x%x, pll8: 0x%x, pll9: 0x%x, pll10: 0x%x, pcsdw12: 0x%x\n",
12307                               pipe_config->ddi_pll_sel,
12308                               pipe_config->dpll_hw_state.ebb0,
12309                               pipe_config->dpll_hw_state.ebb4,
12310                               pipe_config->dpll_hw_state.pll0,
12311                               pipe_config->dpll_hw_state.pll1,
12312                               pipe_config->dpll_hw_state.pll2,
12313                               pipe_config->dpll_hw_state.pll3,
12314                               pipe_config->dpll_hw_state.pll6,
12315                               pipe_config->dpll_hw_state.pll8,
12316                               pipe_config->dpll_hw_state.pll9,
12317                               pipe_config->dpll_hw_state.pll10,
12318                               pipe_config->dpll_hw_state.pcsdw12);
12319         } else if (IS_SKYLAKE(dev) || IS_KABYLAKE(dev)) {
12320                 DRM_DEBUG_KMS("ddi_pll_sel: %u; dpll_hw_state: "
12321                               "ctrl1: 0x%x, cfgcr1: 0x%x, cfgcr2: 0x%x\n",
12322                               pipe_config->ddi_pll_sel,
12323                               pipe_config->dpll_hw_state.ctrl1,
12324                               pipe_config->dpll_hw_state.cfgcr1,
12325                               pipe_config->dpll_hw_state.cfgcr2);
12326         } else if (HAS_DDI(dev)) {
12327                 DRM_DEBUG_KMS("ddi_pll_sel: 0x%x; dpll_hw_state: wrpll: 0x%x spll: 0x%x\n",
12328                               pipe_config->ddi_pll_sel,
12329                               pipe_config->dpll_hw_state.wrpll,
12330                               pipe_config->dpll_hw_state.spll);
12331         } else {
12332                 DRM_DEBUG_KMS("dpll_hw_state: dpll: 0x%x, dpll_md: 0x%x, "
12333                               "fp0: 0x%x, fp1: 0x%x\n",
12334                               pipe_config->dpll_hw_state.dpll,
12335                               pipe_config->dpll_hw_state.dpll_md,
12336                               pipe_config->dpll_hw_state.fp0,
12337                               pipe_config->dpll_hw_state.fp1);
12338         }
12339
12340         DRM_DEBUG_KMS("planes on this crtc\n");
12341         list_for_each_entry(plane, &dev->mode_config.plane_list, head) {
12342                 intel_plane = to_intel_plane(plane);
12343                 if (intel_plane->pipe != crtc->pipe)
12344                         continue;
12345
12346                 state = to_intel_plane_state(plane->state);
12347                 fb = state->base.fb;
12348                 if (!fb) {
12349                         DRM_DEBUG_KMS("[PLANE:%d:%s] disabled, scaler_id = %d\n",
12350                                       plane->base.id, plane->name, state->scaler_id);
12351                         continue;
12352                 }
12353
12354                 DRM_DEBUG_KMS("[PLANE:%d:%s] enabled",
12355                               plane->base.id, plane->name);
12356                 DRM_DEBUG_KMS("\tFB:%d, fb = %ux%u format = %s",
12357                               fb->base.id, fb->width, fb->height,
12358                               drm_get_format_name(fb->pixel_format));
12359                 DRM_DEBUG_KMS("\tscaler:%d src %dx%d+%d+%d dst %dx%d+%d+%d\n",
12360                               state->scaler_id,
12361                               state->src.x1 >> 16, state->src.y1 >> 16,
12362                               drm_rect_width(&state->src) >> 16,
12363                               drm_rect_height(&state->src) >> 16,
12364                               state->dst.x1, state->dst.y1,
12365                               drm_rect_width(&state->dst),
12366                               drm_rect_height(&state->dst));
12367         }
12368 }
12369
12370 static bool check_digital_port_conflicts(struct drm_atomic_state *state)
12371 {
12372         struct drm_device *dev = state->dev;
12373         struct drm_connector *connector;
12374         unsigned int used_ports = 0;
12375
12376         /*
12377          * Walk the connector list instead of the encoder
12378          * list to detect the problem on ddi platforms
12379          * where there's just one encoder per digital port.
12380          */
12381         drm_for_each_connector(connector, dev) {
12382                 struct drm_connector_state *connector_state;
12383                 struct intel_encoder *encoder;
12384
12385                 connector_state = drm_atomic_get_existing_connector_state(state, connector);
12386                 if (!connector_state)
12387                         connector_state = connector->state;
12388
12389                 if (!connector_state->best_encoder)
12390                         continue;
12391
12392                 encoder = to_intel_encoder(connector_state->best_encoder);
12393
12394                 WARN_ON(!connector_state->crtc);
12395
12396                 switch (encoder->type) {
12397                         unsigned int port_mask;
12398                 case INTEL_OUTPUT_UNKNOWN:
12399                         if (WARN_ON(!HAS_DDI(dev)))
12400                                 break;
12401                 case INTEL_OUTPUT_DP:
12402                 case INTEL_OUTPUT_HDMI:
12403                 case INTEL_OUTPUT_EDP:
12404                         port_mask = 1 << enc_to_dig_port(&encoder->base)->port;
12405
12406                         /* the same port mustn't appear more than once */
12407                         if (used_ports & port_mask)
12408                                 return false;
12409
12410                         used_ports |= port_mask;
12411                 default:
12412                         break;
12413                 }
12414         }
12415
12416         return true;
12417 }
12418
12419 static void
12420 clear_intel_crtc_state(struct intel_crtc_state *crtc_state)
12421 {
12422         struct drm_crtc_state tmp_state;
12423         struct intel_crtc_scaler_state scaler_state;
12424         struct intel_dpll_hw_state dpll_hw_state;
12425         struct intel_shared_dpll *shared_dpll;
12426         uint32_t ddi_pll_sel;
12427         bool force_thru;
12428
12429         /* FIXME: before the switch to atomic started, a new pipe_config was
12430          * kzalloc'd. Code that depends on any field being zero should be
12431          * fixed, so that the crtc_state can be safely duplicated. For now,
12432          * only fields that are know to not cause problems are preserved. */
12433
12434         tmp_state = crtc_state->base;
12435         scaler_state = crtc_state->scaler_state;
12436         shared_dpll = crtc_state->shared_dpll;
12437         dpll_hw_state = crtc_state->dpll_hw_state;
12438         ddi_pll_sel = crtc_state->ddi_pll_sel;
12439         force_thru = crtc_state->pch_pfit.force_thru;
12440
12441         memset(crtc_state, 0, sizeof *crtc_state);
12442
12443         crtc_state->base = tmp_state;
12444         crtc_state->scaler_state = scaler_state;
12445         crtc_state->shared_dpll = shared_dpll;
12446         crtc_state->dpll_hw_state = dpll_hw_state;
12447         crtc_state->ddi_pll_sel = ddi_pll_sel;
12448         crtc_state->pch_pfit.force_thru = force_thru;
12449 }
12450
12451 static int
12452 intel_modeset_pipe_config(struct drm_crtc *crtc,
12453                           struct intel_crtc_state *pipe_config)
12454 {
12455         struct drm_atomic_state *state = pipe_config->base.state;
12456         struct intel_encoder *encoder;
12457         struct drm_connector *connector;
12458         struct drm_connector_state *connector_state;
12459         int base_bpp, ret = -EINVAL;
12460         int i;
12461         bool retry = true;
12462
12463         clear_intel_crtc_state(pipe_config);
12464
12465         pipe_config->cpu_transcoder =
12466                 (enum transcoder) to_intel_crtc(crtc)->pipe;
12467
12468         /*
12469          * Sanitize sync polarity flags based on requested ones. If neither
12470          * positive or negative polarity is requested, treat this as meaning
12471          * negative polarity.
12472          */
12473         if (!(pipe_config->base.adjusted_mode.flags &
12474               (DRM_MODE_FLAG_PHSYNC | DRM_MODE_FLAG_NHSYNC)))
12475                 pipe_config->base.adjusted_mode.flags |= DRM_MODE_FLAG_NHSYNC;
12476
12477         if (!(pipe_config->base.adjusted_mode.flags &
12478               (DRM_MODE_FLAG_PVSYNC | DRM_MODE_FLAG_NVSYNC)))
12479                 pipe_config->base.adjusted_mode.flags |= DRM_MODE_FLAG_NVSYNC;
12480
12481         base_bpp = compute_baseline_pipe_bpp(to_intel_crtc(crtc),
12482                                              pipe_config);
12483         if (base_bpp < 0)
12484                 goto fail;
12485
12486         /*
12487          * Determine the real pipe dimensions. Note that stereo modes can
12488          * increase the actual pipe size due to the frame doubling and
12489          * insertion of additional space for blanks between the frame. This
12490          * is stored in the crtc timings. We use the requested mode to do this
12491          * computation to clearly distinguish it from the adjusted mode, which
12492          * can be changed by the connectors in the below retry loop.
12493          */
12494         drm_crtc_get_hv_timing(&pipe_config->base.mode,
12495                                &pipe_config->pipe_src_w,
12496                                &pipe_config->pipe_src_h);
12497
12498         for_each_connector_in_state(state, connector, connector_state, i) {
12499                 if (connector_state->crtc != crtc)
12500                         continue;
12501
12502                 encoder = to_intel_encoder(connector_state->best_encoder);
12503
12504                 if (!check_single_encoder_cloning(state, to_intel_crtc(crtc), encoder)) {
12505                         DRM_DEBUG_KMS("rejecting invalid cloning configuration\n");
12506                         goto fail;
12507                 }
12508
12509                 /*
12510                  * Determine output_types before calling the .compute_config()
12511                  * hooks so that the hooks can use this information safely.
12512                  */
12513                 pipe_config->output_types |= 1 << encoder->type;
12514         }
12515
12516 encoder_retry:
12517         /* Ensure the port clock defaults are reset when retrying. */
12518         pipe_config->port_clock = 0;
12519         pipe_config->pixel_multiplier = 1;
12520
12521         /* Fill in default crtc timings, allow encoders to overwrite them. */
12522         drm_mode_set_crtcinfo(&pipe_config->base.adjusted_mode,
12523                               CRTC_STEREO_DOUBLE);
12524
12525         /* Pass our mode to the connectors and the CRTC to give them a chance to
12526          * adjust it according to limitations or connector properties, and also
12527          * a chance to reject the mode entirely.
12528          */
12529         for_each_connector_in_state(state, connector, connector_state, i) {
12530                 if (connector_state->crtc != crtc)
12531                         continue;
12532
12533                 encoder = to_intel_encoder(connector_state->best_encoder);
12534
12535                 if (!(encoder->compute_config(encoder, pipe_config))) {
12536                         DRM_DEBUG_KMS("Encoder config failure\n");
12537                         goto fail;
12538                 }
12539         }
12540
12541         /* Set default port clock if not overwritten by the encoder. Needs to be
12542          * done afterwards in case the encoder adjusts the mode. */
12543         if (!pipe_config->port_clock)
12544                 pipe_config->port_clock = pipe_config->base.adjusted_mode.crtc_clock
12545                         * pipe_config->pixel_multiplier;
12546
12547         ret = intel_crtc_compute_config(to_intel_crtc(crtc), pipe_config);
12548         if (ret < 0) {
12549                 DRM_DEBUG_KMS("CRTC fixup failed\n");
12550                 goto fail;
12551         }
12552
12553         if (ret == RETRY) {
12554                 if (WARN(!retry, "loop in pipe configuration computation\n")) {
12555                         ret = -EINVAL;
12556                         goto fail;
12557                 }
12558
12559                 DRM_DEBUG_KMS("CRTC bw constrained, retrying\n");
12560                 retry = false;
12561                 goto encoder_retry;
12562         }
12563
12564         /* Dithering seems to not pass-through bits correctly when it should, so
12565          * only enable it on 6bpc panels. */
12566         pipe_config->dither = pipe_config->pipe_bpp == 6*3;
12567         DRM_DEBUG_KMS("hw max bpp: %i, pipe bpp: %i, dithering: %i\n",
12568                       base_bpp, pipe_config->pipe_bpp, pipe_config->dither);
12569
12570 fail:
12571         return ret;
12572 }
12573
12574 static void
12575 intel_modeset_update_crtc_state(struct drm_atomic_state *state)
12576 {
12577         struct drm_crtc *crtc;
12578         struct drm_crtc_state *crtc_state;
12579         int i;
12580
12581         /* Double check state. */
12582         for_each_crtc_in_state(state, crtc, crtc_state, i) {
12583                 to_intel_crtc(crtc)->config = to_intel_crtc_state(crtc->state);
12584
12585                 /* Update hwmode for vblank functions */
12586                 if (crtc->state->active)
12587                         crtc->hwmode = crtc->state->adjusted_mode;
12588                 else
12589                         crtc->hwmode.crtc_clock = 0;
12590
12591                 /*
12592                  * Update legacy state to satisfy fbc code. This can
12593                  * be removed when fbc uses the atomic state.
12594                  */
12595                 if (drm_atomic_get_existing_plane_state(state, crtc->primary)) {
12596                         struct drm_plane_state *plane_state = crtc->primary->state;
12597
12598                         crtc->primary->fb = plane_state->fb;
12599                         crtc->x = plane_state->src_x >> 16;
12600                         crtc->y = plane_state->src_y >> 16;
12601                 }
12602         }
12603 }
12604
12605 static bool intel_fuzzy_clock_check(int clock1, int clock2)
12606 {
12607         int diff;
12608
12609         if (clock1 == clock2)
12610                 return true;
12611
12612         if (!clock1 || !clock2)
12613                 return false;
12614
12615         diff = abs(clock1 - clock2);
12616
12617         if (((((diff + clock1 + clock2) * 100)) / (clock1 + clock2)) < 105)
12618                 return true;
12619
12620         return false;
12621 }
12622
12623 #define for_each_intel_crtc_masked(dev, mask, intel_crtc) \
12624         list_for_each_entry((intel_crtc), \
12625                             &(dev)->mode_config.crtc_list, \
12626                             base.head) \
12627                 for_each_if (mask & (1 <<(intel_crtc)->pipe))
12628
12629 static bool
12630 intel_compare_m_n(unsigned int m, unsigned int n,
12631                   unsigned int m2, unsigned int n2,
12632                   bool exact)
12633 {
12634         if (m == m2 && n == n2)
12635                 return true;
12636
12637         if (exact || !m || !n || !m2 || !n2)
12638                 return false;
12639
12640         BUILD_BUG_ON(DATA_LINK_M_N_MASK > INT_MAX);
12641
12642         if (n > n2) {
12643                 while (n > n2) {
12644                         m2 <<= 1;
12645                         n2 <<= 1;
12646                 }
12647         } else if (n < n2) {
12648                 while (n < n2) {
12649                         m <<= 1;
12650                         n <<= 1;
12651                 }
12652         }
12653
12654         if (n != n2)
12655                 return false;
12656
12657         return intel_fuzzy_clock_check(m, m2);
12658 }
12659
12660 static bool
12661 intel_compare_link_m_n(const struct intel_link_m_n *m_n,
12662                        struct intel_link_m_n *m2_n2,
12663                        bool adjust)
12664 {
12665         if (m_n->tu == m2_n2->tu &&
12666             intel_compare_m_n(m_n->gmch_m, m_n->gmch_n,
12667                               m2_n2->gmch_m, m2_n2->gmch_n, !adjust) &&
12668             intel_compare_m_n(m_n->link_m, m_n->link_n,
12669                               m2_n2->link_m, m2_n2->link_n, !adjust)) {
12670                 if (adjust)
12671                         *m2_n2 = *m_n;
12672
12673                 return true;
12674         }
12675
12676         return false;
12677 }
12678
12679 static bool
12680 intel_pipe_config_compare(struct drm_device *dev,
12681                           struct intel_crtc_state *current_config,
12682                           struct intel_crtc_state *pipe_config,
12683                           bool adjust)
12684 {
12685         bool ret = true;
12686
12687 #define INTEL_ERR_OR_DBG_KMS(fmt, ...) \
12688         do { \
12689                 if (!adjust) \
12690                         DRM_ERROR(fmt, ##__VA_ARGS__); \
12691                 else \
12692                         DRM_DEBUG_KMS(fmt, ##__VA_ARGS__); \
12693         } while (0)
12694
12695 #define PIPE_CONF_CHECK_X(name) \
12696         if (current_config->name != pipe_config->name) { \
12697                 INTEL_ERR_OR_DBG_KMS("mismatch in " #name " " \
12698                           "(expected 0x%08x, found 0x%08x)\n", \
12699                           current_config->name, \
12700                           pipe_config->name); \
12701                 ret = false; \
12702         }
12703
12704 #define PIPE_CONF_CHECK_I(name) \
12705         if (current_config->name != pipe_config->name) { \
12706                 INTEL_ERR_OR_DBG_KMS("mismatch in " #name " " \
12707                           "(expected %i, found %i)\n", \
12708                           current_config->name, \
12709                           pipe_config->name); \
12710                 ret = false; \
12711         }
12712
12713 #define PIPE_CONF_CHECK_P(name) \
12714         if (current_config->name != pipe_config->name) { \
12715                 INTEL_ERR_OR_DBG_KMS("mismatch in " #name " " \
12716                           "(expected %p, found %p)\n", \
12717                           current_config->name, \
12718                           pipe_config->name); \
12719                 ret = false; \
12720         }
12721
12722 #define PIPE_CONF_CHECK_M_N(name) \
12723         if (!intel_compare_link_m_n(&current_config->name, \
12724                                     &pipe_config->name,\
12725                                     adjust)) { \
12726                 INTEL_ERR_OR_DBG_KMS("mismatch in " #name " " \
12727                           "(expected tu %i gmch %i/%i link %i/%i, " \
12728                           "found tu %i, gmch %i/%i link %i/%i)\n", \
12729                           current_config->name.tu, \
12730                           current_config->name.gmch_m, \
12731                           current_config->name.gmch_n, \
12732                           current_config->name.link_m, \
12733                           current_config->name.link_n, \
12734                           pipe_config->name.tu, \
12735                           pipe_config->name.gmch_m, \
12736                           pipe_config->name.gmch_n, \
12737                           pipe_config->name.link_m, \
12738                           pipe_config->name.link_n); \
12739                 ret = false; \
12740         }
12741
12742 /* This is required for BDW+ where there is only one set of registers for
12743  * switching between high and low RR.
12744  * This macro can be used whenever a comparison has to be made between one
12745  * hw state and multiple sw state variables.
12746  */
12747 #define PIPE_CONF_CHECK_M_N_ALT(name, alt_name) \
12748         if (!intel_compare_link_m_n(&current_config->name, \
12749                                     &pipe_config->name, adjust) && \
12750             !intel_compare_link_m_n(&current_config->alt_name, \
12751                                     &pipe_config->name, adjust)) { \
12752                 INTEL_ERR_OR_DBG_KMS("mismatch in " #name " " \
12753                           "(expected tu %i gmch %i/%i link %i/%i, " \
12754                           "or tu %i gmch %i/%i link %i/%i, " \
12755                           "found tu %i, gmch %i/%i link %i/%i)\n", \
12756                           current_config->name.tu, \
12757                           current_config->name.gmch_m, \
12758                           current_config->name.gmch_n, \
12759                           current_config->name.link_m, \
12760                           current_config->name.link_n, \
12761                           current_config->alt_name.tu, \
12762                           current_config->alt_name.gmch_m, \
12763                           current_config->alt_name.gmch_n, \
12764                           current_config->alt_name.link_m, \
12765                           current_config->alt_name.link_n, \
12766                           pipe_config->name.tu, \
12767                           pipe_config->name.gmch_m, \
12768                           pipe_config->name.gmch_n, \
12769                           pipe_config->name.link_m, \
12770                           pipe_config->name.link_n); \
12771                 ret = false; \
12772         }
12773
12774 #define PIPE_CONF_CHECK_FLAGS(name, mask)       \
12775         if ((current_config->name ^ pipe_config->name) & (mask)) { \
12776                 INTEL_ERR_OR_DBG_KMS("mismatch in " #name "(" #mask ") " \
12777                           "(expected %i, found %i)\n", \
12778                           current_config->name & (mask), \
12779                           pipe_config->name & (mask)); \
12780                 ret = false; \
12781         }
12782
12783 #define PIPE_CONF_CHECK_CLOCK_FUZZY(name) \
12784         if (!intel_fuzzy_clock_check(current_config->name, pipe_config->name)) { \
12785                 INTEL_ERR_OR_DBG_KMS("mismatch in " #name " " \
12786                           "(expected %i, found %i)\n", \
12787                           current_config->name, \
12788                           pipe_config->name); \
12789                 ret = false; \
12790         }
12791
12792 #define PIPE_CONF_QUIRK(quirk)  \
12793         ((current_config->quirks | pipe_config->quirks) & (quirk))
12794
12795         PIPE_CONF_CHECK_I(cpu_transcoder);
12796
12797         PIPE_CONF_CHECK_I(has_pch_encoder);
12798         PIPE_CONF_CHECK_I(fdi_lanes);
12799         PIPE_CONF_CHECK_M_N(fdi_m_n);
12800
12801         PIPE_CONF_CHECK_I(lane_count);
12802         PIPE_CONF_CHECK_X(lane_lat_optim_mask);
12803
12804         if (INTEL_INFO(dev)->gen < 8) {
12805                 PIPE_CONF_CHECK_M_N(dp_m_n);
12806
12807                 if (current_config->has_drrs)
12808                         PIPE_CONF_CHECK_M_N(dp_m2_n2);
12809         } else
12810                 PIPE_CONF_CHECK_M_N_ALT(dp_m_n, dp_m2_n2);
12811
12812         PIPE_CONF_CHECK_X(output_types);
12813
12814         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hdisplay);
12815         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_htotal);
12816         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hblank_start);
12817         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hblank_end);
12818         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hsync_start);
12819         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hsync_end);
12820
12821         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vdisplay);
12822         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vtotal);
12823         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vblank_start);
12824         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vblank_end);
12825         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vsync_start);
12826         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vsync_end);
12827
12828         PIPE_CONF_CHECK_I(pixel_multiplier);
12829         PIPE_CONF_CHECK_I(has_hdmi_sink);
12830         if ((INTEL_INFO(dev)->gen < 8 && !IS_HASWELL(dev)) ||
12831             IS_VALLEYVIEW(dev) || IS_CHERRYVIEW(dev))
12832                 PIPE_CONF_CHECK_I(limited_color_range);
12833         PIPE_CONF_CHECK_I(has_infoframe);
12834
12835         PIPE_CONF_CHECK_I(has_audio);
12836
12837         PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
12838                               DRM_MODE_FLAG_INTERLACE);
12839
12840         if (!PIPE_CONF_QUIRK(PIPE_CONFIG_QUIRK_MODE_SYNC_FLAGS)) {
12841                 PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
12842                                       DRM_MODE_FLAG_PHSYNC);
12843                 PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
12844                                       DRM_MODE_FLAG_NHSYNC);
12845                 PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
12846                                       DRM_MODE_FLAG_PVSYNC);
12847                 PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
12848                                       DRM_MODE_FLAG_NVSYNC);
12849         }
12850
12851         PIPE_CONF_CHECK_X(gmch_pfit.control);
12852         /* pfit ratios are autocomputed by the hw on gen4+ */
12853         if (INTEL_INFO(dev)->gen < 4)
12854                 PIPE_CONF_CHECK_X(gmch_pfit.pgm_ratios);
12855         PIPE_CONF_CHECK_X(gmch_pfit.lvds_border_bits);
12856
12857         if (!adjust) {
12858                 PIPE_CONF_CHECK_I(pipe_src_w);
12859                 PIPE_CONF_CHECK_I(pipe_src_h);
12860
12861                 PIPE_CONF_CHECK_I(pch_pfit.enabled);
12862                 if (current_config->pch_pfit.enabled) {
12863                         PIPE_CONF_CHECK_X(pch_pfit.pos);
12864                         PIPE_CONF_CHECK_X(pch_pfit.size);
12865                 }
12866
12867                 PIPE_CONF_CHECK_I(scaler_state.scaler_id);
12868         }
12869
12870         /* BDW+ don't expose a synchronous way to read the state */
12871         if (IS_HASWELL(dev))
12872                 PIPE_CONF_CHECK_I(ips_enabled);
12873
12874         PIPE_CONF_CHECK_I(double_wide);
12875
12876         PIPE_CONF_CHECK_X(ddi_pll_sel);
12877
12878         PIPE_CONF_CHECK_P(shared_dpll);
12879         PIPE_CONF_CHECK_X(dpll_hw_state.dpll);
12880         PIPE_CONF_CHECK_X(dpll_hw_state.dpll_md);
12881         PIPE_CONF_CHECK_X(dpll_hw_state.fp0);
12882         PIPE_CONF_CHECK_X(dpll_hw_state.fp1);
12883         PIPE_CONF_CHECK_X(dpll_hw_state.wrpll);
12884         PIPE_CONF_CHECK_X(dpll_hw_state.spll);
12885         PIPE_CONF_CHECK_X(dpll_hw_state.ctrl1);
12886         PIPE_CONF_CHECK_X(dpll_hw_state.cfgcr1);
12887         PIPE_CONF_CHECK_X(dpll_hw_state.cfgcr2);
12888
12889         PIPE_CONF_CHECK_X(dsi_pll.ctrl);
12890         PIPE_CONF_CHECK_X(dsi_pll.div);
12891
12892         if (IS_G4X(dev) || INTEL_INFO(dev)->gen >= 5)
12893                 PIPE_CONF_CHECK_I(pipe_bpp);
12894
12895         PIPE_CONF_CHECK_CLOCK_FUZZY(base.adjusted_mode.crtc_clock);
12896         PIPE_CONF_CHECK_CLOCK_FUZZY(port_clock);
12897
12898 #undef PIPE_CONF_CHECK_X
12899 #undef PIPE_CONF_CHECK_I
12900 #undef PIPE_CONF_CHECK_P
12901 #undef PIPE_CONF_CHECK_FLAGS
12902 #undef PIPE_CONF_CHECK_CLOCK_FUZZY
12903 #undef PIPE_CONF_QUIRK
12904 #undef INTEL_ERR_OR_DBG_KMS
12905
12906         return ret;
12907 }
12908
12909 static void intel_pipe_config_sanity_check(struct drm_i915_private *dev_priv,
12910                                            const struct intel_crtc_state *pipe_config)
12911 {
12912         if (pipe_config->has_pch_encoder) {
12913                 int fdi_dotclock = intel_dotclock_calculate(intel_fdi_link_freq(dev_priv, pipe_config),
12914                                                             &pipe_config->fdi_m_n);
12915                 int dotclock = pipe_config->base.adjusted_mode.crtc_clock;
12916
12917                 /*
12918                  * FDI already provided one idea for the dotclock.
12919                  * Yell if the encoder disagrees.
12920                  */
12921                 WARN(!intel_fuzzy_clock_check(fdi_dotclock, dotclock),
12922                      "FDI dotclock and encoder dotclock mismatch, fdi: %i, encoder: %i\n",
12923                      fdi_dotclock, dotclock);
12924         }
12925 }
12926
12927 static void verify_wm_state(struct drm_crtc *crtc,
12928                             struct drm_crtc_state *new_state)
12929 {
12930         struct drm_device *dev = crtc->dev;
12931         struct drm_i915_private *dev_priv = to_i915(dev);
12932         struct skl_ddb_allocation hw_ddb, *sw_ddb;
12933         struct skl_ddb_entry *hw_entry, *sw_entry;
12934         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
12935         const enum pipe pipe = intel_crtc->pipe;
12936         int plane;
12937
12938         if (INTEL_INFO(dev)->gen < 9 || !new_state->active)
12939                 return;
12940
12941         skl_ddb_get_hw_state(dev_priv, &hw_ddb);
12942         sw_ddb = &dev_priv->wm.skl_hw.ddb;
12943
12944         /* planes */
12945         for_each_plane(dev_priv, pipe, plane) {
12946                 hw_entry = &hw_ddb.plane[pipe][plane];
12947                 sw_entry = &sw_ddb->plane[pipe][plane];
12948
12949                 if (skl_ddb_entry_equal(hw_entry, sw_entry))
12950                         continue;
12951
12952                 DRM_ERROR("mismatch in DDB state pipe %c plane %d "
12953                           "(expected (%u,%u), found (%u,%u))\n",
12954                           pipe_name(pipe), plane + 1,
12955                           sw_entry->start, sw_entry->end,
12956                           hw_entry->start, hw_entry->end);
12957         }
12958
12959         /* cursor */
12960         hw_entry = &hw_ddb.plane[pipe][PLANE_CURSOR];
12961         sw_entry = &sw_ddb->plane[pipe][PLANE_CURSOR];
12962
12963         if (!skl_ddb_entry_equal(hw_entry, sw_entry)) {
12964                 DRM_ERROR("mismatch in DDB state pipe %c cursor "
12965                           "(expected (%u,%u), found (%u,%u))\n",
12966                           pipe_name(pipe),
12967                           sw_entry->start, sw_entry->end,
12968                           hw_entry->start, hw_entry->end);
12969         }
12970 }
12971
12972 static void
12973 verify_connector_state(struct drm_device *dev, struct drm_crtc *crtc)
12974 {
12975         struct drm_connector *connector;
12976
12977         drm_for_each_connector(connector, dev) {
12978                 struct drm_encoder *encoder = connector->encoder;
12979                 struct drm_connector_state *state = connector->state;
12980
12981                 if (state->crtc != crtc)
12982                         continue;
12983
12984                 intel_connector_verify_state(to_intel_connector(connector));
12985
12986                 I915_STATE_WARN(state->best_encoder != encoder,
12987                      "connector's atomic encoder doesn't match legacy encoder\n");
12988         }
12989 }
12990
12991 static void
12992 verify_encoder_state(struct drm_device *dev)
12993 {
12994         struct intel_encoder *encoder;
12995         struct intel_connector *connector;
12996
12997         for_each_intel_encoder(dev, encoder) {
12998                 bool enabled = false;
12999                 enum pipe pipe;
13000
13001                 DRM_DEBUG_KMS("[ENCODER:%d:%s]\n",
13002                               encoder->base.base.id,
13003                               encoder->base.name);
13004
13005                 for_each_intel_connector(dev, connector) {
13006                         if (connector->base.state->best_encoder != &encoder->base)
13007                                 continue;
13008                         enabled = true;
13009
13010                         I915_STATE_WARN(connector->base.state->crtc !=
13011                                         encoder->base.crtc,
13012                              "connector's crtc doesn't match encoder crtc\n");
13013                 }
13014
13015                 I915_STATE_WARN(!!encoder->base.crtc != enabled,
13016                      "encoder's enabled state mismatch "
13017                      "(expected %i, found %i)\n",
13018                      !!encoder->base.crtc, enabled);
13019
13020                 if (!encoder->base.crtc) {
13021                         bool active;
13022
13023                         active = encoder->get_hw_state(encoder, &pipe);
13024                         I915_STATE_WARN(active,
13025                              "encoder detached but still enabled on pipe %c.\n",
13026                              pipe_name(pipe));
13027                 }
13028         }
13029 }
13030
13031 static void
13032 verify_crtc_state(struct drm_crtc *crtc,
13033                   struct drm_crtc_state *old_crtc_state,
13034                   struct drm_crtc_state *new_crtc_state)
13035 {
13036         struct drm_device *dev = crtc->dev;
13037         struct drm_i915_private *dev_priv = to_i915(dev);
13038         struct intel_encoder *encoder;
13039         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
13040         struct intel_crtc_state *pipe_config, *sw_config;
13041         struct drm_atomic_state *old_state;
13042         bool active;
13043
13044         old_state = old_crtc_state->state;
13045         __drm_atomic_helper_crtc_destroy_state(old_crtc_state);
13046         pipe_config = to_intel_crtc_state(old_crtc_state);
13047         memset(pipe_config, 0, sizeof(*pipe_config));
13048         pipe_config->base.crtc = crtc;
13049         pipe_config->base.state = old_state;
13050
13051         DRM_DEBUG_KMS("[CRTC:%d:%s]\n", crtc->base.id, crtc->name);
13052
13053         active = dev_priv->display.get_pipe_config(intel_crtc, pipe_config);
13054
13055         /* hw state is inconsistent with the pipe quirk */
13056         if ((intel_crtc->pipe == PIPE_A && dev_priv->quirks & QUIRK_PIPEA_FORCE) ||
13057             (intel_crtc->pipe == PIPE_B && dev_priv->quirks & QUIRK_PIPEB_FORCE))
13058                 active = new_crtc_state->active;
13059
13060         I915_STATE_WARN(new_crtc_state->active != active,
13061              "crtc active state doesn't match with hw state "
13062              "(expected %i, found %i)\n", new_crtc_state->active, active);
13063
13064         I915_STATE_WARN(intel_crtc->active != new_crtc_state->active,
13065              "transitional active state does not match atomic hw state "
13066              "(expected %i, found %i)\n", new_crtc_state->active, intel_crtc->active);
13067
13068         for_each_encoder_on_crtc(dev, crtc, encoder) {
13069                 enum pipe pipe;
13070
13071                 active = encoder->get_hw_state(encoder, &pipe);
13072                 I915_STATE_WARN(active != new_crtc_state->active,
13073                         "[ENCODER:%i] active %i with crtc active %i\n",
13074                         encoder->base.base.id, active, new_crtc_state->active);
13075
13076                 I915_STATE_WARN(active && intel_crtc->pipe != pipe,
13077                                 "Encoder connected to wrong pipe %c\n",
13078                                 pipe_name(pipe));
13079
13080                 if (active) {
13081                         pipe_config->output_types |= 1 << encoder->type;
13082                         encoder->get_config(encoder, pipe_config);
13083                 }
13084         }
13085
13086         if (!new_crtc_state->active)
13087                 return;
13088
13089         intel_pipe_config_sanity_check(dev_priv, pipe_config);
13090
13091         sw_config = to_intel_crtc_state(crtc->state);
13092         if (!intel_pipe_config_compare(dev, sw_config,
13093                                        pipe_config, false)) {
13094                 I915_STATE_WARN(1, "pipe state doesn't match!\n");
13095                 intel_dump_pipe_config(intel_crtc, pipe_config,
13096                                        "[hw state]");
13097                 intel_dump_pipe_config(intel_crtc, sw_config,
13098                                        "[sw state]");
13099         }
13100 }
13101
13102 static void
13103 verify_single_dpll_state(struct drm_i915_private *dev_priv,
13104                          struct intel_shared_dpll *pll,
13105                          struct drm_crtc *crtc,
13106                          struct drm_crtc_state *new_state)
13107 {
13108         struct intel_dpll_hw_state dpll_hw_state;
13109         unsigned crtc_mask;
13110         bool active;
13111
13112         memset(&dpll_hw_state, 0, sizeof(dpll_hw_state));
13113
13114         DRM_DEBUG_KMS("%s\n", pll->name);
13115
13116         active = pll->funcs.get_hw_state(dev_priv, pll, &dpll_hw_state);
13117
13118         if (!(pll->flags & INTEL_DPLL_ALWAYS_ON)) {
13119                 I915_STATE_WARN(!pll->on && pll->active_mask,
13120                      "pll in active use but not on in sw tracking\n");
13121                 I915_STATE_WARN(pll->on && !pll->active_mask,
13122                      "pll is on but not used by any active crtc\n");
13123                 I915_STATE_WARN(pll->on != active,
13124                      "pll on state mismatch (expected %i, found %i)\n",
13125                      pll->on, active);
13126         }
13127
13128         if (!crtc) {
13129                 I915_STATE_WARN(pll->active_mask & ~pll->config.crtc_mask,
13130                                 "more active pll users than references: %x vs %x\n",
13131                                 pll->active_mask, pll->config.crtc_mask);
13132
13133                 return;
13134         }
13135
13136         crtc_mask = 1 << drm_crtc_index(crtc);
13137
13138         if (new_state->active)
13139                 I915_STATE_WARN(!(pll->active_mask & crtc_mask),
13140                                 "pll active mismatch (expected pipe %c in active mask 0x%02x)\n",
13141                                 pipe_name(drm_crtc_index(crtc)), pll->active_mask);
13142         else
13143                 I915_STATE_WARN(pll->active_mask & crtc_mask,
13144                                 "pll active mismatch (didn't expect pipe %c in active mask 0x%02x)\n",
13145                                 pipe_name(drm_crtc_index(crtc)), pll->active_mask);
13146
13147         I915_STATE_WARN(!(pll->config.crtc_mask & crtc_mask),
13148                         "pll enabled crtcs mismatch (expected 0x%x in 0x%02x)\n",
13149                         crtc_mask, pll->config.crtc_mask);
13150
13151         I915_STATE_WARN(pll->on && memcmp(&pll->config.hw_state,
13152                                           &dpll_hw_state,
13153                                           sizeof(dpll_hw_state)),
13154                         "pll hw state mismatch\n");
13155 }
13156
13157 static void
13158 verify_shared_dpll_state(struct drm_device *dev, struct drm_crtc *crtc,
13159                          struct drm_crtc_state *old_crtc_state,
13160                          struct drm_crtc_state *new_crtc_state)
13161 {
13162         struct drm_i915_private *dev_priv = to_i915(dev);
13163         struct intel_crtc_state *old_state = to_intel_crtc_state(old_crtc_state);
13164         struct intel_crtc_state *new_state = to_intel_crtc_state(new_crtc_state);
13165
13166         if (new_state->shared_dpll)
13167                 verify_single_dpll_state(dev_priv, new_state->shared_dpll, crtc, new_crtc_state);
13168
13169         if (old_state->shared_dpll &&
13170             old_state->shared_dpll != new_state->shared_dpll) {
13171                 unsigned crtc_mask = 1 << drm_crtc_index(crtc);
13172                 struct intel_shared_dpll *pll = old_state->shared_dpll;
13173
13174                 I915_STATE_WARN(pll->active_mask & crtc_mask,
13175                                 "pll active mismatch (didn't expect pipe %c in active mask)\n",
13176                                 pipe_name(drm_crtc_index(crtc)));
13177                 I915_STATE_WARN(pll->config.crtc_mask & crtc_mask,
13178                                 "pll enabled crtcs mismatch (found %x in enabled mask)\n",
13179                                 pipe_name(drm_crtc_index(crtc)));
13180         }
13181 }
13182
13183 static void
13184 intel_modeset_verify_crtc(struct drm_crtc *crtc,
13185                          struct drm_crtc_state *old_state,
13186                          struct drm_crtc_state *new_state)
13187 {
13188         if (!needs_modeset(new_state) &&
13189             !to_intel_crtc_state(new_state)->update_pipe)
13190                 return;
13191
13192         verify_wm_state(crtc, new_state);
13193         verify_connector_state(crtc->dev, crtc);
13194         verify_crtc_state(crtc, old_state, new_state);
13195         verify_shared_dpll_state(crtc->dev, crtc, old_state, new_state);
13196 }
13197
13198 static void
13199 verify_disabled_dpll_state(struct drm_device *dev)
13200 {
13201         struct drm_i915_private *dev_priv = to_i915(dev);
13202         int i;
13203
13204         for (i = 0; i < dev_priv->num_shared_dpll; i++)
13205                 verify_single_dpll_state(dev_priv, &dev_priv->shared_dplls[i], NULL, NULL);
13206 }
13207
13208 static void
13209 intel_modeset_verify_disabled(struct drm_device *dev)
13210 {
13211         verify_encoder_state(dev);
13212         verify_connector_state(dev, NULL);
13213         verify_disabled_dpll_state(dev);
13214 }
13215
13216 static void update_scanline_offset(struct intel_crtc *crtc)
13217 {
13218         struct drm_device *dev = crtc->base.dev;
13219
13220         /*
13221          * The scanline counter increments at the leading edge of hsync.
13222          *
13223          * On most platforms it starts counting from vtotal-1 on the
13224          * first active line. That means the scanline counter value is
13225          * always one less than what we would expect. Ie. just after
13226          * start of vblank, which also occurs at start of hsync (on the
13227          * last active line), the scanline counter will read vblank_start-1.
13228          *
13229          * On gen2 the scanline counter starts counting from 1 instead
13230          * of vtotal-1, so we have to subtract one (or rather add vtotal-1
13231          * to keep the value positive), instead of adding one.
13232          *
13233          * On HSW+ the behaviour of the scanline counter depends on the output
13234          * type. For DP ports it behaves like most other platforms, but on HDMI
13235          * there's an extra 1 line difference. So we need to add two instead of
13236          * one to the value.
13237          */
13238         if (IS_GEN2(dev)) {
13239                 const struct drm_display_mode *adjusted_mode = &crtc->config->base.adjusted_mode;
13240                 int vtotal;
13241
13242                 vtotal = adjusted_mode->crtc_vtotal;
13243                 if (adjusted_mode->flags & DRM_MODE_FLAG_INTERLACE)
13244                         vtotal /= 2;
13245
13246                 crtc->scanline_offset = vtotal - 1;
13247         } else if (HAS_DDI(dev) &&
13248                    intel_crtc_has_type(crtc->config, INTEL_OUTPUT_HDMI)) {
13249                 crtc->scanline_offset = 2;
13250         } else
13251                 crtc->scanline_offset = 1;
13252 }
13253
13254 static void intel_modeset_clear_plls(struct drm_atomic_state *state)
13255 {
13256         struct drm_device *dev = state->dev;
13257         struct drm_i915_private *dev_priv = to_i915(dev);
13258         struct intel_shared_dpll_config *shared_dpll = NULL;
13259         struct drm_crtc *crtc;
13260         struct drm_crtc_state *crtc_state;
13261         int i;
13262
13263         if (!dev_priv->display.crtc_compute_clock)
13264                 return;
13265
13266         for_each_crtc_in_state(state, crtc, crtc_state, i) {
13267                 struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
13268                 struct intel_shared_dpll *old_dpll =
13269                         to_intel_crtc_state(crtc->state)->shared_dpll;
13270
13271                 if (!needs_modeset(crtc_state))
13272                         continue;
13273
13274                 to_intel_crtc_state(crtc_state)->shared_dpll = NULL;
13275
13276                 if (!old_dpll)
13277                         continue;
13278
13279                 if (!shared_dpll)
13280                         shared_dpll = intel_atomic_get_shared_dpll_state(state);
13281
13282                 intel_shared_dpll_config_put(shared_dpll, old_dpll, intel_crtc);
13283         }
13284 }
13285
13286 /*
13287  * This implements the workaround described in the "notes" section of the mode
13288  * set sequence documentation. When going from no pipes or single pipe to
13289  * multiple pipes, and planes are enabled after the pipe, we need to wait at
13290  * least 2 vblanks on the first pipe before enabling planes on the second pipe.
13291  */
13292 static int haswell_mode_set_planes_workaround(struct drm_atomic_state *state)
13293 {
13294         struct drm_crtc_state *crtc_state;
13295         struct intel_crtc *intel_crtc;
13296         struct drm_crtc *crtc;
13297         struct intel_crtc_state *first_crtc_state = NULL;
13298         struct intel_crtc_state *other_crtc_state = NULL;
13299         enum pipe first_pipe = INVALID_PIPE, enabled_pipe = INVALID_PIPE;
13300         int i;
13301
13302         /* look at all crtc's that are going to be enabled in during modeset */
13303         for_each_crtc_in_state(state, crtc, crtc_state, i) {
13304                 intel_crtc = to_intel_crtc(crtc);
13305
13306                 if (!crtc_state->active || !needs_modeset(crtc_state))
13307                         continue;
13308
13309                 if (first_crtc_state) {
13310                         other_crtc_state = to_intel_crtc_state(crtc_state);
13311                         break;
13312                 } else {
13313                         first_crtc_state = to_intel_crtc_state(crtc_state);
13314                         first_pipe = intel_crtc->pipe;
13315                 }
13316         }
13317
13318         /* No workaround needed? */
13319         if (!first_crtc_state)
13320                 return 0;
13321
13322         /* w/a possibly needed, check how many crtc's are already enabled. */
13323         for_each_intel_crtc(state->dev, intel_crtc) {
13324                 struct intel_crtc_state *pipe_config;
13325
13326                 pipe_config = intel_atomic_get_crtc_state(state, intel_crtc);
13327                 if (IS_ERR(pipe_config))
13328                         return PTR_ERR(pipe_config);
13329
13330                 pipe_config->hsw_workaround_pipe = INVALID_PIPE;
13331
13332                 if (!pipe_config->base.active ||
13333                     needs_modeset(&pipe_config->base))
13334                         continue;
13335
13336                 /* 2 or more enabled crtcs means no need for w/a */
13337                 if (enabled_pipe != INVALID_PIPE)
13338                         return 0;
13339
13340                 enabled_pipe = intel_crtc->pipe;
13341         }
13342
13343         if (enabled_pipe != INVALID_PIPE)
13344                 first_crtc_state->hsw_workaround_pipe = enabled_pipe;
13345         else if (other_crtc_state)
13346                 other_crtc_state->hsw_workaround_pipe = first_pipe;
13347
13348         return 0;
13349 }
13350
13351 static int intel_modeset_all_pipes(struct drm_atomic_state *state)
13352 {
13353         struct drm_crtc *crtc;
13354         struct drm_crtc_state *crtc_state;
13355         int ret = 0;
13356
13357         /* add all active pipes to the state */
13358         for_each_crtc(state->dev, crtc) {
13359                 crtc_state = drm_atomic_get_crtc_state(state, crtc);
13360                 if (IS_ERR(crtc_state))
13361                         return PTR_ERR(crtc_state);
13362
13363                 if (!crtc_state->active || needs_modeset(crtc_state))
13364                         continue;
13365
13366                 crtc_state->mode_changed = true;
13367
13368                 ret = drm_atomic_add_affected_connectors(state, crtc);
13369                 if (ret)
13370                         break;
13371
13372                 ret = drm_atomic_add_affected_planes(state, crtc);
13373                 if (ret)
13374                         break;
13375         }
13376
13377         return ret;
13378 }
13379
13380 static int intel_modeset_checks(struct drm_atomic_state *state)
13381 {
13382         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
13383         struct drm_i915_private *dev_priv = to_i915(state->dev);
13384         struct drm_crtc *crtc;
13385         struct drm_crtc_state *crtc_state;
13386         int ret = 0, i;
13387
13388         if (!check_digital_port_conflicts(state)) {
13389                 DRM_DEBUG_KMS("rejecting conflicting digital port configuration\n");
13390                 return -EINVAL;
13391         }
13392
13393         intel_state->modeset = true;
13394         intel_state->active_crtcs = dev_priv->active_crtcs;
13395
13396         for_each_crtc_in_state(state, crtc, crtc_state, i) {
13397                 if (crtc_state->active)
13398                         intel_state->active_crtcs |= 1 << i;
13399                 else
13400                         intel_state->active_crtcs &= ~(1 << i);
13401
13402                 if (crtc_state->active != crtc->state->active)
13403                         intel_state->active_pipe_changes |= drm_crtc_mask(crtc);
13404         }
13405
13406         /*
13407          * See if the config requires any additional preparation, e.g.
13408          * to adjust global state with pipes off.  We need to do this
13409          * here so we can get the modeset_pipe updated config for the new
13410          * mode set on this crtc.  For other crtcs we need to use the
13411          * adjusted_mode bits in the crtc directly.
13412          */
13413         if (dev_priv->display.modeset_calc_cdclk) {
13414                 if (!intel_state->cdclk_pll_vco)
13415                         intel_state->cdclk_pll_vco = dev_priv->cdclk_pll.vco;
13416                 if (!intel_state->cdclk_pll_vco)
13417                         intel_state->cdclk_pll_vco = dev_priv->skl_preferred_vco_freq;
13418
13419                 ret = dev_priv->display.modeset_calc_cdclk(state);
13420                 if (ret < 0)
13421                         return ret;
13422
13423                 if (intel_state->dev_cdclk != dev_priv->cdclk_freq ||
13424                     intel_state->cdclk_pll_vco != dev_priv->cdclk_pll.vco)
13425                         ret = intel_modeset_all_pipes(state);
13426
13427                 if (ret < 0)
13428                         return ret;
13429
13430                 DRM_DEBUG_KMS("New cdclk calculated to be atomic %u, actual %u\n",
13431                               intel_state->cdclk, intel_state->dev_cdclk);
13432         } else
13433                 to_intel_atomic_state(state)->cdclk = dev_priv->atomic_cdclk_freq;
13434
13435         intel_modeset_clear_plls(state);
13436
13437         if (IS_HASWELL(dev_priv))
13438                 return haswell_mode_set_planes_workaround(state);
13439
13440         return 0;
13441 }
13442
13443 /*
13444  * Handle calculation of various watermark data at the end of the atomic check
13445  * phase.  The code here should be run after the per-crtc and per-plane 'check'
13446  * handlers to ensure that all derived state has been updated.
13447  */
13448 static int calc_watermark_data(struct drm_atomic_state *state)
13449 {
13450         struct drm_device *dev = state->dev;
13451         struct drm_i915_private *dev_priv = to_i915(dev);
13452
13453         /* Is there platform-specific watermark information to calculate? */
13454         if (dev_priv->display.compute_global_watermarks)
13455                 return dev_priv->display.compute_global_watermarks(state);
13456
13457         return 0;
13458 }
13459
13460 /**
13461  * intel_atomic_check - validate state object
13462  * @dev: drm device
13463  * @state: state to validate
13464  */
13465 static int intel_atomic_check(struct drm_device *dev,
13466                               struct drm_atomic_state *state)
13467 {
13468         struct drm_i915_private *dev_priv = to_i915(dev);
13469         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
13470         struct drm_crtc *crtc;
13471         struct drm_crtc_state *crtc_state;
13472         int ret, i;
13473         bool any_ms = false;
13474
13475         ret = drm_atomic_helper_check_modeset(dev, state);
13476         if (ret)
13477                 return ret;
13478
13479         for_each_crtc_in_state(state, crtc, crtc_state, i) {
13480                 struct intel_crtc_state *pipe_config =
13481                         to_intel_crtc_state(crtc_state);
13482
13483                 /* Catch I915_MODE_FLAG_INHERITED */
13484                 if (crtc_state->mode.private_flags != crtc->state->mode.private_flags)
13485                         crtc_state->mode_changed = true;
13486
13487                 if (!needs_modeset(crtc_state))
13488                         continue;
13489
13490                 if (!crtc_state->enable) {
13491                         any_ms = true;
13492                         continue;
13493                 }
13494
13495                 /* FIXME: For only active_changed we shouldn't need to do any
13496                  * state recomputation at all. */
13497
13498                 ret = drm_atomic_add_affected_connectors(state, crtc);
13499                 if (ret)
13500                         return ret;
13501
13502                 ret = intel_modeset_pipe_config(crtc, pipe_config);
13503                 if (ret) {
13504                         intel_dump_pipe_config(to_intel_crtc(crtc),
13505                                                pipe_config, "[failed]");
13506                         return ret;
13507                 }
13508
13509                 if (i915.fastboot &&
13510                     intel_pipe_config_compare(dev,
13511                                         to_intel_crtc_state(crtc->state),
13512                                         pipe_config, true)) {
13513                         crtc_state->mode_changed = false;
13514                         to_intel_crtc_state(crtc_state)->update_pipe = true;
13515                 }
13516
13517                 if (needs_modeset(crtc_state))
13518                         any_ms = true;
13519
13520                 ret = drm_atomic_add_affected_planes(state, crtc);
13521                 if (ret)
13522                         return ret;
13523
13524                 intel_dump_pipe_config(to_intel_crtc(crtc), pipe_config,
13525                                        needs_modeset(crtc_state) ?
13526                                        "[modeset]" : "[fastset]");
13527         }
13528
13529         if (any_ms) {
13530                 ret = intel_modeset_checks(state);
13531
13532                 if (ret)
13533                         return ret;
13534         } else
13535                 intel_state->cdclk = dev_priv->cdclk_freq;
13536
13537         ret = drm_atomic_helper_check_planes(dev, state);
13538         if (ret)
13539                 return ret;
13540
13541         intel_fbc_choose_crtc(dev_priv, state);
13542         return calc_watermark_data(state);
13543 }
13544
13545 static int intel_atomic_prepare_commit(struct drm_device *dev,
13546                                        struct drm_atomic_state *state,
13547                                        bool nonblock)
13548 {
13549         struct drm_i915_private *dev_priv = to_i915(dev);
13550         struct drm_plane_state *plane_state;
13551         struct drm_crtc_state *crtc_state;
13552         struct drm_plane *plane;
13553         struct drm_crtc *crtc;
13554         int i, ret;
13555
13556         for_each_crtc_in_state(state, crtc, crtc_state, i) {
13557                 if (state->legacy_cursor_update)
13558                         continue;
13559
13560                 ret = intel_crtc_wait_for_pending_flips(crtc);
13561                 if (ret)
13562                         return ret;
13563
13564                 if (atomic_read(&to_intel_crtc(crtc)->unpin_work_count) >= 2)
13565                         flush_workqueue(dev_priv->wq);
13566         }
13567
13568         ret = mutex_lock_interruptible(&dev->struct_mutex);
13569         if (ret)
13570                 return ret;
13571
13572         ret = drm_atomic_helper_prepare_planes(dev, state);
13573         mutex_unlock(&dev->struct_mutex);
13574
13575         if (!ret && !nonblock) {
13576                 for_each_plane_in_state(state, plane, plane_state, i) {
13577                         struct intel_plane_state *intel_plane_state =
13578                                 to_intel_plane_state(plane_state);
13579
13580                         if (!intel_plane_state->wait_req)
13581                                 continue;
13582
13583                         ret = __i915_wait_request(intel_plane_state->wait_req,
13584                                                   true, NULL, NULL);
13585                         if (ret) {
13586                                 /* Any hang should be swallowed by the wait */
13587                                 WARN_ON(ret == -EIO);
13588                                 mutex_lock(&dev->struct_mutex);
13589                                 drm_atomic_helper_cleanup_planes(dev, state);
13590                                 mutex_unlock(&dev->struct_mutex);
13591                                 break;
13592                         }
13593                 }
13594         }
13595
13596         return ret;
13597 }
13598
13599 u32 intel_crtc_get_vblank_counter(struct intel_crtc *crtc)
13600 {
13601         struct drm_device *dev = crtc->base.dev;
13602
13603         if (!dev->max_vblank_count)
13604                 return drm_accurate_vblank_count(&crtc->base);
13605
13606         return dev->driver->get_vblank_counter(dev, crtc->pipe);
13607 }
13608
13609 static void intel_atomic_wait_for_vblanks(struct drm_device *dev,
13610                                           struct drm_i915_private *dev_priv,
13611                                           unsigned crtc_mask)
13612 {
13613         unsigned last_vblank_count[I915_MAX_PIPES];
13614         enum pipe pipe;
13615         int ret;
13616
13617         if (!crtc_mask)
13618                 return;
13619
13620         for_each_pipe(dev_priv, pipe) {
13621                 struct drm_crtc *crtc = dev_priv->pipe_to_crtc_mapping[pipe];
13622
13623                 if (!((1 << pipe) & crtc_mask))
13624                         continue;
13625
13626                 ret = drm_crtc_vblank_get(crtc);
13627                 if (WARN_ON(ret != 0)) {
13628                         crtc_mask &= ~(1 << pipe);
13629                         continue;
13630                 }
13631
13632                 last_vblank_count[pipe] = drm_crtc_vblank_count(crtc);
13633         }
13634
13635         for_each_pipe(dev_priv, pipe) {
13636                 struct drm_crtc *crtc = dev_priv->pipe_to_crtc_mapping[pipe];
13637                 long lret;
13638
13639                 if (!((1 << pipe) & crtc_mask))
13640                         continue;
13641
13642                 lret = wait_event_timeout(dev->vblank[pipe].queue,
13643                                 last_vblank_count[pipe] !=
13644                                         drm_crtc_vblank_count(crtc),
13645                                 msecs_to_jiffies(50));
13646
13647                 WARN(!lret, "pipe %c vblank wait timed out\n", pipe_name(pipe));
13648
13649                 drm_crtc_vblank_put(crtc);
13650         }
13651 }
13652
13653 static bool needs_vblank_wait(struct intel_crtc_state *crtc_state)
13654 {
13655         /* fb updated, need to unpin old fb */
13656         if (crtc_state->fb_changed)
13657                 return true;
13658
13659         /* wm changes, need vblank before final wm's */
13660         if (crtc_state->update_wm_post)
13661                 return true;
13662
13663         /*
13664          * cxsr is re-enabled after vblank.
13665          * This is already handled by crtc_state->update_wm_post,
13666          * but added for clarity.
13667          */
13668         if (crtc_state->disable_cxsr)
13669                 return true;
13670
13671         return false;
13672 }
13673
13674 static void intel_atomic_commit_tail(struct drm_atomic_state *state)
13675 {
13676         struct drm_device *dev = state->dev;
13677         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
13678         struct drm_i915_private *dev_priv = to_i915(dev);
13679         struct drm_crtc_state *old_crtc_state;
13680         struct drm_crtc *crtc;
13681         struct intel_crtc_state *intel_cstate;
13682         struct drm_plane *plane;
13683         struct drm_plane_state *plane_state;
13684         bool hw_check = intel_state->modeset;
13685         unsigned long put_domains[I915_MAX_PIPES] = {};
13686         unsigned crtc_vblank_mask = 0;
13687         int i, ret;
13688
13689         for_each_plane_in_state(state, plane, plane_state, i) {
13690                 struct intel_plane_state *intel_plane_state =
13691                         to_intel_plane_state(plane_state);
13692
13693                 if (!intel_plane_state->wait_req)
13694                         continue;
13695
13696                 ret = __i915_wait_request(intel_plane_state->wait_req,
13697                                           true, NULL, NULL);
13698                 /* EIO should be eaten, and we can't get interrupted in the
13699                  * worker, and blocking commits have waited already. */
13700                 WARN_ON(ret);
13701         }
13702
13703         drm_atomic_helper_wait_for_dependencies(state);
13704
13705         if (intel_state->modeset) {
13706                 memcpy(dev_priv->min_pixclk, intel_state->min_pixclk,
13707                        sizeof(intel_state->min_pixclk));
13708                 dev_priv->active_crtcs = intel_state->active_crtcs;
13709                 dev_priv->atomic_cdclk_freq = intel_state->cdclk;
13710
13711                 intel_display_power_get(dev_priv, POWER_DOMAIN_MODESET);
13712         }
13713
13714         for_each_crtc_in_state(state, crtc, old_crtc_state, i) {
13715                 struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
13716
13717                 if (needs_modeset(crtc->state) ||
13718                     to_intel_crtc_state(crtc->state)->update_pipe) {
13719                         hw_check = true;
13720
13721                         put_domains[to_intel_crtc(crtc)->pipe] =
13722                                 modeset_get_crtc_power_domains(crtc,
13723                                         to_intel_crtc_state(crtc->state));
13724                 }
13725
13726                 if (!needs_modeset(crtc->state))
13727                         continue;
13728
13729                 intel_pre_plane_update(to_intel_crtc_state(old_crtc_state));
13730
13731                 if (old_crtc_state->active) {
13732                         intel_crtc_disable_planes(crtc, old_crtc_state->plane_mask);
13733                         dev_priv->display.crtc_disable(crtc);
13734                         intel_crtc->active = false;
13735                         intel_fbc_disable(intel_crtc);
13736                         intel_disable_shared_dpll(intel_crtc);
13737
13738                         /*
13739                          * Underruns don't always raise
13740                          * interrupts, so check manually.
13741                          */
13742                         intel_check_cpu_fifo_underruns(dev_priv);
13743                         intel_check_pch_fifo_underruns(dev_priv);
13744
13745                         if (!crtc->state->active)
13746                                 intel_update_watermarks(crtc);
13747                 }
13748         }
13749
13750         /* Only after disabling all output pipelines that will be changed can we
13751          * update the the output configuration. */
13752         intel_modeset_update_crtc_state(state);
13753
13754         if (intel_state->modeset) {
13755                 drm_atomic_helper_update_legacy_modeset_state(state->dev, state);
13756
13757                 if (dev_priv->display.modeset_commit_cdclk &&
13758                     (intel_state->dev_cdclk != dev_priv->cdclk_freq ||
13759                      intel_state->cdclk_pll_vco != dev_priv->cdclk_pll.vco))
13760                         dev_priv->display.modeset_commit_cdclk(state);
13761
13762                 intel_modeset_verify_disabled(dev);
13763         }
13764
13765         /* Now enable the clocks, plane, pipe, and connectors that we set up. */
13766         for_each_crtc_in_state(state, crtc, old_crtc_state, i) {
13767                 struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
13768                 bool modeset = needs_modeset(crtc->state);
13769                 struct intel_crtc_state *pipe_config =
13770                         to_intel_crtc_state(crtc->state);
13771
13772                 if (modeset && crtc->state->active) {
13773                         update_scanline_offset(to_intel_crtc(crtc));
13774                         dev_priv->display.crtc_enable(crtc);
13775                 }
13776
13777                 /* Complete events for now disable pipes here. */
13778                 if (modeset && !crtc->state->active && crtc->state->event) {
13779                         spin_lock_irq(&dev->event_lock);
13780                         drm_crtc_send_vblank_event(crtc, crtc->state->event);
13781                         spin_unlock_irq(&dev->event_lock);
13782
13783                         crtc->state->event = NULL;
13784                 }
13785
13786                 if (!modeset)
13787                         intel_pre_plane_update(to_intel_crtc_state(old_crtc_state));
13788
13789                 if (crtc->state->active &&
13790                     drm_atomic_get_existing_plane_state(state, crtc->primary))
13791                         intel_fbc_enable(intel_crtc, pipe_config, to_intel_plane_state(crtc->primary->state));
13792
13793                 if (crtc->state->active)
13794                         drm_atomic_helper_commit_planes_on_crtc(old_crtc_state);
13795
13796                 if (pipe_config->base.active && needs_vblank_wait(pipe_config))
13797                         crtc_vblank_mask |= 1 << i;
13798         }
13799
13800         /* FIXME: We should call drm_atomic_helper_commit_hw_done() here
13801          * already, but still need the state for the delayed optimization. To
13802          * fix this:
13803          * - wrap the optimization/post_plane_update stuff into a per-crtc work.
13804          * - schedule that vblank worker _before_ calling hw_done
13805          * - at the start of commit_tail, cancel it _synchrously
13806          * - switch over to the vblank wait helper in the core after that since
13807          *   we don't need out special handling any more.
13808          */
13809         if (!state->legacy_cursor_update)
13810                 intel_atomic_wait_for_vblanks(dev, dev_priv, crtc_vblank_mask);
13811
13812         /*
13813          * Now that the vblank has passed, we can go ahead and program the
13814          * optimal watermarks on platforms that need two-step watermark
13815          * programming.
13816          *
13817          * TODO: Move this (and other cleanup) to an async worker eventually.
13818          */
13819         for_each_crtc_in_state(state, crtc, old_crtc_state, i) {
13820                 intel_cstate = to_intel_crtc_state(crtc->state);
13821
13822                 if (dev_priv->display.optimize_watermarks)
13823                         dev_priv->display.optimize_watermarks(intel_cstate);
13824         }
13825
13826         for_each_crtc_in_state(state, crtc, old_crtc_state, i) {
13827                 intel_post_plane_update(to_intel_crtc_state(old_crtc_state));
13828
13829                 if (put_domains[i])
13830                         modeset_put_power_domains(dev_priv, put_domains[i]);
13831
13832                 intel_modeset_verify_crtc(crtc, old_crtc_state, crtc->state);
13833         }
13834
13835         drm_atomic_helper_commit_hw_done(state);
13836
13837         if (intel_state->modeset)
13838                 intel_display_power_put(dev_priv, POWER_DOMAIN_MODESET);
13839
13840         mutex_lock(&dev->struct_mutex);
13841         drm_atomic_helper_cleanup_planes(dev, state);
13842         mutex_unlock(&dev->struct_mutex);
13843
13844         drm_atomic_helper_commit_cleanup_done(state);
13845
13846         drm_atomic_state_free(state);
13847
13848         /* As one of the primary mmio accessors, KMS has a high likelihood
13849          * of triggering bugs in unclaimed access. After we finish
13850          * modesetting, see if an error has been flagged, and if so
13851          * enable debugging for the next modeset - and hope we catch
13852          * the culprit.
13853          *
13854          * XXX note that we assume display power is on at this point.
13855          * This might hold true now but we need to add pm helper to check
13856          * unclaimed only when the hardware is on, as atomic commits
13857          * can happen also when the device is completely off.
13858          */
13859         intel_uncore_arm_unclaimed_mmio_detection(dev_priv);
13860 }
13861
13862 static void intel_atomic_commit_work(struct work_struct *work)
13863 {
13864         struct drm_atomic_state *state = container_of(work,
13865                                                       struct drm_atomic_state,
13866                                                       commit_work);
13867         intel_atomic_commit_tail(state);
13868 }
13869
13870 static void intel_atomic_track_fbs(struct drm_atomic_state *state)
13871 {
13872         struct drm_plane_state *old_plane_state;
13873         struct drm_plane *plane;
13874         struct drm_i915_gem_object *obj, *old_obj;
13875         struct intel_plane *intel_plane;
13876         int i;
13877
13878         mutex_lock(&state->dev->struct_mutex);
13879         for_each_plane_in_state(state, plane, old_plane_state, i) {
13880                 obj = intel_fb_obj(plane->state->fb);
13881                 old_obj = intel_fb_obj(old_plane_state->fb);
13882                 intel_plane = to_intel_plane(plane);
13883
13884                 i915_gem_track_fb(old_obj, obj, intel_plane->frontbuffer_bit);
13885         }
13886         mutex_unlock(&state->dev->struct_mutex);
13887 }
13888
13889 /**
13890  * intel_atomic_commit - commit validated state object
13891  * @dev: DRM device
13892  * @state: the top-level driver state object
13893  * @nonblock: nonblocking commit
13894  *
13895  * This function commits a top-level state object that has been validated
13896  * with drm_atomic_helper_check().
13897  *
13898  * FIXME:  Atomic modeset support for i915 is not yet complete.  At the moment
13899  * nonblocking commits are only safe for pure plane updates. Everything else
13900  * should work though.
13901  *
13902  * RETURNS
13903  * Zero for success or -errno.
13904  */
13905 static int intel_atomic_commit(struct drm_device *dev,
13906                                struct drm_atomic_state *state,
13907                                bool nonblock)
13908 {
13909         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
13910         struct drm_i915_private *dev_priv = to_i915(dev);
13911         int ret = 0;
13912
13913         if (intel_state->modeset && nonblock) {
13914                 DRM_DEBUG_KMS("nonblocking commit for modeset not yet implemented.\n");
13915                 return -EINVAL;
13916         }
13917
13918         ret = drm_atomic_helper_setup_commit(state, nonblock);
13919         if (ret)
13920                 return ret;
13921
13922         INIT_WORK(&state->commit_work, intel_atomic_commit_work);
13923
13924         ret = intel_atomic_prepare_commit(dev, state, nonblock);
13925         if (ret) {
13926                 DRM_DEBUG_ATOMIC("Preparing state failed with %i\n", ret);
13927                 return ret;
13928         }
13929
13930         drm_atomic_helper_swap_state(state, true);
13931         dev_priv->wm.distrust_bios_wm = false;
13932         dev_priv->wm.skl_results = intel_state->wm_results;
13933         intel_shared_dpll_commit(state);
13934         intel_atomic_track_fbs(state);
13935
13936         if (nonblock)
13937                 queue_work(system_unbound_wq, &state->commit_work);
13938         else
13939                 intel_atomic_commit_tail(state);
13940
13941         return 0;
13942 }
13943
13944 void intel_crtc_restore_mode(struct drm_crtc *crtc)
13945 {
13946         struct drm_device *dev = crtc->dev;
13947         struct drm_atomic_state *state;
13948         struct drm_crtc_state *crtc_state;
13949         int ret;
13950
13951         state = drm_atomic_state_alloc(dev);
13952         if (!state) {
13953                 DRM_DEBUG_KMS("[CRTC:%d:%s] crtc restore failed, out of memory",
13954                               crtc->base.id, crtc->name);
13955                 return;
13956         }
13957
13958         state->acquire_ctx = drm_modeset_legacy_acquire_ctx(crtc);
13959
13960 retry:
13961         crtc_state = drm_atomic_get_crtc_state(state, crtc);
13962         ret = PTR_ERR_OR_ZERO(crtc_state);
13963         if (!ret) {
13964                 if (!crtc_state->active)
13965                         goto out;
13966
13967                 crtc_state->mode_changed = true;
13968                 ret = drm_atomic_commit(state);
13969         }
13970
13971         if (ret == -EDEADLK) {
13972                 drm_atomic_state_clear(state);
13973                 drm_modeset_backoff(state->acquire_ctx);
13974                 goto retry;
13975         }
13976
13977         if (ret)
13978 out:
13979                 drm_atomic_state_free(state);
13980 }
13981
13982 #undef for_each_intel_crtc_masked
13983
13984 /*
13985  * FIXME: Remove this once i915 is fully DRIVER_ATOMIC by calling
13986  *        drm_atomic_helper_legacy_gamma_set() directly.
13987  */
13988 static int intel_atomic_legacy_gamma_set(struct drm_crtc *crtc,
13989                                          u16 *red, u16 *green, u16 *blue,
13990                                          uint32_t size)
13991 {
13992         struct drm_device *dev = crtc->dev;
13993         struct drm_mode_config *config = &dev->mode_config;
13994         struct drm_crtc_state *state;
13995         int ret;
13996
13997         ret = drm_atomic_helper_legacy_gamma_set(crtc, red, green, blue, size);
13998         if (ret)
13999                 return ret;
14000
14001         /*
14002          * Make sure we update the legacy properties so this works when
14003          * atomic is not enabled.
14004          */
14005
14006         state = crtc->state;
14007
14008         drm_object_property_set_value(&crtc->base,
14009                                       config->degamma_lut_property,
14010                                       (state->degamma_lut) ?
14011                                       state->degamma_lut->base.id : 0);
14012
14013         drm_object_property_set_value(&crtc->base,
14014                                       config->ctm_property,
14015                                       (state->ctm) ?
14016                                       state->ctm->base.id : 0);
14017
14018         drm_object_property_set_value(&crtc->base,
14019                                       config->gamma_lut_property,
14020                                       (state->gamma_lut) ?
14021                                       state->gamma_lut->base.id : 0);
14022
14023         return 0;
14024 }
14025
14026 static const struct drm_crtc_funcs intel_crtc_funcs = {
14027         .gamma_set = intel_atomic_legacy_gamma_set,
14028         .set_config = drm_atomic_helper_set_config,
14029         .set_property = drm_atomic_helper_crtc_set_property,
14030         .destroy = intel_crtc_destroy,
14031         .page_flip = intel_crtc_page_flip,
14032         .atomic_duplicate_state = intel_crtc_duplicate_state,
14033         .atomic_destroy_state = intel_crtc_destroy_state,
14034 };
14035
14036 /**
14037  * intel_prepare_plane_fb - Prepare fb for usage on plane
14038  * @plane: drm plane to prepare for
14039  * @fb: framebuffer to prepare for presentation
14040  *
14041  * Prepares a framebuffer for usage on a display plane.  Generally this
14042  * involves pinning the underlying object and updating the frontbuffer tracking
14043  * bits.  Some older platforms need special physical address handling for
14044  * cursor planes.
14045  *
14046  * Must be called with struct_mutex held.
14047  *
14048  * Returns 0 on success, negative error code on failure.
14049  */
14050 int
14051 intel_prepare_plane_fb(struct drm_plane *plane,
14052                        const struct drm_plane_state *new_state)
14053 {
14054         struct drm_device *dev = plane->dev;
14055         struct drm_framebuffer *fb = new_state->fb;
14056         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
14057         struct drm_i915_gem_object *old_obj = intel_fb_obj(plane->state->fb);
14058         struct reservation_object *resv;
14059         int ret = 0;
14060
14061         if (!obj && !old_obj)
14062                 return 0;
14063
14064         if (old_obj) {
14065                 struct drm_crtc_state *crtc_state =
14066                         drm_atomic_get_existing_crtc_state(new_state->state, plane->state->crtc);
14067
14068                 /* Big Hammer, we also need to ensure that any pending
14069                  * MI_WAIT_FOR_EVENT inside a user batch buffer on the
14070                  * current scanout is retired before unpinning the old
14071                  * framebuffer. Note that we rely on userspace rendering
14072                  * into the buffer attached to the pipe they are waiting
14073                  * on. If not, userspace generates a GPU hang with IPEHR
14074                  * point to the MI_WAIT_FOR_EVENT.
14075                  *
14076                  * This should only fail upon a hung GPU, in which case we
14077                  * can safely continue.
14078                  */
14079                 if (needs_modeset(crtc_state))
14080                         ret = i915_gem_object_wait_rendering(old_obj, true);
14081                 if (ret) {
14082                         /* GPU hangs should have been swallowed by the wait */
14083                         WARN_ON(ret == -EIO);
14084                         return ret;
14085                 }
14086         }
14087
14088         if (!obj)
14089                 return 0;
14090
14091         /* For framebuffer backed by dmabuf, wait for fence */
14092         resv = i915_gem_object_get_dmabuf_resv(obj);
14093         if (resv) {
14094                 long lret;
14095
14096                 lret = reservation_object_wait_timeout_rcu(resv, false, true,
14097                                                            MAX_SCHEDULE_TIMEOUT);
14098                 if (lret == -ERESTARTSYS)
14099                         return lret;
14100
14101                 WARN(lret < 0, "waiting returns %li\n", lret);
14102         }
14103
14104         if (plane->type == DRM_PLANE_TYPE_CURSOR &&
14105             INTEL_INFO(dev)->cursor_needs_physical) {
14106                 int align = IS_I830(dev) ? 16 * 1024 : 256;
14107                 ret = i915_gem_object_attach_phys(obj, align);
14108                 if (ret)
14109                         DRM_DEBUG_KMS("failed to attach phys object\n");
14110         } else {
14111                 ret = intel_pin_and_fence_fb_obj(fb, new_state->rotation);
14112         }
14113
14114         if (ret == 0) {
14115                 struct intel_plane_state *plane_state =
14116                         to_intel_plane_state(new_state);
14117
14118                 i915_gem_request_assign(&plane_state->wait_req,
14119                                         obj->last_write_req);
14120         }
14121
14122         return ret;
14123 }
14124
14125 /**
14126  * intel_cleanup_plane_fb - Cleans up an fb after plane use
14127  * @plane: drm plane to clean up for
14128  * @fb: old framebuffer that was on plane
14129  *
14130  * Cleans up a framebuffer that has just been removed from a plane.
14131  *
14132  * Must be called with struct_mutex held.
14133  */
14134 void
14135 intel_cleanup_plane_fb(struct drm_plane *plane,
14136                        const struct drm_plane_state *old_state)
14137 {
14138         struct drm_device *dev = plane->dev;
14139         struct intel_plane_state *old_intel_state;
14140         struct drm_i915_gem_object *old_obj = intel_fb_obj(old_state->fb);
14141         struct drm_i915_gem_object *obj = intel_fb_obj(plane->state->fb);
14142
14143         old_intel_state = to_intel_plane_state(old_state);
14144
14145         if (!obj && !old_obj)
14146                 return;
14147
14148         if (old_obj && (plane->type != DRM_PLANE_TYPE_CURSOR ||
14149             !INTEL_INFO(dev)->cursor_needs_physical))
14150                 intel_unpin_fb_obj(old_state->fb, old_state->rotation);
14151
14152         i915_gem_request_assign(&old_intel_state->wait_req, NULL);
14153 }
14154
14155 int
14156 skl_max_scale(struct intel_crtc *intel_crtc, struct intel_crtc_state *crtc_state)
14157 {
14158         int max_scale;
14159         int crtc_clock, cdclk;
14160
14161         if (!intel_crtc || !crtc_state->base.enable)
14162                 return DRM_PLANE_HELPER_NO_SCALING;
14163
14164         crtc_clock = crtc_state->base.adjusted_mode.crtc_clock;
14165         cdclk = to_intel_atomic_state(crtc_state->base.state)->cdclk;
14166
14167         if (WARN_ON_ONCE(!crtc_clock || cdclk < crtc_clock))
14168                 return DRM_PLANE_HELPER_NO_SCALING;
14169
14170         /*
14171          * skl max scale is lower of:
14172          *    close to 3 but not 3, -1 is for that purpose
14173          *            or
14174          *    cdclk/crtc_clock
14175          */
14176         max_scale = min((1 << 16) * 3 - 1, (1 << 8) * ((cdclk << 8) / crtc_clock));
14177
14178         return max_scale;
14179 }
14180
14181 static int
14182 intel_check_primary_plane(struct drm_plane *plane,
14183                           struct intel_crtc_state *crtc_state,
14184                           struct intel_plane_state *state)
14185 {
14186         struct drm_crtc *crtc = state->base.crtc;
14187         struct drm_framebuffer *fb = state->base.fb;
14188         int min_scale = DRM_PLANE_HELPER_NO_SCALING;
14189         int max_scale = DRM_PLANE_HELPER_NO_SCALING;
14190         bool can_position = false;
14191
14192         if (INTEL_INFO(plane->dev)->gen >= 9) {
14193                 /* use scaler when colorkey is not required */
14194                 if (state->ckey.flags == I915_SET_COLORKEY_NONE) {
14195                         min_scale = 1;
14196                         max_scale = skl_max_scale(to_intel_crtc(crtc), crtc_state);
14197                 }
14198                 can_position = true;
14199         }
14200
14201         return drm_plane_helper_check_update(plane, crtc, fb, &state->src,
14202                                              &state->dst, &state->clip,
14203                                              state->base.rotation,
14204                                              min_scale, max_scale,
14205                                              can_position, true,
14206                                              &state->visible);
14207 }
14208
14209 static void intel_begin_crtc_commit(struct drm_crtc *crtc,
14210                                     struct drm_crtc_state *old_crtc_state)
14211 {
14212         struct drm_device *dev = crtc->dev;
14213         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
14214         struct intel_crtc_state *old_intel_state =
14215                 to_intel_crtc_state(old_crtc_state);
14216         bool modeset = needs_modeset(crtc->state);
14217
14218         /* Perform vblank evasion around commit operation */
14219         intel_pipe_update_start(intel_crtc);
14220
14221         if (modeset)
14222                 return;
14223
14224         if (crtc->state->color_mgmt_changed || to_intel_crtc_state(crtc->state)->update_pipe) {
14225                 intel_color_set_csc(crtc->state);
14226                 intel_color_load_luts(crtc->state);
14227         }
14228
14229         if (to_intel_crtc_state(crtc->state)->update_pipe)
14230                 intel_update_pipe_config(intel_crtc, old_intel_state);
14231         else if (INTEL_INFO(dev)->gen >= 9)
14232                 skl_detach_scalers(intel_crtc);
14233 }
14234
14235 static void intel_finish_crtc_commit(struct drm_crtc *crtc,
14236                                      struct drm_crtc_state *old_crtc_state)
14237 {
14238         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
14239
14240         intel_pipe_update_end(intel_crtc, NULL);
14241 }
14242
14243 /**
14244  * intel_plane_destroy - destroy a plane
14245  * @plane: plane to destroy
14246  *
14247  * Common destruction function for all types of planes (primary, cursor,
14248  * sprite).
14249  */
14250 void intel_plane_destroy(struct drm_plane *plane)
14251 {
14252         if (!plane)
14253                 return;
14254
14255         drm_plane_cleanup(plane);
14256         kfree(to_intel_plane(plane));
14257 }
14258
14259 const struct drm_plane_funcs intel_plane_funcs = {
14260         .update_plane = drm_atomic_helper_update_plane,
14261         .disable_plane = drm_atomic_helper_disable_plane,
14262         .destroy = intel_plane_destroy,
14263         .set_property = drm_atomic_helper_plane_set_property,
14264         .atomic_get_property = intel_plane_atomic_get_property,
14265         .atomic_set_property = intel_plane_atomic_set_property,
14266         .atomic_duplicate_state = intel_plane_duplicate_state,
14267         .atomic_destroy_state = intel_plane_destroy_state,
14268
14269 };
14270
14271 static struct drm_plane *intel_primary_plane_create(struct drm_device *dev,
14272                                                     int pipe)
14273 {
14274         struct intel_plane *primary = NULL;
14275         struct intel_plane_state *state = NULL;
14276         const uint32_t *intel_primary_formats;
14277         unsigned int num_formats;
14278         int ret;
14279
14280         primary = kzalloc(sizeof(*primary), GFP_KERNEL);
14281         if (!primary)
14282                 goto fail;
14283
14284         state = intel_create_plane_state(&primary->base);
14285         if (!state)
14286                 goto fail;
14287         primary->base.state = &state->base;
14288
14289         primary->can_scale = false;
14290         primary->max_downscale = 1;
14291         if (INTEL_INFO(dev)->gen >= 9) {
14292                 primary->can_scale = true;
14293                 state->scaler_id = -1;
14294         }
14295         primary->pipe = pipe;
14296         primary->plane = pipe;
14297         primary->frontbuffer_bit = INTEL_FRONTBUFFER_PRIMARY(pipe);
14298         primary->check_plane = intel_check_primary_plane;
14299         if (HAS_FBC(dev) && INTEL_INFO(dev)->gen < 4)
14300                 primary->plane = !pipe;
14301
14302         if (INTEL_INFO(dev)->gen >= 9) {
14303                 intel_primary_formats = skl_primary_formats;
14304                 num_formats = ARRAY_SIZE(skl_primary_formats);
14305
14306                 primary->update_plane = skylake_update_primary_plane;
14307                 primary->disable_plane = skylake_disable_primary_plane;
14308         } else if (HAS_PCH_SPLIT(dev)) {
14309                 intel_primary_formats = i965_primary_formats;
14310                 num_formats = ARRAY_SIZE(i965_primary_formats);
14311
14312                 primary->update_plane = ironlake_update_primary_plane;
14313                 primary->disable_plane = i9xx_disable_primary_plane;
14314         } else if (INTEL_INFO(dev)->gen >= 4) {
14315                 intel_primary_formats = i965_primary_formats;
14316                 num_formats = ARRAY_SIZE(i965_primary_formats);
14317
14318                 primary->update_plane = i9xx_update_primary_plane;
14319                 primary->disable_plane = i9xx_disable_primary_plane;
14320         } else {
14321                 intel_primary_formats = i8xx_primary_formats;
14322                 num_formats = ARRAY_SIZE(i8xx_primary_formats);
14323
14324                 primary->update_plane = i9xx_update_primary_plane;
14325                 primary->disable_plane = i9xx_disable_primary_plane;
14326         }
14327
14328         if (INTEL_INFO(dev)->gen >= 9)
14329                 ret = drm_universal_plane_init(dev, &primary->base, 0,
14330                                                &intel_plane_funcs,
14331                                                intel_primary_formats, num_formats,
14332                                                DRM_PLANE_TYPE_PRIMARY,
14333                                                "plane 1%c", pipe_name(pipe));
14334         else if (INTEL_INFO(dev)->gen >= 5 || IS_G4X(dev))
14335                 ret = drm_universal_plane_init(dev, &primary->base, 0,
14336                                                &intel_plane_funcs,
14337                                                intel_primary_formats, num_formats,
14338                                                DRM_PLANE_TYPE_PRIMARY,
14339                                                "primary %c", pipe_name(pipe));
14340         else
14341                 ret = drm_universal_plane_init(dev, &primary->base, 0,
14342                                                &intel_plane_funcs,
14343                                                intel_primary_formats, num_formats,
14344                                                DRM_PLANE_TYPE_PRIMARY,
14345                                                "plane %c", plane_name(primary->plane));
14346         if (ret)
14347                 goto fail;
14348
14349         if (INTEL_INFO(dev)->gen >= 4)
14350                 intel_create_rotation_property(dev, primary);
14351
14352         drm_plane_helper_add(&primary->base, &intel_plane_helper_funcs);
14353
14354         return &primary->base;
14355
14356 fail:
14357         kfree(state);
14358         kfree(primary);
14359
14360         return NULL;
14361 }
14362
14363 void intel_create_rotation_property(struct drm_device *dev, struct intel_plane *plane)
14364 {
14365         if (!dev->mode_config.rotation_property) {
14366                 unsigned long flags = BIT(DRM_ROTATE_0) |
14367                         BIT(DRM_ROTATE_180);
14368
14369                 if (INTEL_INFO(dev)->gen >= 9)
14370                         flags |= BIT(DRM_ROTATE_90) | BIT(DRM_ROTATE_270);
14371
14372                 dev->mode_config.rotation_property =
14373                         drm_mode_create_rotation_property(dev, flags);
14374         }
14375         if (dev->mode_config.rotation_property)
14376                 drm_object_attach_property(&plane->base.base,
14377                                 dev->mode_config.rotation_property,
14378                                 plane->base.state->rotation);
14379 }
14380
14381 static int
14382 intel_check_cursor_plane(struct drm_plane *plane,
14383                          struct intel_crtc_state *crtc_state,
14384                          struct intel_plane_state *state)
14385 {
14386         struct drm_crtc *crtc = crtc_state->base.crtc;
14387         struct drm_framebuffer *fb = state->base.fb;
14388         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
14389         enum pipe pipe = to_intel_plane(plane)->pipe;
14390         unsigned stride;
14391         int ret;
14392
14393         ret = drm_plane_helper_check_update(plane, crtc, fb, &state->src,
14394                                             &state->dst, &state->clip,
14395                                             state->base.rotation,
14396                                             DRM_PLANE_HELPER_NO_SCALING,
14397                                             DRM_PLANE_HELPER_NO_SCALING,
14398                                             true, true, &state->visible);
14399         if (ret)
14400                 return ret;
14401
14402         /* if we want to turn off the cursor ignore width and height */
14403         if (!obj)
14404                 return 0;
14405
14406         /* Check for which cursor types we support */
14407         if (!cursor_size_ok(plane->dev, state->base.crtc_w, state->base.crtc_h)) {
14408                 DRM_DEBUG("Cursor dimension %dx%d not supported\n",
14409                           state->base.crtc_w, state->base.crtc_h);
14410                 return -EINVAL;
14411         }
14412
14413         stride = roundup_pow_of_two(state->base.crtc_w) * 4;
14414         if (obj->base.size < stride * state->base.crtc_h) {
14415                 DRM_DEBUG_KMS("buffer is too small\n");
14416                 return -ENOMEM;
14417         }
14418
14419         if (fb->modifier[0] != DRM_FORMAT_MOD_NONE) {
14420                 DRM_DEBUG_KMS("cursor cannot be tiled\n");
14421                 return -EINVAL;
14422         }
14423
14424         /*
14425          * There's something wrong with the cursor on CHV pipe C.
14426          * If it straddles the left edge of the screen then
14427          * moving it away from the edge or disabling it often
14428          * results in a pipe underrun, and often that can lead to
14429          * dead pipe (constant underrun reported, and it scans
14430          * out just a solid color). To recover from that, the
14431          * display power well must be turned off and on again.
14432          * Refuse the put the cursor into that compromised position.
14433          */
14434         if (IS_CHERRYVIEW(plane->dev) && pipe == PIPE_C &&
14435             state->visible && state->base.crtc_x < 0) {
14436                 DRM_DEBUG_KMS("CHV cursor C not allowed to straddle the left screen edge\n");
14437                 return -EINVAL;
14438         }
14439
14440         return 0;
14441 }
14442
14443 static void
14444 intel_disable_cursor_plane(struct drm_plane *plane,
14445                            struct drm_crtc *crtc)
14446 {
14447         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
14448
14449         intel_crtc->cursor_addr = 0;
14450         intel_crtc_update_cursor(crtc, NULL);
14451 }
14452
14453 static void
14454 intel_update_cursor_plane(struct drm_plane *plane,
14455                           const struct intel_crtc_state *crtc_state,
14456                           const struct intel_plane_state *state)
14457 {
14458         struct drm_crtc *crtc = crtc_state->base.crtc;
14459         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
14460         struct drm_device *dev = plane->dev;
14461         struct drm_i915_gem_object *obj = intel_fb_obj(state->base.fb);
14462         uint32_t addr;
14463
14464         if (!obj)
14465                 addr = 0;
14466         else if (!INTEL_INFO(dev)->cursor_needs_physical)
14467                 addr = i915_gem_obj_ggtt_offset(obj);
14468         else
14469                 addr = obj->phys_handle->busaddr;
14470
14471         intel_crtc->cursor_addr = addr;
14472         intel_crtc_update_cursor(crtc, state);
14473 }
14474
14475 static struct drm_plane *intel_cursor_plane_create(struct drm_device *dev,
14476                                                    int pipe)
14477 {
14478         struct intel_plane *cursor = NULL;
14479         struct intel_plane_state *state = NULL;
14480         int ret;
14481
14482         cursor = kzalloc(sizeof(*cursor), GFP_KERNEL);
14483         if (!cursor)
14484                 goto fail;
14485
14486         state = intel_create_plane_state(&cursor->base);
14487         if (!state)
14488                 goto fail;
14489         cursor->base.state = &state->base;
14490
14491         cursor->can_scale = false;
14492         cursor->max_downscale = 1;
14493         cursor->pipe = pipe;
14494         cursor->plane = pipe;
14495         cursor->frontbuffer_bit = INTEL_FRONTBUFFER_CURSOR(pipe);
14496         cursor->check_plane = intel_check_cursor_plane;
14497         cursor->update_plane = intel_update_cursor_plane;
14498         cursor->disable_plane = intel_disable_cursor_plane;
14499
14500         ret = drm_universal_plane_init(dev, &cursor->base, 0,
14501                                        &intel_plane_funcs,
14502                                        intel_cursor_formats,
14503                                        ARRAY_SIZE(intel_cursor_formats),
14504                                        DRM_PLANE_TYPE_CURSOR,
14505                                        "cursor %c", pipe_name(pipe));
14506         if (ret)
14507                 goto fail;
14508
14509         if (INTEL_INFO(dev)->gen >= 4) {
14510                 if (!dev->mode_config.rotation_property)
14511                         dev->mode_config.rotation_property =
14512                                 drm_mode_create_rotation_property(dev,
14513                                                         BIT(DRM_ROTATE_0) |
14514                                                         BIT(DRM_ROTATE_180));
14515                 if (dev->mode_config.rotation_property)
14516                         drm_object_attach_property(&cursor->base.base,
14517                                 dev->mode_config.rotation_property,
14518                                 state->base.rotation);
14519         }
14520
14521         if (INTEL_INFO(dev)->gen >=9)
14522                 state->scaler_id = -1;
14523
14524         drm_plane_helper_add(&cursor->base, &intel_plane_helper_funcs);
14525
14526         return &cursor->base;
14527
14528 fail:
14529         kfree(state);
14530         kfree(cursor);
14531
14532         return NULL;
14533 }
14534
14535 static void skl_init_scalers(struct drm_device *dev, struct intel_crtc *intel_crtc,
14536         struct intel_crtc_state *crtc_state)
14537 {
14538         int i;
14539         struct intel_scaler *intel_scaler;
14540         struct intel_crtc_scaler_state *scaler_state = &crtc_state->scaler_state;
14541
14542         for (i = 0; i < intel_crtc->num_scalers; i++) {
14543                 intel_scaler = &scaler_state->scalers[i];
14544                 intel_scaler->in_use = 0;
14545                 intel_scaler->mode = PS_SCALER_MODE_DYN;
14546         }
14547
14548         scaler_state->scaler_id = -1;
14549 }
14550
14551 static void intel_crtc_init(struct drm_device *dev, int pipe)
14552 {
14553         struct drm_i915_private *dev_priv = to_i915(dev);
14554         struct intel_crtc *intel_crtc;
14555         struct intel_crtc_state *crtc_state = NULL;
14556         struct drm_plane *primary = NULL;
14557         struct drm_plane *cursor = NULL;
14558         int ret;
14559
14560         intel_crtc = kzalloc(sizeof(*intel_crtc), GFP_KERNEL);
14561         if (intel_crtc == NULL)
14562                 return;
14563
14564         crtc_state = kzalloc(sizeof(*crtc_state), GFP_KERNEL);
14565         if (!crtc_state)
14566                 goto fail;
14567         intel_crtc->config = crtc_state;
14568         intel_crtc->base.state = &crtc_state->base;
14569         crtc_state->base.crtc = &intel_crtc->base;
14570
14571         /* initialize shared scalers */
14572         if (INTEL_INFO(dev)->gen >= 9) {
14573                 if (pipe == PIPE_C)
14574                         intel_crtc->num_scalers = 1;
14575                 else
14576                         intel_crtc->num_scalers = SKL_NUM_SCALERS;
14577
14578                 skl_init_scalers(dev, intel_crtc, crtc_state);
14579         }
14580
14581         primary = intel_primary_plane_create(dev, pipe);
14582         if (!primary)
14583                 goto fail;
14584
14585         cursor = intel_cursor_plane_create(dev, pipe);
14586         if (!cursor)
14587                 goto fail;
14588
14589         ret = drm_crtc_init_with_planes(dev, &intel_crtc->base, primary,
14590                                         cursor, &intel_crtc_funcs,
14591                                         "pipe %c", pipe_name(pipe));
14592         if (ret)
14593                 goto fail;
14594
14595         /*
14596          * On gen2/3 only plane A can do fbc, but the panel fitter and lvds port
14597          * is hooked to pipe B. Hence we want plane A feeding pipe B.
14598          */
14599         intel_crtc->pipe = pipe;
14600         intel_crtc->plane = pipe;
14601         if (HAS_FBC(dev) && INTEL_INFO(dev)->gen < 4) {
14602                 DRM_DEBUG_KMS("swapping pipes & planes for FBC\n");
14603                 intel_crtc->plane = !pipe;
14604         }
14605
14606         intel_crtc->cursor_base = ~0;
14607         intel_crtc->cursor_cntl = ~0;
14608         intel_crtc->cursor_size = ~0;
14609
14610         intel_crtc->wm.cxsr_allowed = true;
14611
14612         BUG_ON(pipe >= ARRAY_SIZE(dev_priv->plane_to_crtc_mapping) ||
14613                dev_priv->plane_to_crtc_mapping[intel_crtc->plane] != NULL);
14614         dev_priv->plane_to_crtc_mapping[intel_crtc->plane] = &intel_crtc->base;
14615         dev_priv->pipe_to_crtc_mapping[intel_crtc->pipe] = &intel_crtc->base;
14616
14617         drm_crtc_helper_add(&intel_crtc->base, &intel_helper_funcs);
14618
14619         intel_color_init(&intel_crtc->base);
14620
14621         WARN_ON(drm_crtc_index(&intel_crtc->base) != intel_crtc->pipe);
14622         return;
14623
14624 fail:
14625         intel_plane_destroy(primary);
14626         intel_plane_destroy(cursor);
14627         kfree(crtc_state);
14628         kfree(intel_crtc);
14629 }
14630
14631 enum pipe intel_get_pipe_from_connector(struct intel_connector *connector)
14632 {
14633         struct drm_encoder *encoder = connector->base.encoder;
14634         struct drm_device *dev = connector->base.dev;
14635
14636         WARN_ON(!drm_modeset_is_locked(&dev->mode_config.connection_mutex));
14637
14638         if (!encoder || WARN_ON(!encoder->crtc))
14639                 return INVALID_PIPE;
14640
14641         return to_intel_crtc(encoder->crtc)->pipe;
14642 }
14643
14644 int intel_get_pipe_from_crtc_id(struct drm_device *dev, void *data,
14645                                 struct drm_file *file)
14646 {
14647         struct drm_i915_get_pipe_from_crtc_id *pipe_from_crtc_id = data;
14648         struct drm_crtc *drmmode_crtc;
14649         struct intel_crtc *crtc;
14650
14651         drmmode_crtc = drm_crtc_find(dev, pipe_from_crtc_id->crtc_id);
14652         if (!drmmode_crtc)
14653                 return -ENOENT;
14654
14655         crtc = to_intel_crtc(drmmode_crtc);
14656         pipe_from_crtc_id->pipe = crtc->pipe;
14657
14658         return 0;
14659 }
14660
14661 static int intel_encoder_clones(struct intel_encoder *encoder)
14662 {
14663         struct drm_device *dev = encoder->base.dev;
14664         struct intel_encoder *source_encoder;
14665         int index_mask = 0;
14666         int entry = 0;
14667
14668         for_each_intel_encoder(dev, source_encoder) {
14669                 if (encoders_cloneable(encoder, source_encoder))
14670                         index_mask |= (1 << entry);
14671
14672                 entry++;
14673         }
14674
14675         return index_mask;
14676 }
14677
14678 static bool has_edp_a(struct drm_device *dev)
14679 {
14680         struct drm_i915_private *dev_priv = to_i915(dev);
14681
14682         if (!IS_MOBILE(dev))
14683                 return false;
14684
14685         if ((I915_READ(DP_A) & DP_DETECTED) == 0)
14686                 return false;
14687
14688         if (IS_GEN5(dev) && (I915_READ(FUSE_STRAP) & ILK_eDP_A_DISABLE))
14689                 return false;
14690
14691         return true;
14692 }
14693
14694 static bool intel_crt_present(struct drm_device *dev)
14695 {
14696         struct drm_i915_private *dev_priv = to_i915(dev);
14697
14698         if (INTEL_INFO(dev)->gen >= 9)
14699                 return false;
14700
14701         if (IS_HSW_ULT(dev) || IS_BDW_ULT(dev))
14702                 return false;
14703
14704         if (IS_CHERRYVIEW(dev))
14705                 return false;
14706
14707         if (HAS_PCH_LPT_H(dev) && I915_READ(SFUSE_STRAP) & SFUSE_STRAP_CRT_DISABLED)
14708                 return false;
14709
14710         /* DDI E can't be used if DDI A requires 4 lanes */
14711         if (HAS_DDI(dev) && I915_READ(DDI_BUF_CTL(PORT_A)) & DDI_A_4_LANES)
14712                 return false;
14713
14714         if (!dev_priv->vbt.int_crt_support)
14715                 return false;
14716
14717         return true;
14718 }
14719
14720 static void intel_setup_outputs(struct drm_device *dev)
14721 {
14722         struct drm_i915_private *dev_priv = to_i915(dev);
14723         struct intel_encoder *encoder;
14724         bool dpd_is_edp = false;
14725
14726         /*
14727          * intel_edp_init_connector() depends on this completing first, to
14728          * prevent the registeration of both eDP and LVDS and the incorrect
14729          * sharing of the PPS.
14730          */
14731         intel_lvds_init(dev);
14732
14733         if (intel_crt_present(dev))
14734                 intel_crt_init(dev);
14735
14736         if (IS_BROXTON(dev)) {
14737                 /*
14738                  * FIXME: Broxton doesn't support port detection via the
14739                  * DDI_BUF_CTL_A or SFUSE_STRAP registers, find another way to
14740                  * detect the ports.
14741                  */
14742                 intel_ddi_init(dev, PORT_A);
14743                 intel_ddi_init(dev, PORT_B);
14744                 intel_ddi_init(dev, PORT_C);
14745
14746                 intel_dsi_init(dev);
14747         } else if (HAS_DDI(dev)) {
14748                 int found;
14749
14750                 /*
14751                  * Haswell uses DDI functions to detect digital outputs.
14752                  * On SKL pre-D0 the strap isn't connected, so we assume
14753                  * it's there.
14754                  */
14755                 found = I915_READ(DDI_BUF_CTL(PORT_A)) & DDI_INIT_DISPLAY_DETECTED;
14756                 /* WaIgnoreDDIAStrap: skl */
14757                 if (found || IS_SKYLAKE(dev) || IS_KABYLAKE(dev))
14758                         intel_ddi_init(dev, PORT_A);
14759
14760                 /* DDI B, C and D detection is indicated by the SFUSE_STRAP
14761                  * register */
14762                 found = I915_READ(SFUSE_STRAP);
14763
14764                 if (found & SFUSE_STRAP_DDIB_DETECTED)
14765                         intel_ddi_init(dev, PORT_B);
14766                 if (found & SFUSE_STRAP_DDIC_DETECTED)
14767                         intel_ddi_init(dev, PORT_C);
14768                 if (found & SFUSE_STRAP_DDID_DETECTED)
14769                         intel_ddi_init(dev, PORT_D);
14770                 /*
14771                  * On SKL we don't have a way to detect DDI-E so we rely on VBT.
14772                  */
14773                 if ((IS_SKYLAKE(dev) || IS_KABYLAKE(dev)) &&
14774                     (dev_priv->vbt.ddi_port_info[PORT_E].supports_dp ||
14775                      dev_priv->vbt.ddi_port_info[PORT_E].supports_dvi ||
14776                      dev_priv->vbt.ddi_port_info[PORT_E].supports_hdmi))
14777                         intel_ddi_init(dev, PORT_E);
14778
14779         } else if (HAS_PCH_SPLIT(dev)) {
14780                 int found;
14781                 dpd_is_edp = intel_dp_is_edp(dev, PORT_D);
14782
14783                 if (has_edp_a(dev))
14784                         intel_dp_init(dev, DP_A, PORT_A);
14785
14786                 if (I915_READ(PCH_HDMIB) & SDVO_DETECTED) {
14787                         /* PCH SDVOB multiplex with HDMIB */
14788                         found = intel_sdvo_init(dev, PCH_SDVOB, PORT_B);
14789                         if (!found)
14790                                 intel_hdmi_init(dev, PCH_HDMIB, PORT_B);
14791                         if (!found && (I915_READ(PCH_DP_B) & DP_DETECTED))
14792                                 intel_dp_init(dev, PCH_DP_B, PORT_B);
14793                 }
14794
14795                 if (I915_READ(PCH_HDMIC) & SDVO_DETECTED)
14796                         intel_hdmi_init(dev, PCH_HDMIC, PORT_C);
14797
14798                 if (!dpd_is_edp && I915_READ(PCH_HDMID) & SDVO_DETECTED)
14799                         intel_hdmi_init(dev, PCH_HDMID, PORT_D);
14800
14801                 if (I915_READ(PCH_DP_C) & DP_DETECTED)
14802                         intel_dp_init(dev, PCH_DP_C, PORT_C);
14803
14804                 if (I915_READ(PCH_DP_D) & DP_DETECTED)
14805                         intel_dp_init(dev, PCH_DP_D, PORT_D);
14806         } else if (IS_VALLEYVIEW(dev) || IS_CHERRYVIEW(dev)) {
14807                 bool has_edp, has_port;
14808
14809                 /*
14810                  * The DP_DETECTED bit is the latched state of the DDC
14811                  * SDA pin at boot. However since eDP doesn't require DDC
14812                  * (no way to plug in a DP->HDMI dongle) the DDC pins for
14813                  * eDP ports may have been muxed to an alternate function.
14814                  * Thus we can't rely on the DP_DETECTED bit alone to detect
14815                  * eDP ports. Consult the VBT as well as DP_DETECTED to
14816                  * detect eDP ports.
14817                  *
14818                  * Sadly the straps seem to be missing sometimes even for HDMI
14819                  * ports (eg. on Voyo V3 - CHT x7-Z8700), so check both strap
14820                  * and VBT for the presence of the port. Additionally we can't
14821                  * trust the port type the VBT declares as we've seen at least
14822                  * HDMI ports that the VBT claim are DP or eDP.
14823                  */
14824                 has_edp = intel_dp_is_edp(dev, PORT_B);
14825                 has_port = intel_bios_is_port_present(dev_priv, PORT_B);
14826                 if (I915_READ(VLV_DP_B) & DP_DETECTED || has_port)
14827                         has_edp &= intel_dp_init(dev, VLV_DP_B, PORT_B);
14828                 if ((I915_READ(VLV_HDMIB) & SDVO_DETECTED || has_port) && !has_edp)
14829                         intel_hdmi_init(dev, VLV_HDMIB, PORT_B);
14830
14831                 has_edp = intel_dp_is_edp(dev, PORT_C);
14832                 has_port = intel_bios_is_port_present(dev_priv, PORT_C);
14833                 if (I915_READ(VLV_DP_C) & DP_DETECTED || has_port)
14834                         has_edp &= intel_dp_init(dev, VLV_DP_C, PORT_C);
14835                 if ((I915_READ(VLV_HDMIC) & SDVO_DETECTED || has_port) && !has_edp)
14836                         intel_hdmi_init(dev, VLV_HDMIC, PORT_C);
14837
14838                 if (IS_CHERRYVIEW(dev)) {
14839                         /*
14840                          * eDP not supported on port D,
14841                          * so no need to worry about it
14842                          */
14843                         has_port = intel_bios_is_port_present(dev_priv, PORT_D);
14844                         if (I915_READ(CHV_DP_D) & DP_DETECTED || has_port)
14845                                 intel_dp_init(dev, CHV_DP_D, PORT_D);
14846                         if (I915_READ(CHV_HDMID) & SDVO_DETECTED || has_port)
14847                                 intel_hdmi_init(dev, CHV_HDMID, PORT_D);
14848                 }
14849
14850                 intel_dsi_init(dev);
14851         } else if (!IS_GEN2(dev) && !IS_PINEVIEW(dev)) {
14852                 bool found = false;
14853
14854                 if (I915_READ(GEN3_SDVOB) & SDVO_DETECTED) {
14855                         DRM_DEBUG_KMS("probing SDVOB\n");
14856                         found = intel_sdvo_init(dev, GEN3_SDVOB, PORT_B);
14857                         if (!found && IS_G4X(dev)) {
14858                                 DRM_DEBUG_KMS("probing HDMI on SDVOB\n");
14859                                 intel_hdmi_init(dev, GEN4_HDMIB, PORT_B);
14860                         }
14861
14862                         if (!found && IS_G4X(dev))
14863                                 intel_dp_init(dev, DP_B, PORT_B);
14864                 }
14865
14866                 /* Before G4X SDVOC doesn't have its own detect register */
14867
14868                 if (I915_READ(GEN3_SDVOB) & SDVO_DETECTED) {
14869                         DRM_DEBUG_KMS("probing SDVOC\n");
14870                         found = intel_sdvo_init(dev, GEN3_SDVOC, PORT_C);
14871                 }
14872
14873                 if (!found && (I915_READ(GEN3_SDVOC) & SDVO_DETECTED)) {
14874
14875                         if (IS_G4X(dev)) {
14876                                 DRM_DEBUG_KMS("probing HDMI on SDVOC\n");
14877                                 intel_hdmi_init(dev, GEN4_HDMIC, PORT_C);
14878                         }
14879                         if (IS_G4X(dev))
14880                                 intel_dp_init(dev, DP_C, PORT_C);
14881                 }
14882
14883                 if (IS_G4X(dev) &&
14884                     (I915_READ(DP_D) & DP_DETECTED))
14885                         intel_dp_init(dev, DP_D, PORT_D);
14886         } else if (IS_GEN2(dev))
14887                 intel_dvo_init(dev);
14888
14889         if (SUPPORTS_TV(dev))
14890                 intel_tv_init(dev);
14891
14892         intel_psr_init(dev);
14893
14894         for_each_intel_encoder(dev, encoder) {
14895                 encoder->base.possible_crtcs = encoder->crtc_mask;
14896                 encoder->base.possible_clones =
14897                         intel_encoder_clones(encoder);
14898         }
14899
14900         intel_init_pch_refclk(dev);
14901
14902         drm_helper_move_panel_connectors_to_head(dev);
14903 }
14904
14905 static void intel_user_framebuffer_destroy(struct drm_framebuffer *fb)
14906 {
14907         struct drm_device *dev = fb->dev;
14908         struct intel_framebuffer *intel_fb = to_intel_framebuffer(fb);
14909
14910         drm_framebuffer_cleanup(fb);
14911         mutex_lock(&dev->struct_mutex);
14912         WARN_ON(!intel_fb->obj->framebuffer_references--);
14913         drm_gem_object_unreference(&intel_fb->obj->base);
14914         mutex_unlock(&dev->struct_mutex);
14915         kfree(intel_fb);
14916 }
14917
14918 static int intel_user_framebuffer_create_handle(struct drm_framebuffer *fb,
14919                                                 struct drm_file *file,
14920                                                 unsigned int *handle)
14921 {
14922         struct intel_framebuffer *intel_fb = to_intel_framebuffer(fb);
14923         struct drm_i915_gem_object *obj = intel_fb->obj;
14924
14925         if (obj->userptr.mm) {
14926                 DRM_DEBUG("attempting to use a userptr for a framebuffer, denied\n");
14927                 return -EINVAL;
14928         }
14929
14930         return drm_gem_handle_create(file, &obj->base, handle);
14931 }
14932
14933 static int intel_user_framebuffer_dirty(struct drm_framebuffer *fb,
14934                                         struct drm_file *file,
14935                                         unsigned flags, unsigned color,
14936                                         struct drm_clip_rect *clips,
14937                                         unsigned num_clips)
14938 {
14939         struct drm_device *dev = fb->dev;
14940         struct intel_framebuffer *intel_fb = to_intel_framebuffer(fb);
14941         struct drm_i915_gem_object *obj = intel_fb->obj;
14942
14943         mutex_lock(&dev->struct_mutex);
14944         intel_fb_obj_flush(obj, false, ORIGIN_DIRTYFB);
14945         mutex_unlock(&dev->struct_mutex);
14946
14947         return 0;
14948 }
14949
14950 static const struct drm_framebuffer_funcs intel_fb_funcs = {
14951         .destroy = intel_user_framebuffer_destroy,
14952         .create_handle = intel_user_framebuffer_create_handle,
14953         .dirty = intel_user_framebuffer_dirty,
14954 };
14955
14956 static
14957 u32 intel_fb_pitch_limit(struct drm_device *dev, uint64_t fb_modifier,
14958                          uint32_t pixel_format)
14959 {
14960         u32 gen = INTEL_INFO(dev)->gen;
14961
14962         if (gen >= 9) {
14963                 int cpp = drm_format_plane_cpp(pixel_format, 0);
14964
14965                 /* "The stride in bytes must not exceed the of the size of 8K
14966                  *  pixels and 32K bytes."
14967                  */
14968                 return min(8192 * cpp, 32768);
14969         } else if (gen >= 5 && !IS_VALLEYVIEW(dev) && !IS_CHERRYVIEW(dev)) {
14970                 return 32*1024;
14971         } else if (gen >= 4) {
14972                 if (fb_modifier == I915_FORMAT_MOD_X_TILED)
14973                         return 16*1024;
14974                 else
14975                         return 32*1024;
14976         } else if (gen >= 3) {
14977                 if (fb_modifier == I915_FORMAT_MOD_X_TILED)
14978                         return 8*1024;
14979                 else
14980                         return 16*1024;
14981         } else {
14982                 /* XXX DSPC is limited to 4k tiled */
14983                 return 8*1024;
14984         }
14985 }
14986
14987 static int intel_framebuffer_init(struct drm_device *dev,
14988                                   struct intel_framebuffer *intel_fb,
14989                                   struct drm_mode_fb_cmd2 *mode_cmd,
14990                                   struct drm_i915_gem_object *obj)
14991 {
14992         struct drm_i915_private *dev_priv = to_i915(dev);
14993         unsigned int aligned_height;
14994         int ret;
14995         u32 pitch_limit, stride_alignment;
14996
14997         WARN_ON(!mutex_is_locked(&dev->struct_mutex));
14998
14999         if (mode_cmd->flags & DRM_MODE_FB_MODIFIERS) {
15000                 /* Enforce that fb modifier and tiling mode match, but only for
15001                  * X-tiled. This is needed for FBC. */
15002                 if (!!(obj->tiling_mode == I915_TILING_X) !=
15003                     !!(mode_cmd->modifier[0] == I915_FORMAT_MOD_X_TILED)) {
15004                         DRM_DEBUG("tiling_mode doesn't match fb modifier\n");
15005                         return -EINVAL;
15006                 }
15007         } else {
15008                 if (obj->tiling_mode == I915_TILING_X)
15009                         mode_cmd->modifier[0] = I915_FORMAT_MOD_X_TILED;
15010                 else if (obj->tiling_mode == I915_TILING_Y) {
15011                         DRM_DEBUG("No Y tiling for legacy addfb\n");
15012                         return -EINVAL;
15013                 }
15014         }
15015
15016         /* Passed in modifier sanity checking. */
15017         switch (mode_cmd->modifier[0]) {
15018         case I915_FORMAT_MOD_Y_TILED:
15019         case I915_FORMAT_MOD_Yf_TILED:
15020                 if (INTEL_INFO(dev)->gen < 9) {
15021                         DRM_DEBUG("Unsupported tiling 0x%llx!\n",
15022                                   mode_cmd->modifier[0]);
15023                         return -EINVAL;
15024                 }
15025         case DRM_FORMAT_MOD_NONE:
15026         case I915_FORMAT_MOD_X_TILED:
15027                 break;
15028         default:
15029                 DRM_DEBUG("Unsupported fb modifier 0x%llx!\n",
15030                           mode_cmd->modifier[0]);
15031                 return -EINVAL;
15032         }
15033
15034         stride_alignment = intel_fb_stride_alignment(dev_priv,
15035                                                      mode_cmd->modifier[0],
15036                                                      mode_cmd->pixel_format);
15037         if (mode_cmd->pitches[0] & (stride_alignment - 1)) {
15038                 DRM_DEBUG("pitch (%d) must be at least %u byte aligned\n",
15039                           mode_cmd->pitches[0], stride_alignment);
15040                 return -EINVAL;
15041         }
15042
15043         pitch_limit = intel_fb_pitch_limit(dev, mode_cmd->modifier[0],
15044                                            mode_cmd->pixel_format);
15045         if (mode_cmd->pitches[0] > pitch_limit) {
15046                 DRM_DEBUG("%s pitch (%u) must be at less than %d\n",
15047                           mode_cmd->modifier[0] != DRM_FORMAT_MOD_NONE ?
15048                           "tiled" : "linear",
15049                           mode_cmd->pitches[0], pitch_limit);
15050                 return -EINVAL;
15051         }
15052
15053         if (mode_cmd->modifier[0] == I915_FORMAT_MOD_X_TILED &&
15054             mode_cmd->pitches[0] != obj->stride) {
15055                 DRM_DEBUG("pitch (%d) must match tiling stride (%d)\n",
15056                           mode_cmd->pitches[0], obj->stride);
15057                 return -EINVAL;
15058         }
15059
15060         /* Reject formats not supported by any plane early. */
15061         switch (mode_cmd->pixel_format) {
15062         case DRM_FORMAT_C8:
15063         case DRM_FORMAT_RGB565:
15064         case DRM_FORMAT_XRGB8888:
15065         case DRM_FORMAT_ARGB8888:
15066                 break;
15067         case DRM_FORMAT_XRGB1555:
15068                 if (INTEL_INFO(dev)->gen > 3) {
15069                         DRM_DEBUG("unsupported pixel format: %s\n",
15070                                   drm_get_format_name(mode_cmd->pixel_format));
15071                         return -EINVAL;
15072                 }
15073                 break;
15074         case DRM_FORMAT_ABGR8888:
15075                 if (!IS_VALLEYVIEW(dev) && !IS_CHERRYVIEW(dev) &&
15076                     INTEL_INFO(dev)->gen < 9) {
15077                         DRM_DEBUG("unsupported pixel format: %s\n",
15078                                   drm_get_format_name(mode_cmd->pixel_format));
15079                         return -EINVAL;
15080                 }
15081                 break;
15082         case DRM_FORMAT_XBGR8888:
15083         case DRM_FORMAT_XRGB2101010:
15084         case DRM_FORMAT_XBGR2101010:
15085                 if (INTEL_INFO(dev)->gen < 4) {
15086                         DRM_DEBUG("unsupported pixel format: %s\n",
15087                                   drm_get_format_name(mode_cmd->pixel_format));
15088                         return -EINVAL;
15089                 }
15090                 break;
15091         case DRM_FORMAT_ABGR2101010:
15092                 if (!IS_VALLEYVIEW(dev) && !IS_CHERRYVIEW(dev)) {
15093                         DRM_DEBUG("unsupported pixel format: %s\n",
15094                                   drm_get_format_name(mode_cmd->pixel_format));
15095                         return -EINVAL;
15096                 }
15097                 break;
15098         case DRM_FORMAT_YUYV:
15099         case DRM_FORMAT_UYVY:
15100         case DRM_FORMAT_YVYU:
15101         case DRM_FORMAT_VYUY:
15102                 if (INTEL_INFO(dev)->gen < 5) {
15103                         DRM_DEBUG("unsupported pixel format: %s\n",
15104                                   drm_get_format_name(mode_cmd->pixel_format));
15105                         return -EINVAL;
15106                 }
15107                 break;
15108         default:
15109                 DRM_DEBUG("unsupported pixel format: %s\n",
15110                           drm_get_format_name(mode_cmd->pixel_format));
15111                 return -EINVAL;
15112         }
15113
15114         /* FIXME need to adjust LINOFF/TILEOFF accordingly. */
15115         if (mode_cmd->offsets[0] != 0)
15116                 return -EINVAL;
15117
15118         aligned_height = intel_fb_align_height(dev, mode_cmd->height,
15119                                                mode_cmd->pixel_format,
15120                                                mode_cmd->modifier[0]);
15121         /* FIXME drm helper for size checks (especially planar formats)? */
15122         if (obj->base.size < aligned_height * mode_cmd->pitches[0])
15123                 return -EINVAL;
15124
15125         drm_helper_mode_fill_fb_struct(&intel_fb->base, mode_cmd);
15126         intel_fb->obj = obj;
15127
15128         intel_fill_fb_info(dev_priv, &intel_fb->base);
15129
15130         ret = drm_framebuffer_init(dev, &intel_fb->base, &intel_fb_funcs);
15131         if (ret) {
15132                 DRM_ERROR("framebuffer init failed %d\n", ret);
15133                 return ret;
15134         }
15135
15136         intel_fb->obj->framebuffer_references++;
15137
15138         return 0;
15139 }
15140
15141 static struct drm_framebuffer *
15142 intel_user_framebuffer_create(struct drm_device *dev,
15143                               struct drm_file *filp,
15144                               const struct drm_mode_fb_cmd2 *user_mode_cmd)
15145 {
15146         struct drm_framebuffer *fb;
15147         struct drm_i915_gem_object *obj;
15148         struct drm_mode_fb_cmd2 mode_cmd = *user_mode_cmd;
15149
15150         obj = to_intel_bo(drm_gem_object_lookup(filp, mode_cmd.handles[0]));
15151         if (&obj->base == NULL)
15152                 return ERR_PTR(-ENOENT);
15153
15154         fb = intel_framebuffer_create(dev, &mode_cmd, obj);
15155         if (IS_ERR(fb))
15156                 drm_gem_object_unreference_unlocked(&obj->base);
15157
15158         return fb;
15159 }
15160
15161 #ifndef CONFIG_DRM_FBDEV_EMULATION
15162 static inline void intel_fbdev_output_poll_changed(struct drm_device *dev)
15163 {
15164 }
15165 #endif
15166
15167 static const struct drm_mode_config_funcs intel_mode_funcs = {
15168         .fb_create = intel_user_framebuffer_create,
15169         .output_poll_changed = intel_fbdev_output_poll_changed,
15170         .atomic_check = intel_atomic_check,
15171         .atomic_commit = intel_atomic_commit,
15172         .atomic_state_alloc = intel_atomic_state_alloc,
15173         .atomic_state_clear = intel_atomic_state_clear,
15174 };
15175
15176 /**
15177  * intel_init_display_hooks - initialize the display modesetting hooks
15178  * @dev_priv: device private
15179  */
15180 void intel_init_display_hooks(struct drm_i915_private *dev_priv)
15181 {
15182         if (INTEL_INFO(dev_priv)->gen >= 9) {
15183                 dev_priv->display.get_pipe_config = haswell_get_pipe_config;
15184                 dev_priv->display.get_initial_plane_config =
15185                         skylake_get_initial_plane_config;
15186                 dev_priv->display.crtc_compute_clock =
15187                         haswell_crtc_compute_clock;
15188                 dev_priv->display.crtc_enable = haswell_crtc_enable;
15189                 dev_priv->display.crtc_disable = haswell_crtc_disable;
15190         } else if (HAS_DDI(dev_priv)) {
15191                 dev_priv->display.get_pipe_config = haswell_get_pipe_config;
15192                 dev_priv->display.get_initial_plane_config =
15193                         ironlake_get_initial_plane_config;
15194                 dev_priv->display.crtc_compute_clock =
15195                         haswell_crtc_compute_clock;
15196                 dev_priv->display.crtc_enable = haswell_crtc_enable;
15197                 dev_priv->display.crtc_disable = haswell_crtc_disable;
15198         } else if (HAS_PCH_SPLIT(dev_priv)) {
15199                 dev_priv->display.get_pipe_config = ironlake_get_pipe_config;
15200                 dev_priv->display.get_initial_plane_config =
15201                         ironlake_get_initial_plane_config;
15202                 dev_priv->display.crtc_compute_clock =
15203                         ironlake_crtc_compute_clock;
15204                 dev_priv->display.crtc_enable = ironlake_crtc_enable;
15205                 dev_priv->display.crtc_disable = ironlake_crtc_disable;
15206         } else if (IS_CHERRYVIEW(dev_priv)) {
15207                 dev_priv->display.get_pipe_config = i9xx_get_pipe_config;
15208                 dev_priv->display.get_initial_plane_config =
15209                         i9xx_get_initial_plane_config;
15210                 dev_priv->display.crtc_compute_clock = chv_crtc_compute_clock;
15211                 dev_priv->display.crtc_enable = valleyview_crtc_enable;
15212                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
15213         } else if (IS_VALLEYVIEW(dev_priv)) {
15214                 dev_priv->display.get_pipe_config = i9xx_get_pipe_config;
15215                 dev_priv->display.get_initial_plane_config =
15216                         i9xx_get_initial_plane_config;
15217                 dev_priv->display.crtc_compute_clock = vlv_crtc_compute_clock;
15218                 dev_priv->display.crtc_enable = valleyview_crtc_enable;
15219                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
15220         } else if (IS_G4X(dev_priv)) {
15221                 dev_priv->display.get_pipe_config = i9xx_get_pipe_config;
15222                 dev_priv->display.get_initial_plane_config =
15223                         i9xx_get_initial_plane_config;
15224                 dev_priv->display.crtc_compute_clock = g4x_crtc_compute_clock;
15225                 dev_priv->display.crtc_enable = i9xx_crtc_enable;
15226                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
15227         } else if (IS_PINEVIEW(dev_priv)) {
15228                 dev_priv->display.get_pipe_config = i9xx_get_pipe_config;
15229                 dev_priv->display.get_initial_plane_config =
15230                         i9xx_get_initial_plane_config;
15231                 dev_priv->display.crtc_compute_clock = pnv_crtc_compute_clock;
15232                 dev_priv->display.crtc_enable = i9xx_crtc_enable;
15233                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
15234         } else if (!IS_GEN2(dev_priv)) {
15235                 dev_priv->display.get_pipe_config = i9xx_get_pipe_config;
15236                 dev_priv->display.get_initial_plane_config =
15237                         i9xx_get_initial_plane_config;
15238                 dev_priv->display.crtc_compute_clock = i9xx_crtc_compute_clock;
15239                 dev_priv->display.crtc_enable = i9xx_crtc_enable;
15240                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
15241         } else {
15242                 dev_priv->display.get_pipe_config = i9xx_get_pipe_config;
15243                 dev_priv->display.get_initial_plane_config =
15244                         i9xx_get_initial_plane_config;
15245                 dev_priv->display.crtc_compute_clock = i8xx_crtc_compute_clock;
15246                 dev_priv->display.crtc_enable = i9xx_crtc_enable;
15247                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
15248         }
15249
15250         /* Returns the core display clock speed */
15251         if (IS_SKYLAKE(dev_priv) || IS_KABYLAKE(dev_priv))
15252                 dev_priv->display.get_display_clock_speed =
15253                         skylake_get_display_clock_speed;
15254         else if (IS_BROXTON(dev_priv))
15255                 dev_priv->display.get_display_clock_speed =
15256                         broxton_get_display_clock_speed;
15257         else if (IS_BROADWELL(dev_priv))
15258                 dev_priv->display.get_display_clock_speed =
15259                         broadwell_get_display_clock_speed;
15260         else if (IS_HASWELL(dev_priv))
15261                 dev_priv->display.get_display_clock_speed =
15262                         haswell_get_display_clock_speed;
15263         else if (IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv))
15264                 dev_priv->display.get_display_clock_speed =
15265                         valleyview_get_display_clock_speed;
15266         else if (IS_GEN5(dev_priv))
15267                 dev_priv->display.get_display_clock_speed =
15268                         ilk_get_display_clock_speed;
15269         else if (IS_I945G(dev_priv) || IS_BROADWATER(dev_priv) ||
15270                  IS_GEN6(dev_priv) || IS_IVYBRIDGE(dev_priv))
15271                 dev_priv->display.get_display_clock_speed =
15272                         i945_get_display_clock_speed;
15273         else if (IS_GM45(dev_priv))
15274                 dev_priv->display.get_display_clock_speed =
15275                         gm45_get_display_clock_speed;
15276         else if (IS_CRESTLINE(dev_priv))
15277                 dev_priv->display.get_display_clock_speed =
15278                         i965gm_get_display_clock_speed;
15279         else if (IS_PINEVIEW(dev_priv))
15280                 dev_priv->display.get_display_clock_speed =
15281                         pnv_get_display_clock_speed;
15282         else if (IS_G33(dev_priv) || IS_G4X(dev_priv))
15283                 dev_priv->display.get_display_clock_speed =
15284                         g33_get_display_clock_speed;
15285         else if (IS_I915G(dev_priv))
15286                 dev_priv->display.get_display_clock_speed =
15287                         i915_get_display_clock_speed;
15288         else if (IS_I945GM(dev_priv) || IS_845G(dev_priv))
15289                 dev_priv->display.get_display_clock_speed =
15290                         i9xx_misc_get_display_clock_speed;
15291         else if (IS_I915GM(dev_priv))
15292                 dev_priv->display.get_display_clock_speed =
15293                         i915gm_get_display_clock_speed;
15294         else if (IS_I865G(dev_priv))
15295                 dev_priv->display.get_display_clock_speed =
15296                         i865_get_display_clock_speed;
15297         else if (IS_I85X(dev_priv))
15298                 dev_priv->display.get_display_clock_speed =
15299                         i85x_get_display_clock_speed;
15300         else { /* 830 */
15301                 WARN(!IS_I830(dev_priv), "Unknown platform. Assuming 133 MHz CDCLK\n");
15302                 dev_priv->display.get_display_clock_speed =
15303                         i830_get_display_clock_speed;
15304         }
15305
15306         if (IS_GEN5(dev_priv)) {
15307                 dev_priv->display.fdi_link_train = ironlake_fdi_link_train;
15308         } else if (IS_GEN6(dev_priv)) {
15309                 dev_priv->display.fdi_link_train = gen6_fdi_link_train;
15310         } else if (IS_IVYBRIDGE(dev_priv)) {
15311                 /* FIXME: detect B0+ stepping and use auto training */
15312                 dev_priv->display.fdi_link_train = ivb_manual_fdi_link_train;
15313         } else if (IS_HASWELL(dev_priv) || IS_BROADWELL(dev_priv)) {
15314                 dev_priv->display.fdi_link_train = hsw_fdi_link_train;
15315         }
15316
15317         if (IS_BROADWELL(dev_priv)) {
15318                 dev_priv->display.modeset_commit_cdclk =
15319                         broadwell_modeset_commit_cdclk;
15320                 dev_priv->display.modeset_calc_cdclk =
15321                         broadwell_modeset_calc_cdclk;
15322         } else if (IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv)) {
15323                 dev_priv->display.modeset_commit_cdclk =
15324                         valleyview_modeset_commit_cdclk;
15325                 dev_priv->display.modeset_calc_cdclk =
15326                         valleyview_modeset_calc_cdclk;
15327         } else if (IS_BROXTON(dev_priv)) {
15328                 dev_priv->display.modeset_commit_cdclk =
15329                         bxt_modeset_commit_cdclk;
15330                 dev_priv->display.modeset_calc_cdclk =
15331                         bxt_modeset_calc_cdclk;
15332         } else if (IS_SKYLAKE(dev_priv) || IS_KABYLAKE(dev_priv)) {
15333                 dev_priv->display.modeset_commit_cdclk =
15334                         skl_modeset_commit_cdclk;
15335                 dev_priv->display.modeset_calc_cdclk =
15336                         skl_modeset_calc_cdclk;
15337         }
15338
15339         switch (INTEL_INFO(dev_priv)->gen) {
15340         case 2:
15341                 dev_priv->display.queue_flip = intel_gen2_queue_flip;
15342                 break;
15343
15344         case 3:
15345                 dev_priv->display.queue_flip = intel_gen3_queue_flip;
15346                 break;
15347
15348         case 4:
15349         case 5:
15350                 dev_priv->display.queue_flip = intel_gen4_queue_flip;
15351                 break;
15352
15353         case 6:
15354                 dev_priv->display.queue_flip = intel_gen6_queue_flip;
15355                 break;
15356         case 7:
15357         case 8: /* FIXME(BDW): Check that the gen8 RCS flip works. */
15358                 dev_priv->display.queue_flip = intel_gen7_queue_flip;
15359                 break;
15360         case 9:
15361                 /* Drop through - unsupported since execlist only. */
15362         default:
15363                 /* Default just returns -ENODEV to indicate unsupported */
15364                 dev_priv->display.queue_flip = intel_default_queue_flip;
15365         }
15366 }
15367
15368 /*
15369  * Some BIOSes insist on assuming the GPU's pipe A is enabled at suspend,
15370  * resume, or other times.  This quirk makes sure that's the case for
15371  * affected systems.
15372  */
15373 static void quirk_pipea_force(struct drm_device *dev)
15374 {
15375         struct drm_i915_private *dev_priv = to_i915(dev);
15376
15377         dev_priv->quirks |= QUIRK_PIPEA_FORCE;
15378         DRM_INFO("applying pipe a force quirk\n");
15379 }
15380
15381 static void quirk_pipeb_force(struct drm_device *dev)
15382 {
15383         struct drm_i915_private *dev_priv = to_i915(dev);
15384
15385         dev_priv->quirks |= QUIRK_PIPEB_FORCE;
15386         DRM_INFO("applying pipe b force quirk\n");
15387 }
15388
15389 /*
15390  * Some machines (Lenovo U160) do not work with SSC on LVDS for some reason
15391  */
15392 static void quirk_ssc_force_disable(struct drm_device *dev)
15393 {
15394         struct drm_i915_private *dev_priv = to_i915(dev);
15395         dev_priv->quirks |= QUIRK_LVDS_SSC_DISABLE;
15396         DRM_INFO("applying lvds SSC disable quirk\n");
15397 }
15398
15399 /*
15400  * A machine (e.g. Acer Aspire 5734Z) may need to invert the panel backlight
15401  * brightness value
15402  */
15403 static void quirk_invert_brightness(struct drm_device *dev)
15404 {
15405         struct drm_i915_private *dev_priv = to_i915(dev);
15406         dev_priv->quirks |= QUIRK_INVERT_BRIGHTNESS;
15407         DRM_INFO("applying inverted panel brightness quirk\n");
15408 }
15409
15410 /* Some VBT's incorrectly indicate no backlight is present */
15411 static void quirk_backlight_present(struct drm_device *dev)
15412 {
15413         struct drm_i915_private *dev_priv = to_i915(dev);
15414         dev_priv->quirks |= QUIRK_BACKLIGHT_PRESENT;
15415         DRM_INFO("applying backlight present quirk\n");
15416 }
15417
15418 struct intel_quirk {
15419         int device;
15420         int subsystem_vendor;
15421         int subsystem_device;
15422         void (*hook)(struct drm_device *dev);
15423 };
15424
15425 /* For systems that don't have a meaningful PCI subdevice/subvendor ID */
15426 struct intel_dmi_quirk {
15427         void (*hook)(struct drm_device *dev);
15428         const struct dmi_system_id (*dmi_id_list)[];
15429 };
15430
15431 static int intel_dmi_reverse_brightness(const struct dmi_system_id *id)
15432 {
15433         DRM_INFO("Backlight polarity reversed on %s\n", id->ident);
15434         return 1;
15435 }
15436
15437 static const struct intel_dmi_quirk intel_dmi_quirks[] = {
15438         {
15439                 .dmi_id_list = &(const struct dmi_system_id[]) {
15440                         {
15441                                 .callback = intel_dmi_reverse_brightness,
15442                                 .ident = "NCR Corporation",
15443                                 .matches = {DMI_MATCH(DMI_SYS_VENDOR, "NCR Corporation"),
15444                                             DMI_MATCH(DMI_PRODUCT_NAME, ""),
15445                                 },
15446                         },
15447                         { }  /* terminating entry */
15448                 },
15449                 .hook = quirk_invert_brightness,
15450         },
15451 };
15452
15453 static struct intel_quirk intel_quirks[] = {
15454         /* Toshiba Protege R-205, S-209 needs pipe A force quirk */
15455         { 0x2592, 0x1179, 0x0001, quirk_pipea_force },
15456
15457         /* ThinkPad T60 needs pipe A force quirk (bug #16494) */
15458         { 0x2782, 0x17aa, 0x201a, quirk_pipea_force },
15459
15460         /* 830 needs to leave pipe A & dpll A up */
15461         { 0x3577, PCI_ANY_ID, PCI_ANY_ID, quirk_pipea_force },
15462
15463         /* 830 needs to leave pipe B & dpll B up */
15464         { 0x3577, PCI_ANY_ID, PCI_ANY_ID, quirk_pipeb_force },
15465
15466         /* Lenovo U160 cannot use SSC on LVDS */
15467         { 0x0046, 0x17aa, 0x3920, quirk_ssc_force_disable },
15468
15469         /* Sony Vaio Y cannot use SSC on LVDS */
15470         { 0x0046, 0x104d, 0x9076, quirk_ssc_force_disable },
15471
15472         /* Acer Aspire 5734Z must invert backlight brightness */
15473         { 0x2a42, 0x1025, 0x0459, quirk_invert_brightness },
15474
15475         /* Acer/eMachines G725 */
15476         { 0x2a42, 0x1025, 0x0210, quirk_invert_brightness },
15477
15478         /* Acer/eMachines e725 */
15479         { 0x2a42, 0x1025, 0x0212, quirk_invert_brightness },
15480
15481         /* Acer/Packard Bell NCL20 */
15482         { 0x2a42, 0x1025, 0x034b, quirk_invert_brightness },
15483
15484         /* Acer Aspire 4736Z */
15485         { 0x2a42, 0x1025, 0x0260, quirk_invert_brightness },
15486
15487         /* Acer Aspire 5336 */
15488         { 0x2a42, 0x1025, 0x048a, quirk_invert_brightness },
15489
15490         /* Acer C720 and C720P Chromebooks (Celeron 2955U) have backlights */
15491         { 0x0a06, 0x1025, 0x0a11, quirk_backlight_present },
15492
15493         /* Acer C720 Chromebook (Core i3 4005U) */
15494         { 0x0a16, 0x1025, 0x0a11, quirk_backlight_present },
15495
15496         /* Apple Macbook 2,1 (Core 2 T7400) */
15497         { 0x27a2, 0x8086, 0x7270, quirk_backlight_present },
15498
15499         /* Apple Macbook 4,1 */
15500         { 0x2a02, 0x106b, 0x00a1, quirk_backlight_present },
15501
15502         /* Toshiba CB35 Chromebook (Celeron 2955U) */
15503         { 0x0a06, 0x1179, 0x0a88, quirk_backlight_present },
15504
15505         /* HP Chromebook 14 (Celeron 2955U) */
15506         { 0x0a06, 0x103c, 0x21ed, quirk_backlight_present },
15507
15508         /* Dell Chromebook 11 */
15509         { 0x0a06, 0x1028, 0x0a35, quirk_backlight_present },
15510
15511         /* Dell Chromebook 11 (2015 version) */
15512         { 0x0a16, 0x1028, 0x0a35, quirk_backlight_present },
15513 };
15514
15515 static void intel_init_quirks(struct drm_device *dev)
15516 {
15517         struct pci_dev *d = dev->pdev;
15518         int i;
15519
15520         for (i = 0; i < ARRAY_SIZE(intel_quirks); i++) {
15521                 struct intel_quirk *q = &intel_quirks[i];
15522
15523                 if (d->device == q->device &&
15524                     (d->subsystem_vendor == q->subsystem_vendor ||
15525                      q->subsystem_vendor == PCI_ANY_ID) &&
15526                     (d->subsystem_device == q->subsystem_device ||
15527                      q->subsystem_device == PCI_ANY_ID))
15528                         q->hook(dev);
15529         }
15530         for (i = 0; i < ARRAY_SIZE(intel_dmi_quirks); i++) {
15531                 if (dmi_check_system(*intel_dmi_quirks[i].dmi_id_list) != 0)
15532                         intel_dmi_quirks[i].hook(dev);
15533         }
15534 }
15535
15536 /* Disable the VGA plane that we never use */
15537 static void i915_disable_vga(struct drm_device *dev)
15538 {
15539         struct drm_i915_private *dev_priv = to_i915(dev);
15540         u8 sr1;
15541         i915_reg_t vga_reg = i915_vgacntrl_reg(dev);
15542
15543         /* WaEnableVGAAccessThroughIOPort:ctg,elk,ilk,snb,ivb,vlv,hsw */
15544         vga_get_uninterruptible(dev->pdev, VGA_RSRC_LEGACY_IO);
15545         outb(SR01, VGA_SR_INDEX);
15546         sr1 = inb(VGA_SR_DATA);
15547         outb(sr1 | 1<<5, VGA_SR_DATA);
15548         vga_put(dev->pdev, VGA_RSRC_LEGACY_IO);
15549         udelay(300);
15550
15551         I915_WRITE(vga_reg, VGA_DISP_DISABLE);
15552         POSTING_READ(vga_reg);
15553 }
15554
15555 void intel_modeset_init_hw(struct drm_device *dev)
15556 {
15557         struct drm_i915_private *dev_priv = to_i915(dev);
15558
15559         intel_update_cdclk(dev);
15560
15561         dev_priv->atomic_cdclk_freq = dev_priv->cdclk_freq;
15562
15563         intel_init_clock_gating(dev);
15564         intel_enable_gt_powersave(dev_priv);
15565 }
15566
15567 /*
15568  * Calculate what we think the watermarks should be for the state we've read
15569  * out of the hardware and then immediately program those watermarks so that
15570  * we ensure the hardware settings match our internal state.
15571  *
15572  * We can calculate what we think WM's should be by creating a duplicate of the
15573  * current state (which was constructed during hardware readout) and running it
15574  * through the atomic check code to calculate new watermark values in the
15575  * state object.
15576  */
15577 static void sanitize_watermarks(struct drm_device *dev)
15578 {
15579         struct drm_i915_private *dev_priv = to_i915(dev);
15580         struct drm_atomic_state *state;
15581         struct drm_crtc *crtc;
15582         struct drm_crtc_state *cstate;
15583         struct drm_modeset_acquire_ctx ctx;
15584         int ret;
15585         int i;
15586
15587         /* Only supported on platforms that use atomic watermark design */
15588         if (!dev_priv->display.optimize_watermarks)
15589                 return;
15590
15591         /*
15592          * We need to hold connection_mutex before calling duplicate_state so
15593          * that the connector loop is protected.
15594          */
15595         drm_modeset_acquire_init(&ctx, 0);
15596 retry:
15597         ret = drm_modeset_lock_all_ctx(dev, &ctx);
15598         if (ret == -EDEADLK) {
15599                 drm_modeset_backoff(&ctx);
15600                 goto retry;
15601         } else if (WARN_ON(ret)) {
15602                 goto fail;
15603         }
15604
15605         state = drm_atomic_helper_duplicate_state(dev, &ctx);
15606         if (WARN_ON(IS_ERR(state)))
15607                 goto fail;
15608
15609         /*
15610          * Hardware readout is the only time we don't want to calculate
15611          * intermediate watermarks (since we don't trust the current
15612          * watermarks).
15613          */
15614         to_intel_atomic_state(state)->skip_intermediate_wm = true;
15615
15616         ret = intel_atomic_check(dev, state);
15617         if (ret) {
15618                 /*
15619                  * If we fail here, it means that the hardware appears to be
15620                  * programmed in a way that shouldn't be possible, given our
15621                  * understanding of watermark requirements.  This might mean a
15622                  * mistake in the hardware readout code or a mistake in the
15623                  * watermark calculations for a given platform.  Raise a WARN
15624                  * so that this is noticeable.
15625                  *
15626                  * If this actually happens, we'll have to just leave the
15627                  * BIOS-programmed watermarks untouched and hope for the best.
15628                  */
15629                 WARN(true, "Could not determine valid watermarks for inherited state\n");
15630                 goto fail;
15631         }
15632
15633         /* Write calculated watermark values back */
15634         for_each_crtc_in_state(state, crtc, cstate, i) {
15635                 struct intel_crtc_state *cs = to_intel_crtc_state(cstate);
15636
15637                 cs->wm.need_postvbl_update = true;
15638                 dev_priv->display.optimize_watermarks(cs);
15639         }
15640
15641         drm_atomic_state_free(state);
15642 fail:
15643         drm_modeset_drop_locks(&ctx);
15644         drm_modeset_acquire_fini(&ctx);
15645 }
15646
15647 void intel_modeset_init(struct drm_device *dev)
15648 {
15649         struct drm_i915_private *dev_priv = to_i915(dev);
15650         struct i915_ggtt *ggtt = &dev_priv->ggtt;
15651         int sprite, ret;
15652         enum pipe pipe;
15653         struct intel_crtc *crtc;
15654
15655         drm_mode_config_init(dev);
15656
15657         dev->mode_config.min_width = 0;
15658         dev->mode_config.min_height = 0;
15659
15660         dev->mode_config.preferred_depth = 24;
15661         dev->mode_config.prefer_shadow = 1;
15662
15663         dev->mode_config.allow_fb_modifiers = true;
15664
15665         dev->mode_config.funcs = &intel_mode_funcs;
15666
15667         intel_init_quirks(dev);
15668
15669         intel_init_pm(dev);
15670
15671         if (INTEL_INFO(dev)->num_pipes == 0)
15672                 return;
15673
15674         /*
15675          * There may be no VBT; and if the BIOS enabled SSC we can
15676          * just keep using it to avoid unnecessary flicker.  Whereas if the
15677          * BIOS isn't using it, don't assume it will work even if the VBT
15678          * indicates as much.
15679          */
15680         if (HAS_PCH_IBX(dev) || HAS_PCH_CPT(dev)) {
15681                 bool bios_lvds_use_ssc = !!(I915_READ(PCH_DREF_CONTROL) &
15682                                             DREF_SSC1_ENABLE);
15683
15684                 if (dev_priv->vbt.lvds_use_ssc != bios_lvds_use_ssc) {
15685                         DRM_DEBUG_KMS("SSC %sabled by BIOS, overriding VBT which says %sabled\n",
15686                                      bios_lvds_use_ssc ? "en" : "dis",
15687                                      dev_priv->vbt.lvds_use_ssc ? "en" : "dis");
15688                         dev_priv->vbt.lvds_use_ssc = bios_lvds_use_ssc;
15689                 }
15690         }
15691
15692         if (IS_GEN2(dev)) {
15693                 dev->mode_config.max_width = 2048;
15694                 dev->mode_config.max_height = 2048;
15695         } else if (IS_GEN3(dev)) {
15696                 dev->mode_config.max_width = 4096;
15697                 dev->mode_config.max_height = 4096;
15698         } else {
15699                 dev->mode_config.max_width = 8192;
15700                 dev->mode_config.max_height = 8192;
15701         }
15702
15703         if (IS_845G(dev) || IS_I865G(dev)) {
15704                 dev->mode_config.cursor_width = IS_845G(dev) ? 64 : 512;
15705                 dev->mode_config.cursor_height = 1023;
15706         } else if (IS_GEN2(dev)) {
15707                 dev->mode_config.cursor_width = GEN2_CURSOR_WIDTH;
15708                 dev->mode_config.cursor_height = GEN2_CURSOR_HEIGHT;
15709         } else {
15710                 dev->mode_config.cursor_width = MAX_CURSOR_WIDTH;
15711                 dev->mode_config.cursor_height = MAX_CURSOR_HEIGHT;
15712         }
15713
15714         dev->mode_config.fb_base = ggtt->mappable_base;
15715
15716         DRM_DEBUG_KMS("%d display pipe%s available.\n",
15717                       INTEL_INFO(dev)->num_pipes,
15718                       INTEL_INFO(dev)->num_pipes > 1 ? "s" : "");
15719
15720         for_each_pipe(dev_priv, pipe) {
15721                 intel_crtc_init(dev, pipe);
15722                 for_each_sprite(dev_priv, pipe, sprite) {
15723                         ret = intel_plane_init(dev, pipe, sprite);
15724                         if (ret)
15725                                 DRM_DEBUG_KMS("pipe %c sprite %c init failed: %d\n",
15726                                               pipe_name(pipe), sprite_name(pipe, sprite), ret);
15727                 }
15728         }
15729
15730         intel_update_czclk(dev_priv);
15731         intel_update_cdclk(dev);
15732
15733         intel_shared_dpll_init(dev);
15734
15735         if (dev_priv->max_cdclk_freq == 0)
15736                 intel_update_max_cdclk(dev);
15737
15738         /* Just disable it once at startup */
15739         i915_disable_vga(dev);
15740         intel_setup_outputs(dev);
15741
15742         drm_modeset_lock_all(dev);
15743         intel_modeset_setup_hw_state(dev);
15744         drm_modeset_unlock_all(dev);
15745
15746         for_each_intel_crtc(dev, crtc) {
15747                 struct intel_initial_plane_config plane_config = {};
15748
15749                 if (!crtc->active)
15750                         continue;
15751
15752                 /*
15753                  * Note that reserving the BIOS fb up front prevents us
15754                  * from stuffing other stolen allocations like the ring
15755                  * on top.  This prevents some ugliness at boot time, and
15756                  * can even allow for smooth boot transitions if the BIOS
15757                  * fb is large enough for the active pipe configuration.
15758                  */
15759                 dev_priv->display.get_initial_plane_config(crtc,
15760                                                            &plane_config);
15761
15762                 /*
15763                  * If the fb is shared between multiple heads, we'll
15764                  * just get the first one.
15765                  */
15766                 intel_find_initial_plane_obj(crtc, &plane_config);
15767         }
15768
15769         /*
15770          * Make sure hardware watermarks really match the state we read out.
15771          * Note that we need to do this after reconstructing the BIOS fb's
15772          * since the watermark calculation done here will use pstate->fb.
15773          */
15774         sanitize_watermarks(dev);
15775 }
15776
15777 static void intel_enable_pipe_a(struct drm_device *dev)
15778 {
15779         struct intel_connector *connector;
15780         struct drm_connector *crt = NULL;
15781         struct intel_load_detect_pipe load_detect_temp;
15782         struct drm_modeset_acquire_ctx *ctx = dev->mode_config.acquire_ctx;
15783
15784         /* We can't just switch on the pipe A, we need to set things up with a
15785          * proper mode and output configuration. As a gross hack, enable pipe A
15786          * by enabling the load detect pipe once. */
15787         for_each_intel_connector(dev, connector) {
15788                 if (connector->encoder->type == INTEL_OUTPUT_ANALOG) {
15789                         crt = &connector->base;
15790                         break;
15791                 }
15792         }
15793
15794         if (!crt)
15795                 return;
15796
15797         if (intel_get_load_detect_pipe(crt, NULL, &load_detect_temp, ctx))
15798                 intel_release_load_detect_pipe(crt, &load_detect_temp, ctx);
15799 }
15800
15801 static bool
15802 intel_check_plane_mapping(struct intel_crtc *crtc)
15803 {
15804         struct drm_device *dev = crtc->base.dev;
15805         struct drm_i915_private *dev_priv = to_i915(dev);
15806         u32 val;
15807
15808         if (INTEL_INFO(dev)->num_pipes == 1)
15809                 return true;
15810
15811         val = I915_READ(DSPCNTR(!crtc->plane));
15812
15813         if ((val & DISPLAY_PLANE_ENABLE) &&
15814             (!!(val & DISPPLANE_SEL_PIPE_MASK) == crtc->pipe))
15815                 return false;
15816
15817         return true;
15818 }
15819
15820 static bool intel_crtc_has_encoders(struct intel_crtc *crtc)
15821 {
15822         struct drm_device *dev = crtc->base.dev;
15823         struct intel_encoder *encoder;
15824
15825         for_each_encoder_on_crtc(dev, &crtc->base, encoder)
15826                 return true;
15827
15828         return false;
15829 }
15830
15831 static bool intel_encoder_has_connectors(struct intel_encoder *encoder)
15832 {
15833         struct drm_device *dev = encoder->base.dev;
15834         struct intel_connector *connector;
15835
15836         for_each_connector_on_encoder(dev, &encoder->base, connector)
15837                 return true;
15838
15839         return false;
15840 }
15841
15842 static void intel_sanitize_crtc(struct intel_crtc *crtc)
15843 {
15844         struct drm_device *dev = crtc->base.dev;
15845         struct drm_i915_private *dev_priv = to_i915(dev);
15846         enum transcoder cpu_transcoder = crtc->config->cpu_transcoder;
15847
15848         /* Clear any frame start delays used for debugging left by the BIOS */
15849         if (!transcoder_is_dsi(cpu_transcoder)) {
15850                 i915_reg_t reg = PIPECONF(cpu_transcoder);
15851
15852                 I915_WRITE(reg,
15853                            I915_READ(reg) & ~PIPECONF_FRAME_START_DELAY_MASK);
15854         }
15855
15856         /* restore vblank interrupts to correct state */
15857         drm_crtc_vblank_reset(&crtc->base);
15858         if (crtc->active) {
15859                 struct intel_plane *plane;
15860
15861                 drm_crtc_vblank_on(&crtc->base);
15862
15863                 /* Disable everything but the primary plane */
15864                 for_each_intel_plane_on_crtc(dev, crtc, plane) {
15865                         if (plane->base.type == DRM_PLANE_TYPE_PRIMARY)
15866                                 continue;
15867
15868                         plane->disable_plane(&plane->base, &crtc->base);
15869                 }
15870         }
15871
15872         /* We need to sanitize the plane -> pipe mapping first because this will
15873          * disable the crtc (and hence change the state) if it is wrong. Note
15874          * that gen4+ has a fixed plane -> pipe mapping.  */
15875         if (INTEL_INFO(dev)->gen < 4 && !intel_check_plane_mapping(crtc)) {
15876                 bool plane;
15877
15878                 DRM_DEBUG_KMS("[CRTC:%d:%s] wrong plane connection detected!\n",
15879                               crtc->base.base.id, crtc->base.name);
15880
15881                 /* Pipe has the wrong plane attached and the plane is active.
15882                  * Temporarily change the plane mapping and disable everything
15883                  * ...  */
15884                 plane = crtc->plane;
15885                 to_intel_plane_state(crtc->base.primary->state)->visible = true;
15886                 crtc->plane = !plane;
15887                 intel_crtc_disable_noatomic(&crtc->base);
15888                 crtc->plane = plane;
15889         }
15890
15891         if (dev_priv->quirks & QUIRK_PIPEA_FORCE &&
15892             crtc->pipe == PIPE_A && !crtc->active) {
15893                 /* BIOS forgot to enable pipe A, this mostly happens after
15894                  * resume. Force-enable the pipe to fix this, the update_dpms
15895                  * call below we restore the pipe to the right state, but leave
15896                  * the required bits on. */
15897                 intel_enable_pipe_a(dev);
15898         }
15899
15900         /* Adjust the state of the output pipe according to whether we
15901          * have active connectors/encoders. */
15902         if (crtc->active && !intel_crtc_has_encoders(crtc))
15903                 intel_crtc_disable_noatomic(&crtc->base);
15904
15905         if (crtc->active || HAS_GMCH_DISPLAY(dev)) {
15906                 /*
15907                  * We start out with underrun reporting disabled to avoid races.
15908                  * For correct bookkeeping mark this on active crtcs.
15909                  *
15910                  * Also on gmch platforms we dont have any hardware bits to
15911                  * disable the underrun reporting. Which means we need to start
15912                  * out with underrun reporting disabled also on inactive pipes,
15913                  * since otherwise we'll complain about the garbage we read when
15914                  * e.g. coming up after runtime pm.
15915                  *
15916                  * No protection against concurrent access is required - at
15917                  * worst a fifo underrun happens which also sets this to false.
15918                  */
15919                 crtc->cpu_fifo_underrun_disabled = true;
15920                 crtc->pch_fifo_underrun_disabled = true;
15921         }
15922 }
15923
15924 static void intel_sanitize_encoder(struct intel_encoder *encoder)
15925 {
15926         struct intel_connector *connector;
15927         struct drm_device *dev = encoder->base.dev;
15928
15929         /* We need to check both for a crtc link (meaning that the
15930          * encoder is active and trying to read from a pipe) and the
15931          * pipe itself being active. */
15932         bool has_active_crtc = encoder->base.crtc &&
15933                 to_intel_crtc(encoder->base.crtc)->active;
15934
15935         if (intel_encoder_has_connectors(encoder) && !has_active_crtc) {
15936                 DRM_DEBUG_KMS("[ENCODER:%d:%s] has active connectors but no active pipe!\n",
15937                               encoder->base.base.id,
15938                               encoder->base.name);
15939
15940                 /* Connector is active, but has no active pipe. This is
15941                  * fallout from our resume register restoring. Disable
15942                  * the encoder manually again. */
15943                 if (encoder->base.crtc) {
15944                         DRM_DEBUG_KMS("[ENCODER:%d:%s] manually disabled\n",
15945                                       encoder->base.base.id,
15946                                       encoder->base.name);
15947                         encoder->disable(encoder);
15948                         if (encoder->post_disable)
15949                                 encoder->post_disable(encoder);
15950                 }
15951                 encoder->base.crtc = NULL;
15952
15953                 /* Inconsistent output/port/pipe state happens presumably due to
15954                  * a bug in one of the get_hw_state functions. Or someplace else
15955                  * in our code, like the register restore mess on resume. Clamp
15956                  * things to off as a safer default. */
15957                 for_each_intel_connector(dev, connector) {
15958                         if (connector->encoder != encoder)
15959                                 continue;
15960                         connector->base.dpms = DRM_MODE_DPMS_OFF;
15961                         connector->base.encoder = NULL;
15962                 }
15963         }
15964         /* Enabled encoders without active connectors will be fixed in
15965          * the crtc fixup. */
15966 }
15967
15968 void i915_redisable_vga_power_on(struct drm_device *dev)
15969 {
15970         struct drm_i915_private *dev_priv = to_i915(dev);
15971         i915_reg_t vga_reg = i915_vgacntrl_reg(dev);
15972
15973         if (!(I915_READ(vga_reg) & VGA_DISP_DISABLE)) {
15974                 DRM_DEBUG_KMS("Something enabled VGA plane, disabling it\n");
15975                 i915_disable_vga(dev);
15976         }
15977 }
15978
15979 void i915_redisable_vga(struct drm_device *dev)
15980 {
15981         struct drm_i915_private *dev_priv = to_i915(dev);
15982
15983         /* This function can be called both from intel_modeset_setup_hw_state or
15984          * at a very early point in our resume sequence, where the power well
15985          * structures are not yet restored. Since this function is at a very
15986          * paranoid "someone might have enabled VGA while we were not looking"
15987          * level, just check if the power well is enabled instead of trying to
15988          * follow the "don't touch the power well if we don't need it" policy
15989          * the rest of the driver uses. */
15990         if (!intel_display_power_get_if_enabled(dev_priv, POWER_DOMAIN_VGA))
15991                 return;
15992
15993         i915_redisable_vga_power_on(dev);
15994
15995         intel_display_power_put(dev_priv, POWER_DOMAIN_VGA);
15996 }
15997
15998 static bool primary_get_hw_state(struct intel_plane *plane)
15999 {
16000         struct drm_i915_private *dev_priv = to_i915(plane->base.dev);
16001
16002         return I915_READ(DSPCNTR(plane->plane)) & DISPLAY_PLANE_ENABLE;
16003 }
16004
16005 /* FIXME read out full plane state for all planes */
16006 static void readout_plane_state(struct intel_crtc *crtc)
16007 {
16008         struct drm_plane *primary = crtc->base.primary;
16009         struct intel_plane_state *plane_state =
16010                 to_intel_plane_state(primary->state);
16011
16012         plane_state->visible = crtc->active &&
16013                 primary_get_hw_state(to_intel_plane(primary));
16014
16015         if (plane_state->visible)
16016                 crtc->base.state->plane_mask |= 1 << drm_plane_index(primary);
16017 }
16018
16019 static void intel_modeset_readout_hw_state(struct drm_device *dev)
16020 {
16021         struct drm_i915_private *dev_priv = to_i915(dev);
16022         enum pipe pipe;
16023         struct intel_crtc *crtc;
16024         struct intel_encoder *encoder;
16025         struct intel_connector *connector;
16026         int i;
16027
16028         dev_priv->active_crtcs = 0;
16029
16030         for_each_intel_crtc(dev, crtc) {
16031                 struct intel_crtc_state *crtc_state = crtc->config;
16032                 int pixclk = 0;
16033
16034                 __drm_atomic_helper_crtc_destroy_state(&crtc_state->base);
16035                 memset(crtc_state, 0, sizeof(*crtc_state));
16036                 crtc_state->base.crtc = &crtc->base;
16037
16038                 crtc_state->base.active = crtc_state->base.enable =
16039                         dev_priv->display.get_pipe_config(crtc, crtc_state);
16040
16041                 crtc->base.enabled = crtc_state->base.enable;
16042                 crtc->active = crtc_state->base.active;
16043
16044                 if (crtc_state->base.active) {
16045                         dev_priv->active_crtcs |= 1 << crtc->pipe;
16046
16047                         if (INTEL_GEN(dev_priv) >= 9 || IS_BROADWELL(dev_priv))
16048                                 pixclk = ilk_pipe_pixel_rate(crtc_state);
16049                         else if (IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv))
16050                                 pixclk = crtc_state->base.adjusted_mode.crtc_clock;
16051                         else
16052                                 WARN_ON(dev_priv->display.modeset_calc_cdclk);
16053
16054                         /* pixel rate mustn't exceed 95% of cdclk with IPS on BDW */
16055                         if (IS_BROADWELL(dev_priv) && crtc_state->ips_enabled)
16056                                 pixclk = DIV_ROUND_UP(pixclk * 100, 95);
16057                 }
16058
16059                 dev_priv->min_pixclk[crtc->pipe] = pixclk;
16060
16061                 readout_plane_state(crtc);
16062
16063                 DRM_DEBUG_KMS("[CRTC:%d:%s] hw state readout: %s\n",
16064                               crtc->base.base.id, crtc->base.name,
16065                               crtc->active ? "enabled" : "disabled");
16066         }
16067
16068         for (i = 0; i < dev_priv->num_shared_dpll; i++) {
16069                 struct intel_shared_dpll *pll = &dev_priv->shared_dplls[i];
16070
16071                 pll->on = pll->funcs.get_hw_state(dev_priv, pll,
16072                                                   &pll->config.hw_state);
16073                 pll->config.crtc_mask = 0;
16074                 for_each_intel_crtc(dev, crtc) {
16075                         if (crtc->active && crtc->config->shared_dpll == pll)
16076                                 pll->config.crtc_mask |= 1 << crtc->pipe;
16077                 }
16078                 pll->active_mask = pll->config.crtc_mask;
16079
16080                 DRM_DEBUG_KMS("%s hw state readout: crtc_mask 0x%08x, on %i\n",
16081                               pll->name, pll->config.crtc_mask, pll->on);
16082         }
16083
16084         for_each_intel_encoder(dev, encoder) {
16085                 pipe = 0;
16086
16087                 if (encoder->get_hw_state(encoder, &pipe)) {
16088                         crtc = to_intel_crtc(dev_priv->pipe_to_crtc_mapping[pipe]);
16089                         encoder->base.crtc = &crtc->base;
16090                         crtc->config->output_types |= 1 << encoder->type;
16091                         encoder->get_config(encoder, crtc->config);
16092                 } else {
16093                         encoder->base.crtc = NULL;
16094                 }
16095
16096                 DRM_DEBUG_KMS("[ENCODER:%d:%s] hw state readout: %s, pipe %c\n",
16097                               encoder->base.base.id,
16098                               encoder->base.name,
16099                               encoder->base.crtc ? "enabled" : "disabled",
16100                               pipe_name(pipe));
16101         }
16102
16103         for_each_intel_connector(dev, connector) {
16104                 if (connector->get_hw_state(connector)) {
16105                         connector->base.dpms = DRM_MODE_DPMS_ON;
16106
16107                         encoder = connector->encoder;
16108                         connector->base.encoder = &encoder->base;
16109
16110                         if (encoder->base.crtc &&
16111                             encoder->base.crtc->state->active) {
16112                                 /*
16113                                  * This has to be done during hardware readout
16114                                  * because anything calling .crtc_disable may
16115                                  * rely on the connector_mask being accurate.
16116                                  */
16117                                 encoder->base.crtc->state->connector_mask |=
16118                                         1 << drm_connector_index(&connector->base);
16119                                 encoder->base.crtc->state->encoder_mask |=
16120                                         1 << drm_encoder_index(&encoder->base);
16121                         }
16122
16123                 } else {
16124                         connector->base.dpms = DRM_MODE_DPMS_OFF;
16125                         connector->base.encoder = NULL;
16126                 }
16127                 DRM_DEBUG_KMS("[CONNECTOR:%d:%s] hw state readout: %s\n",
16128                               connector->base.base.id,
16129                               connector->base.name,
16130                               connector->base.encoder ? "enabled" : "disabled");
16131         }
16132
16133         for_each_intel_crtc(dev, crtc) {
16134                 crtc->base.hwmode = crtc->config->base.adjusted_mode;
16135
16136                 memset(&crtc->base.mode, 0, sizeof(crtc->base.mode));
16137                 if (crtc->base.state->active) {
16138                         intel_mode_from_pipe_config(&crtc->base.mode, crtc->config);
16139                         intel_mode_from_pipe_config(&crtc->base.state->adjusted_mode, crtc->config);
16140                         WARN_ON(drm_atomic_set_mode_for_crtc(crtc->base.state, &crtc->base.mode));
16141
16142                         /*
16143                          * The initial mode needs to be set in order to keep
16144                          * the atomic core happy. It wants a valid mode if the
16145                          * crtc's enabled, so we do the above call.
16146                          *
16147                          * At this point some state updated by the connectors
16148                          * in their ->detect() callback has not run yet, so
16149                          * no recalculation can be done yet.
16150                          *
16151                          * Even if we could do a recalculation and modeset
16152                          * right now it would cause a double modeset if
16153                          * fbdev or userspace chooses a different initial mode.
16154                          *
16155                          * If that happens, someone indicated they wanted a
16156                          * mode change, which means it's safe to do a full
16157                          * recalculation.
16158                          */
16159                         crtc->base.state->mode.private_flags = I915_MODE_FLAG_INHERITED;
16160
16161                         drm_calc_timestamping_constants(&crtc->base, &crtc->base.hwmode);
16162                         update_scanline_offset(crtc);
16163                 }
16164
16165                 intel_pipe_config_sanity_check(dev_priv, crtc->config);
16166         }
16167 }
16168
16169 /* Scan out the current hw modeset state,
16170  * and sanitizes it to the current state
16171  */
16172 static void
16173 intel_modeset_setup_hw_state(struct drm_device *dev)
16174 {
16175         struct drm_i915_private *dev_priv = to_i915(dev);
16176         enum pipe pipe;
16177         struct intel_crtc *crtc;
16178         struct intel_encoder *encoder;
16179         int i;
16180
16181         intel_modeset_readout_hw_state(dev);
16182
16183         /* HW state is read out, now we need to sanitize this mess. */
16184         for_each_intel_encoder(dev, encoder) {
16185                 intel_sanitize_encoder(encoder);
16186         }
16187
16188         for_each_pipe(dev_priv, pipe) {
16189                 crtc = to_intel_crtc(dev_priv->pipe_to_crtc_mapping[pipe]);
16190                 intel_sanitize_crtc(crtc);
16191                 intel_dump_pipe_config(crtc, crtc->config,
16192                                        "[setup_hw_state]");
16193         }
16194
16195         intel_modeset_update_connector_atomic_state(dev);
16196
16197         for (i = 0; i < dev_priv->num_shared_dpll; i++) {
16198                 struct intel_shared_dpll *pll = &dev_priv->shared_dplls[i];
16199
16200                 if (!pll->on || pll->active_mask)
16201                         continue;
16202
16203                 DRM_DEBUG_KMS("%s enabled but not in use, disabling\n", pll->name);
16204
16205                 pll->funcs.disable(dev_priv, pll);
16206                 pll->on = false;
16207         }
16208
16209         if (IS_VALLEYVIEW(dev) || IS_CHERRYVIEW(dev))
16210                 vlv_wm_get_hw_state(dev);
16211         else if (IS_GEN9(dev))
16212                 skl_wm_get_hw_state(dev);
16213         else if (HAS_PCH_SPLIT(dev))
16214                 ilk_wm_get_hw_state(dev);
16215
16216         for_each_intel_crtc(dev, crtc) {
16217                 unsigned long put_domains;
16218
16219                 put_domains = modeset_get_crtc_power_domains(&crtc->base, crtc->config);
16220                 if (WARN_ON(put_domains))
16221                         modeset_put_power_domains(dev_priv, put_domains);
16222         }
16223         intel_display_set_init_power(dev_priv, false);
16224
16225         intel_fbc_init_pipe_state(dev_priv);
16226 }
16227
16228 void intel_display_resume(struct drm_device *dev)
16229 {
16230         struct drm_i915_private *dev_priv = to_i915(dev);
16231         struct drm_atomic_state *state = dev_priv->modeset_restore_state;
16232         struct drm_modeset_acquire_ctx ctx;
16233         int ret;
16234
16235         dev_priv->modeset_restore_state = NULL;
16236         if (state)
16237                 state->acquire_ctx = &ctx;
16238
16239         /*
16240          * This is a cludge because with real atomic modeset mode_config.mutex
16241          * won't be taken. Unfortunately some probed state like
16242          * audio_codec_enable is still protected by mode_config.mutex, so lock
16243          * it here for now.
16244          */
16245         mutex_lock(&dev->mode_config.mutex);
16246         drm_modeset_acquire_init(&ctx, 0);
16247
16248         while (1) {
16249                 ret = drm_modeset_lock_all_ctx(dev, &ctx);
16250                 if (ret != -EDEADLK)
16251                         break;
16252
16253                 drm_modeset_backoff(&ctx);
16254         }
16255
16256         if (!ret)
16257                 ret = __intel_display_resume(dev, state);
16258
16259         drm_modeset_drop_locks(&ctx);
16260         drm_modeset_acquire_fini(&ctx);
16261         mutex_unlock(&dev->mode_config.mutex);
16262
16263         if (ret) {
16264                 DRM_ERROR("Restoring old state failed with %i\n", ret);
16265                 drm_atomic_state_free(state);
16266         }
16267 }
16268
16269 void intel_modeset_gem_init(struct drm_device *dev)
16270 {
16271         struct drm_i915_private *dev_priv = to_i915(dev);
16272         struct drm_crtc *c;
16273         struct drm_i915_gem_object *obj;
16274         int ret;
16275
16276         intel_init_gt_powersave(dev_priv);
16277
16278         intel_modeset_init_hw(dev);
16279
16280         intel_setup_overlay(dev_priv);
16281
16282         /*
16283          * Make sure any fbs we allocated at startup are properly
16284          * pinned & fenced.  When we do the allocation it's too early
16285          * for this.
16286          */
16287         for_each_crtc(dev, c) {
16288                 obj = intel_fb_obj(c->primary->fb);
16289                 if (obj == NULL)
16290                         continue;
16291
16292                 mutex_lock(&dev->struct_mutex);
16293                 ret = intel_pin_and_fence_fb_obj(c->primary->fb,
16294                                                  c->primary->state->rotation);
16295                 mutex_unlock(&dev->struct_mutex);
16296                 if (ret) {
16297                         DRM_ERROR("failed to pin boot fb on pipe %d\n",
16298                                   to_intel_crtc(c)->pipe);
16299                         drm_framebuffer_unreference(c->primary->fb);
16300                         c->primary->fb = NULL;
16301                         c->primary->crtc = c->primary->state->crtc = NULL;
16302                         update_state_fb(c->primary);
16303                         c->state->plane_mask &= ~(1 << drm_plane_index(c->primary));
16304                 }
16305         }
16306 }
16307
16308 int intel_connector_register(struct drm_connector *connector)
16309 {
16310         struct intel_connector *intel_connector = to_intel_connector(connector);
16311         int ret;
16312
16313         ret = intel_backlight_device_register(intel_connector);
16314         if (ret)
16315                 goto err;
16316
16317         return 0;
16318
16319 err:
16320         return ret;
16321 }
16322
16323 void intel_connector_unregister(struct drm_connector *connector)
16324 {
16325         struct intel_connector *intel_connector = to_intel_connector(connector);
16326
16327         intel_backlight_device_unregister(intel_connector);
16328         intel_panel_destroy_backlight(connector);
16329 }
16330
16331 void intel_modeset_cleanup(struct drm_device *dev)
16332 {
16333         struct drm_i915_private *dev_priv = to_i915(dev);
16334
16335         intel_disable_gt_powersave(dev_priv);
16336
16337         /*
16338          * Interrupts and polling as the first thing to avoid creating havoc.
16339          * Too much stuff here (turning of connectors, ...) would
16340          * experience fancy races otherwise.
16341          */
16342         intel_irq_uninstall(dev_priv);
16343
16344         /*
16345          * Due to the hpd irq storm handling the hotplug work can re-arm the
16346          * poll handlers. Hence disable polling after hpd handling is shut down.
16347          */
16348         drm_kms_helper_poll_fini(dev);
16349
16350         intel_unregister_dsm_handler();
16351
16352         intel_fbc_global_disable(dev_priv);
16353
16354         /* flush any delayed tasks or pending work */
16355         flush_scheduled_work();
16356
16357         drm_mode_config_cleanup(dev);
16358
16359         intel_cleanup_overlay(dev_priv);
16360
16361         intel_cleanup_gt_powersave(dev_priv);
16362
16363         intel_teardown_gmbus(dev);
16364 }
16365
16366 void intel_connector_attach_encoder(struct intel_connector *connector,
16367                                     struct intel_encoder *encoder)
16368 {
16369         connector->encoder = encoder;
16370         drm_mode_connector_attach_encoder(&connector->base,
16371                                           &encoder->base);
16372 }
16373
16374 /*
16375  * set vga decode state - true == enable VGA decode
16376  */
16377 int intel_modeset_vga_set_state(struct drm_device *dev, bool state)
16378 {
16379         struct drm_i915_private *dev_priv = to_i915(dev);
16380         unsigned reg = INTEL_INFO(dev)->gen >= 6 ? SNB_GMCH_CTRL : INTEL_GMCH_CTRL;
16381         u16 gmch_ctrl;
16382
16383         if (pci_read_config_word(dev_priv->bridge_dev, reg, &gmch_ctrl)) {
16384                 DRM_ERROR("failed to read control word\n");
16385                 return -EIO;
16386         }
16387
16388         if (!!(gmch_ctrl & INTEL_GMCH_VGA_DISABLE) == !state)
16389                 return 0;
16390
16391         if (state)
16392                 gmch_ctrl &= ~INTEL_GMCH_VGA_DISABLE;
16393         else
16394                 gmch_ctrl |= INTEL_GMCH_VGA_DISABLE;
16395
16396         if (pci_write_config_word(dev_priv->bridge_dev, reg, gmch_ctrl)) {
16397                 DRM_ERROR("failed to write control word\n");
16398                 return -EIO;
16399         }
16400
16401         return 0;
16402 }
16403
16404 struct intel_display_error_state {
16405
16406         u32 power_well_driver;
16407
16408         int num_transcoders;
16409
16410         struct intel_cursor_error_state {
16411                 u32 control;
16412                 u32 position;
16413                 u32 base;
16414                 u32 size;
16415         } cursor[I915_MAX_PIPES];
16416
16417         struct intel_pipe_error_state {
16418                 bool power_domain_on;
16419                 u32 source;
16420                 u32 stat;
16421         } pipe[I915_MAX_PIPES];
16422
16423         struct intel_plane_error_state {
16424                 u32 control;
16425                 u32 stride;
16426                 u32 size;
16427                 u32 pos;
16428                 u32 addr;
16429                 u32 surface;
16430                 u32 tile_offset;
16431         } plane[I915_MAX_PIPES];
16432
16433         struct intel_transcoder_error_state {
16434                 bool power_domain_on;
16435                 enum transcoder cpu_transcoder;
16436
16437                 u32 conf;
16438
16439                 u32 htotal;
16440                 u32 hblank;
16441                 u32 hsync;
16442                 u32 vtotal;
16443                 u32 vblank;
16444                 u32 vsync;
16445         } transcoder[4];
16446 };
16447
16448 struct intel_display_error_state *
16449 intel_display_capture_error_state(struct drm_i915_private *dev_priv)
16450 {
16451         struct intel_display_error_state *error;
16452         int transcoders[] = {
16453                 TRANSCODER_A,
16454                 TRANSCODER_B,
16455                 TRANSCODER_C,
16456                 TRANSCODER_EDP,
16457         };
16458         int i;
16459
16460         if (INTEL_INFO(dev_priv)->num_pipes == 0)
16461                 return NULL;
16462
16463         error = kzalloc(sizeof(*error), GFP_ATOMIC);
16464         if (error == NULL)
16465                 return NULL;
16466
16467         if (IS_HASWELL(dev_priv) || IS_BROADWELL(dev_priv))
16468                 error->power_well_driver = I915_READ(HSW_PWR_WELL_DRIVER);
16469
16470         for_each_pipe(dev_priv, i) {
16471                 error->pipe[i].power_domain_on =
16472                         __intel_display_power_is_enabled(dev_priv,
16473                                                          POWER_DOMAIN_PIPE(i));
16474                 if (!error->pipe[i].power_domain_on)
16475                         continue;
16476
16477                 error->cursor[i].control = I915_READ(CURCNTR(i));
16478                 error->cursor[i].position = I915_READ(CURPOS(i));
16479                 error->cursor[i].base = I915_READ(CURBASE(i));
16480
16481                 error->plane[i].control = I915_READ(DSPCNTR(i));
16482                 error->plane[i].stride = I915_READ(DSPSTRIDE(i));
16483                 if (INTEL_GEN(dev_priv) <= 3) {
16484                         error->plane[i].size = I915_READ(DSPSIZE(i));
16485                         error->plane[i].pos = I915_READ(DSPPOS(i));
16486                 }
16487                 if (INTEL_GEN(dev_priv) <= 7 && !IS_HASWELL(dev_priv))
16488                         error->plane[i].addr = I915_READ(DSPADDR(i));
16489                 if (INTEL_GEN(dev_priv) >= 4) {
16490                         error->plane[i].surface = I915_READ(DSPSURF(i));
16491                         error->plane[i].tile_offset = I915_READ(DSPTILEOFF(i));
16492                 }
16493
16494                 error->pipe[i].source = I915_READ(PIPESRC(i));
16495
16496                 if (HAS_GMCH_DISPLAY(dev_priv))
16497                         error->pipe[i].stat = I915_READ(PIPESTAT(i));
16498         }
16499
16500         /* Note: this does not include DSI transcoders. */
16501         error->num_transcoders = INTEL_INFO(dev_priv)->num_pipes;
16502         if (HAS_DDI(dev_priv))
16503                 error->num_transcoders++; /* Account for eDP. */
16504
16505         for (i = 0; i < error->num_transcoders; i++) {
16506                 enum transcoder cpu_transcoder = transcoders[i];
16507
16508                 error->transcoder[i].power_domain_on =
16509                         __intel_display_power_is_enabled(dev_priv,
16510                                 POWER_DOMAIN_TRANSCODER(cpu_transcoder));
16511                 if (!error->transcoder[i].power_domain_on)
16512                         continue;
16513
16514                 error->transcoder[i].cpu_transcoder = cpu_transcoder;
16515
16516                 error->transcoder[i].conf = I915_READ(PIPECONF(cpu_transcoder));
16517                 error->transcoder[i].htotal = I915_READ(HTOTAL(cpu_transcoder));
16518                 error->transcoder[i].hblank = I915_READ(HBLANK(cpu_transcoder));
16519                 error->transcoder[i].hsync = I915_READ(HSYNC(cpu_transcoder));
16520                 error->transcoder[i].vtotal = I915_READ(VTOTAL(cpu_transcoder));
16521                 error->transcoder[i].vblank = I915_READ(VBLANK(cpu_transcoder));
16522                 error->transcoder[i].vsync = I915_READ(VSYNC(cpu_transcoder));
16523         }
16524
16525         return error;
16526 }
16527
16528 #define err_printf(e, ...) i915_error_printf(e, __VA_ARGS__)
16529
16530 void
16531 intel_display_print_error_state(struct drm_i915_error_state_buf *m,
16532                                 struct drm_device *dev,
16533                                 struct intel_display_error_state *error)
16534 {
16535         struct drm_i915_private *dev_priv = to_i915(dev);
16536         int i;
16537
16538         if (!error)
16539                 return;
16540
16541         err_printf(m, "Num Pipes: %d\n", INTEL_INFO(dev)->num_pipes);
16542         if (IS_HASWELL(dev) || IS_BROADWELL(dev))
16543                 err_printf(m, "PWR_WELL_CTL2: %08x\n",
16544                            error->power_well_driver);
16545         for_each_pipe(dev_priv, i) {
16546                 err_printf(m, "Pipe [%d]:\n", i);
16547                 err_printf(m, "  Power: %s\n",
16548                            onoff(error->pipe[i].power_domain_on));
16549                 err_printf(m, "  SRC: %08x\n", error->pipe[i].source);
16550                 err_printf(m, "  STAT: %08x\n", error->pipe[i].stat);
16551
16552                 err_printf(m, "Plane [%d]:\n", i);
16553                 err_printf(m, "  CNTR: %08x\n", error->plane[i].control);
16554                 err_printf(m, "  STRIDE: %08x\n", error->plane[i].stride);
16555                 if (INTEL_INFO(dev)->gen <= 3) {
16556                         err_printf(m, "  SIZE: %08x\n", error->plane[i].size);
16557                         err_printf(m, "  POS: %08x\n", error->plane[i].pos);
16558                 }
16559                 if (INTEL_INFO(dev)->gen <= 7 && !IS_HASWELL(dev))
16560                         err_printf(m, "  ADDR: %08x\n", error->plane[i].addr);
16561                 if (INTEL_INFO(dev)->gen >= 4) {
16562                         err_printf(m, "  SURF: %08x\n", error->plane[i].surface);
16563                         err_printf(m, "  TILEOFF: %08x\n", error->plane[i].tile_offset);
16564                 }
16565
16566                 err_printf(m, "Cursor [%d]:\n", i);
16567                 err_printf(m, "  CNTR: %08x\n", error->cursor[i].control);
16568                 err_printf(m, "  POS: %08x\n", error->cursor[i].position);
16569                 err_printf(m, "  BASE: %08x\n", error->cursor[i].base);
16570         }
16571
16572         for (i = 0; i < error->num_transcoders; i++) {
16573                 err_printf(m, "CPU transcoder: %s\n",
16574                            transcoder_name(error->transcoder[i].cpu_transcoder));
16575                 err_printf(m, "  Power: %s\n",
16576                            onoff(error->transcoder[i].power_domain_on));
16577                 err_printf(m, "  CONF: %08x\n", error->transcoder[i].conf);
16578                 err_printf(m, "  HTOTAL: %08x\n", error->transcoder[i].htotal);
16579                 err_printf(m, "  HBLANK: %08x\n", error->transcoder[i].hblank);
16580                 err_printf(m, "  HSYNC: %08x\n", error->transcoder[i].hsync);
16581                 err_printf(m, "  VTOTAL: %08x\n", error->transcoder[i].vtotal);
16582                 err_printf(m, "  VBLANK: %08x\n", error->transcoder[i].vblank);
16583                 err_printf(m, "  VSYNC: %08x\n", error->transcoder[i].vsync);
16584         }
16585 }