drm/i915: Introduce gpu_reset_clobbers_display()
[linux-2.6-microblaze.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 "intel_frontbuffer.h"
38 #include <drm/i915_drm.h>
39 #include "i915_drv.h"
40 #include "i915_gem_dmabuf.h"
41 #include "intel_dsi.h"
42 #include "i915_trace.h"
43 #include <drm/drm_atomic.h>
44 #include <drm/drm_atomic_helper.h>
45 #include <drm/drm_dp_helper.h>
46 #include <drm/drm_crtc_helper.h>
47 #include <drm/drm_plane_helper.h>
48 #include <drm/drm_rect.h>
49 #include <linux/dma_remapping.h>
50 #include <linux/reservation.h>
51
52 static bool is_mmio_work(struct intel_flip_work *work)
53 {
54         return work->mmio_work.func;
55 }
56
57 /* Primary plane formats for gen <= 3 */
58 static const uint32_t i8xx_primary_formats[] = {
59         DRM_FORMAT_C8,
60         DRM_FORMAT_RGB565,
61         DRM_FORMAT_XRGB1555,
62         DRM_FORMAT_XRGB8888,
63 };
64
65 /* Primary plane formats for gen >= 4 */
66 static const uint32_t i965_primary_formats[] = {
67         DRM_FORMAT_C8,
68         DRM_FORMAT_RGB565,
69         DRM_FORMAT_XRGB8888,
70         DRM_FORMAT_XBGR8888,
71         DRM_FORMAT_XRGB2101010,
72         DRM_FORMAT_XBGR2101010,
73 };
74
75 static const uint32_t skl_primary_formats[] = {
76         DRM_FORMAT_C8,
77         DRM_FORMAT_RGB565,
78         DRM_FORMAT_XRGB8888,
79         DRM_FORMAT_XBGR8888,
80         DRM_FORMAT_ARGB8888,
81         DRM_FORMAT_ABGR8888,
82         DRM_FORMAT_XRGB2101010,
83         DRM_FORMAT_XBGR2101010,
84         DRM_FORMAT_YUYV,
85         DRM_FORMAT_YVYU,
86         DRM_FORMAT_UYVY,
87         DRM_FORMAT_VYUY,
88 };
89
90 /* Cursor formats */
91 static const uint32_t intel_cursor_formats[] = {
92         DRM_FORMAT_ARGB8888,
93 };
94
95 static void i9xx_crtc_clock_get(struct intel_crtc *crtc,
96                                 struct intel_crtc_state *pipe_config);
97 static void ironlake_pch_clock_get(struct intel_crtc *crtc,
98                                    struct intel_crtc_state *pipe_config);
99
100 static int intel_framebuffer_init(struct drm_device *dev,
101                                   struct intel_framebuffer *ifb,
102                                   struct drm_mode_fb_cmd2 *mode_cmd,
103                                   struct drm_i915_gem_object *obj);
104 static void i9xx_set_pipeconf(struct intel_crtc *intel_crtc);
105 static void intel_set_pipe_timings(struct intel_crtc *intel_crtc);
106 static void intel_set_pipe_src_size(struct intel_crtc *intel_crtc);
107 static void intel_cpu_transcoder_set_m_n(struct intel_crtc *crtc,
108                                          struct intel_link_m_n *m_n,
109                                          struct intel_link_m_n *m2_n2);
110 static void ironlake_set_pipeconf(struct drm_crtc *crtc);
111 static void haswell_set_pipeconf(struct drm_crtc *crtc);
112 static void haswell_set_pipemisc(struct drm_crtc *crtc);
113 static void vlv_prepare_pll(struct intel_crtc *crtc,
114                             const struct intel_crtc_state *pipe_config);
115 static void chv_prepare_pll(struct intel_crtc *crtc,
116                             const struct intel_crtc_state *pipe_config);
117 static void intel_begin_crtc_commit(struct drm_crtc *, struct drm_crtc_state *);
118 static void intel_finish_crtc_commit(struct drm_crtc *, struct drm_crtc_state *);
119 static void skl_init_scalers(struct drm_device *dev, struct intel_crtc *intel_crtc,
120         struct intel_crtc_state *crtc_state);
121 static void skylake_pfit_enable(struct intel_crtc *crtc);
122 static void ironlake_pfit_disable(struct intel_crtc *crtc, bool force);
123 static void ironlake_pfit_enable(struct intel_crtc *crtc);
124 static void intel_modeset_setup_hw_state(struct drm_device *dev);
125 static void intel_pre_disable_primary_noatomic(struct drm_crtc *crtc);
126 static int ilk_max_pixel_rate(struct drm_atomic_state *state);
127 static int bxt_calc_cdclk(int max_pixclk);
128
129 struct intel_limit {
130         struct {
131                 int min, max;
132         } dot, vco, n, m, m1, m2, p, p1;
133
134         struct {
135                 int dot_limit;
136                 int p2_slow, p2_fast;
137         } p2;
138 };
139
140 /* returns HPLL frequency in kHz */
141 static int valleyview_get_vco(struct drm_i915_private *dev_priv)
142 {
143         int hpll_freq, vco_freq[] = { 800, 1600, 2000, 2400 };
144
145         /* Obtain SKU information */
146         mutex_lock(&dev_priv->sb_lock);
147         hpll_freq = vlv_cck_read(dev_priv, CCK_FUSE_REG) &
148                 CCK_FUSE_HPLL_FREQ_MASK;
149         mutex_unlock(&dev_priv->sb_lock);
150
151         return vco_freq[hpll_freq] * 1000;
152 }
153
154 int vlv_get_cck_clock(struct drm_i915_private *dev_priv,
155                       const char *name, u32 reg, int ref_freq)
156 {
157         u32 val;
158         int divider;
159
160         mutex_lock(&dev_priv->sb_lock);
161         val = vlv_cck_read(dev_priv, reg);
162         mutex_unlock(&dev_priv->sb_lock);
163
164         divider = val & CCK_FREQUENCY_VALUES;
165
166         WARN((val & CCK_FREQUENCY_STATUS) !=
167              (divider << CCK_FREQUENCY_STATUS_SHIFT),
168              "%s change in progress\n", name);
169
170         return DIV_ROUND_CLOSEST(ref_freq << 1, divider + 1);
171 }
172
173 static int vlv_get_cck_clock_hpll(struct drm_i915_private *dev_priv,
174                                   const char *name, u32 reg)
175 {
176         if (dev_priv->hpll_freq == 0)
177                 dev_priv->hpll_freq = valleyview_get_vco(dev_priv);
178
179         return vlv_get_cck_clock(dev_priv, name, reg,
180                                  dev_priv->hpll_freq);
181 }
182
183 static int
184 intel_pch_rawclk(struct drm_i915_private *dev_priv)
185 {
186         return (I915_READ(PCH_RAWCLK_FREQ) & RAWCLK_FREQ_MASK) * 1000;
187 }
188
189 static int
190 intel_vlv_hrawclk(struct drm_i915_private *dev_priv)
191 {
192         /* RAWCLK_FREQ_VLV register updated from power well code */
193         return vlv_get_cck_clock_hpll(dev_priv, "hrawclk",
194                                       CCK_DISPLAY_REF_CLOCK_CONTROL);
195 }
196
197 static int
198 intel_g4x_hrawclk(struct drm_i915_private *dev_priv)
199 {
200         uint32_t clkcfg;
201
202         /* hrawclock is 1/4 the FSB frequency */
203         clkcfg = I915_READ(CLKCFG);
204         switch (clkcfg & CLKCFG_FSB_MASK) {
205         case CLKCFG_FSB_400:
206                 return 100000;
207         case CLKCFG_FSB_533:
208                 return 133333;
209         case CLKCFG_FSB_667:
210                 return 166667;
211         case CLKCFG_FSB_800:
212                 return 200000;
213         case CLKCFG_FSB_1067:
214                 return 266667;
215         case CLKCFG_FSB_1333:
216                 return 333333;
217         /* these two are just a guess; one of them might be right */
218         case CLKCFG_FSB_1600:
219         case CLKCFG_FSB_1600_ALT:
220                 return 400000;
221         default:
222                 return 133333;
223         }
224 }
225
226 void intel_update_rawclk(struct drm_i915_private *dev_priv)
227 {
228         if (HAS_PCH_SPLIT(dev_priv))
229                 dev_priv->rawclk_freq = intel_pch_rawclk(dev_priv);
230         else if (IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv))
231                 dev_priv->rawclk_freq = intel_vlv_hrawclk(dev_priv);
232         else if (IS_G4X(dev_priv) || IS_PINEVIEW(dev_priv))
233                 dev_priv->rawclk_freq = intel_g4x_hrawclk(dev_priv);
234         else
235                 return; /* no rawclk on other platforms, or no need to know it */
236
237         DRM_DEBUG_DRIVER("rawclk rate: %d kHz\n", dev_priv->rawclk_freq);
238 }
239
240 static void intel_update_czclk(struct drm_i915_private *dev_priv)
241 {
242         if (!(IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv)))
243                 return;
244
245         dev_priv->czclk_freq = vlv_get_cck_clock_hpll(dev_priv, "czclk",
246                                                       CCK_CZ_CLOCK_CONTROL);
247
248         DRM_DEBUG_DRIVER("CZ clock rate: %d kHz\n", dev_priv->czclk_freq);
249 }
250
251 static inline u32 /* units of 100MHz */
252 intel_fdi_link_freq(struct drm_i915_private *dev_priv,
253                     const struct intel_crtc_state *pipe_config)
254 {
255         if (HAS_DDI(dev_priv))
256                 return pipe_config->port_clock; /* SPLL */
257         else if (IS_GEN5(dev_priv))
258                 return ((I915_READ(FDI_PLL_BIOS_0) & FDI_PLL_FB_CLOCK_MASK) + 2) * 10000;
259         else
260                 return 270000;
261 }
262
263 static const struct intel_limit intel_limits_i8xx_dac = {
264         .dot = { .min = 25000, .max = 350000 },
265         .vco = { .min = 908000, .max = 1512000 },
266         .n = { .min = 2, .max = 16 },
267         .m = { .min = 96, .max = 140 },
268         .m1 = { .min = 18, .max = 26 },
269         .m2 = { .min = 6, .max = 16 },
270         .p = { .min = 4, .max = 128 },
271         .p1 = { .min = 2, .max = 33 },
272         .p2 = { .dot_limit = 165000,
273                 .p2_slow = 4, .p2_fast = 2 },
274 };
275
276 static const struct intel_limit intel_limits_i8xx_dvo = {
277         .dot = { .min = 25000, .max = 350000 },
278         .vco = { .min = 908000, .max = 1512000 },
279         .n = { .min = 2, .max = 16 },
280         .m = { .min = 96, .max = 140 },
281         .m1 = { .min = 18, .max = 26 },
282         .m2 = { .min = 6, .max = 16 },
283         .p = { .min = 4, .max = 128 },
284         .p1 = { .min = 2, .max = 33 },
285         .p2 = { .dot_limit = 165000,
286                 .p2_slow = 4, .p2_fast = 4 },
287 };
288
289 static const struct intel_limit intel_limits_i8xx_lvds = {
290         .dot = { .min = 25000, .max = 350000 },
291         .vco = { .min = 908000, .max = 1512000 },
292         .n = { .min = 2, .max = 16 },
293         .m = { .min = 96, .max = 140 },
294         .m1 = { .min = 18, .max = 26 },
295         .m2 = { .min = 6, .max = 16 },
296         .p = { .min = 4, .max = 128 },
297         .p1 = { .min = 1, .max = 6 },
298         .p2 = { .dot_limit = 165000,
299                 .p2_slow = 14, .p2_fast = 7 },
300 };
301
302 static const struct intel_limit intel_limits_i9xx_sdvo = {
303         .dot = { .min = 20000, .max = 400000 },
304         .vco = { .min = 1400000, .max = 2800000 },
305         .n = { .min = 1, .max = 6 },
306         .m = { .min = 70, .max = 120 },
307         .m1 = { .min = 8, .max = 18 },
308         .m2 = { .min = 3, .max = 7 },
309         .p = { .min = 5, .max = 80 },
310         .p1 = { .min = 1, .max = 8 },
311         .p2 = { .dot_limit = 200000,
312                 .p2_slow = 10, .p2_fast = 5 },
313 };
314
315 static const struct intel_limit intel_limits_i9xx_lvds = {
316         .dot = { .min = 20000, .max = 400000 },
317         .vco = { .min = 1400000, .max = 2800000 },
318         .n = { .min = 1, .max = 6 },
319         .m = { .min = 70, .max = 120 },
320         .m1 = { .min = 8, .max = 18 },
321         .m2 = { .min = 3, .max = 7 },
322         .p = { .min = 7, .max = 98 },
323         .p1 = { .min = 1, .max = 8 },
324         .p2 = { .dot_limit = 112000,
325                 .p2_slow = 14, .p2_fast = 7 },
326 };
327
328
329 static const struct intel_limit intel_limits_g4x_sdvo = {
330         .dot = { .min = 25000, .max = 270000 },
331         .vco = { .min = 1750000, .max = 3500000},
332         .n = { .min = 1, .max = 4 },
333         .m = { .min = 104, .max = 138 },
334         .m1 = { .min = 17, .max = 23 },
335         .m2 = { .min = 5, .max = 11 },
336         .p = { .min = 10, .max = 30 },
337         .p1 = { .min = 1, .max = 3},
338         .p2 = { .dot_limit = 270000,
339                 .p2_slow = 10,
340                 .p2_fast = 10
341         },
342 };
343
344 static const struct intel_limit intel_limits_g4x_hdmi = {
345         .dot = { .min = 22000, .max = 400000 },
346         .vco = { .min = 1750000, .max = 3500000},
347         .n = { .min = 1, .max = 4 },
348         .m = { .min = 104, .max = 138 },
349         .m1 = { .min = 16, .max = 23 },
350         .m2 = { .min = 5, .max = 11 },
351         .p = { .min = 5, .max = 80 },
352         .p1 = { .min = 1, .max = 8},
353         .p2 = { .dot_limit = 165000,
354                 .p2_slow = 10, .p2_fast = 5 },
355 };
356
357 static const struct intel_limit intel_limits_g4x_single_channel_lvds = {
358         .dot = { .min = 20000, .max = 115000 },
359         .vco = { .min = 1750000, .max = 3500000 },
360         .n = { .min = 1, .max = 3 },
361         .m = { .min = 104, .max = 138 },
362         .m1 = { .min = 17, .max = 23 },
363         .m2 = { .min = 5, .max = 11 },
364         .p = { .min = 28, .max = 112 },
365         .p1 = { .min = 2, .max = 8 },
366         .p2 = { .dot_limit = 0,
367                 .p2_slow = 14, .p2_fast = 14
368         },
369 };
370
371 static const struct intel_limit intel_limits_g4x_dual_channel_lvds = {
372         .dot = { .min = 80000, .max = 224000 },
373         .vco = { .min = 1750000, .max = 3500000 },
374         .n = { .min = 1, .max = 3 },
375         .m = { .min = 104, .max = 138 },
376         .m1 = { .min = 17, .max = 23 },
377         .m2 = { .min = 5, .max = 11 },
378         .p = { .min = 14, .max = 42 },
379         .p1 = { .min = 2, .max = 6 },
380         .p2 = { .dot_limit = 0,
381                 .p2_slow = 7, .p2_fast = 7
382         },
383 };
384
385 static const struct intel_limit intel_limits_pineview_sdvo = {
386         .dot = { .min = 20000, .max = 400000},
387         .vco = { .min = 1700000, .max = 3500000 },
388         /* Pineview's Ncounter is a ring counter */
389         .n = { .min = 3, .max = 6 },
390         .m = { .min = 2, .max = 256 },
391         /* Pineview only has one combined m divider, which we treat as m2. */
392         .m1 = { .min = 0, .max = 0 },
393         .m2 = { .min = 0, .max = 254 },
394         .p = { .min = 5, .max = 80 },
395         .p1 = { .min = 1, .max = 8 },
396         .p2 = { .dot_limit = 200000,
397                 .p2_slow = 10, .p2_fast = 5 },
398 };
399
400 static const struct intel_limit intel_limits_pineview_lvds = {
401         .dot = { .min = 20000, .max = 400000 },
402         .vco = { .min = 1700000, .max = 3500000 },
403         .n = { .min = 3, .max = 6 },
404         .m = { .min = 2, .max = 256 },
405         .m1 = { .min = 0, .max = 0 },
406         .m2 = { .min = 0, .max = 254 },
407         .p = { .min = 7, .max = 112 },
408         .p1 = { .min = 1, .max = 8 },
409         .p2 = { .dot_limit = 112000,
410                 .p2_slow = 14, .p2_fast = 14 },
411 };
412
413 /* Ironlake / Sandybridge
414  *
415  * We calculate clock using (register_value + 2) for N/M1/M2, so here
416  * the range value for them is (actual_value - 2).
417  */
418 static const struct intel_limit intel_limits_ironlake_dac = {
419         .dot = { .min = 25000, .max = 350000 },
420         .vco = { .min = 1760000, .max = 3510000 },
421         .n = { .min = 1, .max = 5 },
422         .m = { .min = 79, .max = 127 },
423         .m1 = { .min = 12, .max = 22 },
424         .m2 = { .min = 5, .max = 9 },
425         .p = { .min = 5, .max = 80 },
426         .p1 = { .min = 1, .max = 8 },
427         .p2 = { .dot_limit = 225000,
428                 .p2_slow = 10, .p2_fast = 5 },
429 };
430
431 static const struct intel_limit intel_limits_ironlake_single_lvds = {
432         .dot = { .min = 25000, .max = 350000 },
433         .vco = { .min = 1760000, .max = 3510000 },
434         .n = { .min = 1, .max = 3 },
435         .m = { .min = 79, .max = 118 },
436         .m1 = { .min = 12, .max = 22 },
437         .m2 = { .min = 5, .max = 9 },
438         .p = { .min = 28, .max = 112 },
439         .p1 = { .min = 2, .max = 8 },
440         .p2 = { .dot_limit = 225000,
441                 .p2_slow = 14, .p2_fast = 14 },
442 };
443
444 static const struct intel_limit intel_limits_ironlake_dual_lvds = {
445         .dot = { .min = 25000, .max = 350000 },
446         .vco = { .min = 1760000, .max = 3510000 },
447         .n = { .min = 1, .max = 3 },
448         .m = { .min = 79, .max = 127 },
449         .m1 = { .min = 12, .max = 22 },
450         .m2 = { .min = 5, .max = 9 },
451         .p = { .min = 14, .max = 56 },
452         .p1 = { .min = 2, .max = 8 },
453         .p2 = { .dot_limit = 225000,
454                 .p2_slow = 7, .p2_fast = 7 },
455 };
456
457 /* LVDS 100mhz refclk limits. */
458 static const struct intel_limit intel_limits_ironlake_single_lvds_100m = {
459         .dot = { .min = 25000, .max = 350000 },
460         .vco = { .min = 1760000, .max = 3510000 },
461         .n = { .min = 1, .max = 2 },
462         .m = { .min = 79, .max = 126 },
463         .m1 = { .min = 12, .max = 22 },
464         .m2 = { .min = 5, .max = 9 },
465         .p = { .min = 28, .max = 112 },
466         .p1 = { .min = 2, .max = 8 },
467         .p2 = { .dot_limit = 225000,
468                 .p2_slow = 14, .p2_fast = 14 },
469 };
470
471 static const struct intel_limit intel_limits_ironlake_dual_lvds_100m = {
472         .dot = { .min = 25000, .max = 350000 },
473         .vco = { .min = 1760000, .max = 3510000 },
474         .n = { .min = 1, .max = 3 },
475         .m = { .min = 79, .max = 126 },
476         .m1 = { .min = 12, .max = 22 },
477         .m2 = { .min = 5, .max = 9 },
478         .p = { .min = 14, .max = 42 },
479         .p1 = { .min = 2, .max = 6 },
480         .p2 = { .dot_limit = 225000,
481                 .p2_slow = 7, .p2_fast = 7 },
482 };
483
484 static const struct intel_limit intel_limits_vlv = {
485          /*
486           * These are the data rate limits (measured in fast clocks)
487           * since those are the strictest limits we have. The fast
488           * clock and actual rate limits are more relaxed, so checking
489           * them would make no difference.
490           */
491         .dot = { .min = 25000 * 5, .max = 270000 * 5 },
492         .vco = { .min = 4000000, .max = 6000000 },
493         .n = { .min = 1, .max = 7 },
494         .m1 = { .min = 2, .max = 3 },
495         .m2 = { .min = 11, .max = 156 },
496         .p1 = { .min = 2, .max = 3 },
497         .p2 = { .p2_slow = 2, .p2_fast = 20 }, /* slow=min, fast=max */
498 };
499
500 static const struct intel_limit intel_limits_chv = {
501         /*
502          * These are the data rate limits (measured in fast clocks)
503          * since those are the strictest limits we have.  The fast
504          * clock and actual rate limits are more relaxed, so checking
505          * them would make no difference.
506          */
507         .dot = { .min = 25000 * 5, .max = 540000 * 5},
508         .vco = { .min = 4800000, .max = 6480000 },
509         .n = { .min = 1, .max = 1 },
510         .m1 = { .min = 2, .max = 2 },
511         .m2 = { .min = 24 << 22, .max = 175 << 22 },
512         .p1 = { .min = 2, .max = 4 },
513         .p2 = { .p2_slow = 1, .p2_fast = 14 },
514 };
515
516 static const struct intel_limit intel_limits_bxt = {
517         /* FIXME: find real dot limits */
518         .dot = { .min = 0, .max = INT_MAX },
519         .vco = { .min = 4800000, .max = 6700000 },
520         .n = { .min = 1, .max = 1 },
521         .m1 = { .min = 2, .max = 2 },
522         /* FIXME: find real m2 limits */
523         .m2 = { .min = 2 << 22, .max = 255 << 22 },
524         .p1 = { .min = 2, .max = 4 },
525         .p2 = { .p2_slow = 1, .p2_fast = 20 },
526 };
527
528 static bool
529 needs_modeset(struct drm_crtc_state *state)
530 {
531         return drm_atomic_crtc_needs_modeset(state);
532 }
533
534 /*
535  * Platform specific helpers to calculate the port PLL loopback- (clock.m),
536  * and post-divider (clock.p) values, pre- (clock.vco) and post-divided fast
537  * (clock.dot) clock rates. This fast dot clock is fed to the port's IO logic.
538  * The helpers' return value is the rate of the clock that is fed to the
539  * display engine's pipe which can be the above fast dot clock rate or a
540  * divided-down version of it.
541  */
542 /* m1 is reserved as 0 in Pineview, n is a ring counter */
543 static int pnv_calc_dpll_params(int refclk, struct dpll *clock)
544 {
545         clock->m = clock->m2 + 2;
546         clock->p = clock->p1 * clock->p2;
547         if (WARN_ON(clock->n == 0 || clock->p == 0))
548                 return 0;
549         clock->vco = DIV_ROUND_CLOSEST(refclk * clock->m, clock->n);
550         clock->dot = DIV_ROUND_CLOSEST(clock->vco, clock->p);
551
552         return clock->dot;
553 }
554
555 static uint32_t i9xx_dpll_compute_m(struct dpll *dpll)
556 {
557         return 5 * (dpll->m1 + 2) + (dpll->m2 + 2);
558 }
559
560 static int i9xx_calc_dpll_params(int refclk, struct dpll *clock)
561 {
562         clock->m = i9xx_dpll_compute_m(clock);
563         clock->p = clock->p1 * clock->p2;
564         if (WARN_ON(clock->n + 2 == 0 || clock->p == 0))
565                 return 0;
566         clock->vco = DIV_ROUND_CLOSEST(refclk * clock->m, clock->n + 2);
567         clock->dot = DIV_ROUND_CLOSEST(clock->vco, clock->p);
568
569         return clock->dot;
570 }
571
572 static int vlv_calc_dpll_params(int refclk, struct dpll *clock)
573 {
574         clock->m = clock->m1 * clock->m2;
575         clock->p = clock->p1 * clock->p2;
576         if (WARN_ON(clock->n == 0 || clock->p == 0))
577                 return 0;
578         clock->vco = DIV_ROUND_CLOSEST(refclk * clock->m, clock->n);
579         clock->dot = DIV_ROUND_CLOSEST(clock->vco, clock->p);
580
581         return clock->dot / 5;
582 }
583
584 int chv_calc_dpll_params(int refclk, struct dpll *clock)
585 {
586         clock->m = clock->m1 * clock->m2;
587         clock->p = clock->p1 * clock->p2;
588         if (WARN_ON(clock->n == 0 || clock->p == 0))
589                 return 0;
590         clock->vco = DIV_ROUND_CLOSEST_ULL((uint64_t)refclk * clock->m,
591                         clock->n << 22);
592         clock->dot = DIV_ROUND_CLOSEST(clock->vco, clock->p);
593
594         return clock->dot / 5;
595 }
596
597 #define INTELPllInvalid(s)   do { /* DRM_DEBUG(s); */ return false; } while (0)
598 /**
599  * Returns whether the given set of divisors are valid for a given refclk with
600  * the given connectors.
601  */
602
603 static bool intel_PLL_is_valid(struct drm_device *dev,
604                                const struct intel_limit *limit,
605                                const struct dpll *clock)
606 {
607         if (clock->n   < limit->n.min   || limit->n.max   < clock->n)
608                 INTELPllInvalid("n out of range\n");
609         if (clock->p1  < limit->p1.min  || limit->p1.max  < clock->p1)
610                 INTELPllInvalid("p1 out of range\n");
611         if (clock->m2  < limit->m2.min  || limit->m2.max  < clock->m2)
612                 INTELPllInvalid("m2 out of range\n");
613         if (clock->m1  < limit->m1.min  || limit->m1.max  < clock->m1)
614                 INTELPllInvalid("m1 out of range\n");
615
616         if (!IS_PINEVIEW(dev) && !IS_VALLEYVIEW(dev) &&
617             !IS_CHERRYVIEW(dev) && !IS_BROXTON(dev))
618                 if (clock->m1 <= clock->m2)
619                         INTELPllInvalid("m1 <= m2\n");
620
621         if (!IS_VALLEYVIEW(dev) && !IS_CHERRYVIEW(dev) && !IS_BROXTON(dev)) {
622                 if (clock->p < limit->p.min || limit->p.max < clock->p)
623                         INTELPllInvalid("p out of range\n");
624                 if (clock->m < limit->m.min || limit->m.max < clock->m)
625                         INTELPllInvalid("m out of range\n");
626         }
627
628         if (clock->vco < limit->vco.min || limit->vco.max < clock->vco)
629                 INTELPllInvalid("vco out of range\n");
630         /* XXX: We may need to be checking "Dot clock" depending on the multiplier,
631          * connector, etc., rather than just a single range.
632          */
633         if (clock->dot < limit->dot.min || limit->dot.max < clock->dot)
634                 INTELPllInvalid("dot out of range\n");
635
636         return true;
637 }
638
639 static int
640 i9xx_select_p2_div(const struct intel_limit *limit,
641                    const struct intel_crtc_state *crtc_state,
642                    int target)
643 {
644         struct drm_device *dev = crtc_state->base.crtc->dev;
645
646         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS)) {
647                 /*
648                  * For LVDS just rely on its current settings for dual-channel.
649                  * We haven't figured out how to reliably set up different
650                  * single/dual channel state, if we even can.
651                  */
652                 if (intel_is_dual_link_lvds(dev))
653                         return limit->p2.p2_fast;
654                 else
655                         return limit->p2.p2_slow;
656         } else {
657                 if (target < limit->p2.dot_limit)
658                         return limit->p2.p2_slow;
659                 else
660                         return limit->p2.p2_fast;
661         }
662 }
663
664 /*
665  * Returns a set of divisors for the desired target clock with the given
666  * refclk, or FALSE.  The returned values represent the clock equation:
667  * reflck * (5 * (m1 + 2) + (m2 + 2)) / (n + 2) / p1 / p2.
668  *
669  * Target and reference clocks are specified in kHz.
670  *
671  * If match_clock is provided, then best_clock P divider must match the P
672  * divider from @match_clock used for LVDS downclocking.
673  */
674 static bool
675 i9xx_find_best_dpll(const struct intel_limit *limit,
676                     struct intel_crtc_state *crtc_state,
677                     int target, int refclk, struct dpll *match_clock,
678                     struct dpll *best_clock)
679 {
680         struct drm_device *dev = crtc_state->base.crtc->dev;
681         struct dpll clock;
682         int err = target;
683
684         memset(best_clock, 0, sizeof(*best_clock));
685
686         clock.p2 = i9xx_select_p2_div(limit, crtc_state, target);
687
688         for (clock.m1 = limit->m1.min; clock.m1 <= limit->m1.max;
689              clock.m1++) {
690                 for (clock.m2 = limit->m2.min;
691                      clock.m2 <= limit->m2.max; clock.m2++) {
692                         if (clock.m2 >= clock.m1)
693                                 break;
694                         for (clock.n = limit->n.min;
695                              clock.n <= limit->n.max; clock.n++) {
696                                 for (clock.p1 = limit->p1.min;
697                                         clock.p1 <= limit->p1.max; clock.p1++) {
698                                         int this_err;
699
700                                         i9xx_calc_dpll_params(refclk, &clock);
701                                         if (!intel_PLL_is_valid(dev, limit,
702                                                                 &clock))
703                                                 continue;
704                                         if (match_clock &&
705                                             clock.p != match_clock->p)
706                                                 continue;
707
708                                         this_err = abs(clock.dot - target);
709                                         if (this_err < err) {
710                                                 *best_clock = clock;
711                                                 err = this_err;
712                                         }
713                                 }
714                         }
715                 }
716         }
717
718         return (err != target);
719 }
720
721 /*
722  * Returns a set of divisors for the desired target clock with the given
723  * refclk, or FALSE.  The returned values represent the clock equation:
724  * reflck * (5 * (m1 + 2) + (m2 + 2)) / (n + 2) / p1 / p2.
725  *
726  * Target and reference clocks are specified in kHz.
727  *
728  * If match_clock is provided, then best_clock P divider must match the P
729  * divider from @match_clock used for LVDS downclocking.
730  */
731 static bool
732 pnv_find_best_dpll(const struct intel_limit *limit,
733                    struct intel_crtc_state *crtc_state,
734                    int target, int refclk, struct dpll *match_clock,
735                    struct dpll *best_clock)
736 {
737         struct drm_device *dev = crtc_state->base.crtc->dev;
738         struct dpll clock;
739         int err = target;
740
741         memset(best_clock, 0, sizeof(*best_clock));
742
743         clock.p2 = i9xx_select_p2_div(limit, crtc_state, target);
744
745         for (clock.m1 = limit->m1.min; clock.m1 <= limit->m1.max;
746              clock.m1++) {
747                 for (clock.m2 = limit->m2.min;
748                      clock.m2 <= limit->m2.max; clock.m2++) {
749                         for (clock.n = limit->n.min;
750                              clock.n <= limit->n.max; clock.n++) {
751                                 for (clock.p1 = limit->p1.min;
752                                         clock.p1 <= limit->p1.max; clock.p1++) {
753                                         int this_err;
754
755                                         pnv_calc_dpll_params(refclk, &clock);
756                                         if (!intel_PLL_is_valid(dev, limit,
757                                                                 &clock))
758                                                 continue;
759                                         if (match_clock &&
760                                             clock.p != match_clock->p)
761                                                 continue;
762
763                                         this_err = abs(clock.dot - target);
764                                         if (this_err < err) {
765                                                 *best_clock = clock;
766                                                 err = this_err;
767                                         }
768                                 }
769                         }
770                 }
771         }
772
773         return (err != target);
774 }
775
776 /*
777  * Returns a set of divisors for the desired target clock with the given
778  * refclk, or FALSE.  The returned values represent the clock equation:
779  * reflck * (5 * (m1 + 2) + (m2 + 2)) / (n + 2) / p1 / p2.
780  *
781  * Target and reference clocks are specified in kHz.
782  *
783  * If match_clock is provided, then best_clock P divider must match the P
784  * divider from @match_clock used for LVDS downclocking.
785  */
786 static bool
787 g4x_find_best_dpll(const struct intel_limit *limit,
788                    struct intel_crtc_state *crtc_state,
789                    int target, int refclk, struct dpll *match_clock,
790                    struct dpll *best_clock)
791 {
792         struct drm_device *dev = crtc_state->base.crtc->dev;
793         struct dpll clock;
794         int max_n;
795         bool found = false;
796         /* approximately equals target * 0.00585 */
797         int err_most = (target >> 8) + (target >> 9);
798
799         memset(best_clock, 0, sizeof(*best_clock));
800
801         clock.p2 = i9xx_select_p2_div(limit, crtc_state, target);
802
803         max_n = limit->n.max;
804         /* based on hardware requirement, prefer smaller n to precision */
805         for (clock.n = limit->n.min; clock.n <= max_n; clock.n++) {
806                 /* based on hardware requirement, prefere larger m1,m2 */
807                 for (clock.m1 = limit->m1.max;
808                      clock.m1 >= limit->m1.min; clock.m1--) {
809                         for (clock.m2 = limit->m2.max;
810                              clock.m2 >= limit->m2.min; clock.m2--) {
811                                 for (clock.p1 = limit->p1.max;
812                                      clock.p1 >= limit->p1.min; clock.p1--) {
813                                         int this_err;
814
815                                         i9xx_calc_dpll_params(refclk, &clock);
816                                         if (!intel_PLL_is_valid(dev, limit,
817                                                                 &clock))
818                                                 continue;
819
820                                         this_err = abs(clock.dot - target);
821                                         if (this_err < err_most) {
822                                                 *best_clock = clock;
823                                                 err_most = this_err;
824                                                 max_n = clock.n;
825                                                 found = true;
826                                         }
827                                 }
828                         }
829                 }
830         }
831         return found;
832 }
833
834 /*
835  * Check if the calculated PLL configuration is more optimal compared to the
836  * best configuration and error found so far. Return the calculated error.
837  */
838 static bool vlv_PLL_is_optimal(struct drm_device *dev, int target_freq,
839                                const struct dpll *calculated_clock,
840                                const struct dpll *best_clock,
841                                unsigned int best_error_ppm,
842                                unsigned int *error_ppm)
843 {
844         /*
845          * For CHV ignore the error and consider only the P value.
846          * Prefer a bigger P value based on HW requirements.
847          */
848         if (IS_CHERRYVIEW(dev)) {
849                 *error_ppm = 0;
850
851                 return calculated_clock->p > best_clock->p;
852         }
853
854         if (WARN_ON_ONCE(!target_freq))
855                 return false;
856
857         *error_ppm = div_u64(1000000ULL *
858                                 abs(target_freq - calculated_clock->dot),
859                              target_freq);
860         /*
861          * Prefer a better P value over a better (smaller) error if the error
862          * is small. Ensure this preference for future configurations too by
863          * setting the error to 0.
864          */
865         if (*error_ppm < 100 && calculated_clock->p > best_clock->p) {
866                 *error_ppm = 0;
867
868                 return true;
869         }
870
871         return *error_ppm + 10 < best_error_ppm;
872 }
873
874 /*
875  * Returns a set of divisors for the desired target clock with the given
876  * refclk, or FALSE.  The returned values represent the clock equation:
877  * reflck * (5 * (m1 + 2) + (m2 + 2)) / (n + 2) / p1 / p2.
878  */
879 static bool
880 vlv_find_best_dpll(const struct intel_limit *limit,
881                    struct intel_crtc_state *crtc_state,
882                    int target, int refclk, struct dpll *match_clock,
883                    struct dpll *best_clock)
884 {
885         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
886         struct drm_device *dev = crtc->base.dev;
887         struct dpll clock;
888         unsigned int bestppm = 1000000;
889         /* min update 19.2 MHz */
890         int max_n = min(limit->n.max, refclk / 19200);
891         bool found = false;
892
893         target *= 5; /* fast clock */
894
895         memset(best_clock, 0, sizeof(*best_clock));
896
897         /* based on hardware requirement, prefer smaller n to precision */
898         for (clock.n = limit->n.min; clock.n <= max_n; clock.n++) {
899                 for (clock.p1 = limit->p1.max; clock.p1 >= limit->p1.min; clock.p1--) {
900                         for (clock.p2 = limit->p2.p2_fast; clock.p2 >= limit->p2.p2_slow;
901                              clock.p2 -= clock.p2 > 10 ? 2 : 1) {
902                                 clock.p = clock.p1 * clock.p2;
903                                 /* based on hardware requirement, prefer bigger m1,m2 values */
904                                 for (clock.m1 = limit->m1.min; clock.m1 <= limit->m1.max; clock.m1++) {
905                                         unsigned int ppm;
906
907                                         clock.m2 = DIV_ROUND_CLOSEST(target * clock.p * clock.n,
908                                                                      refclk * clock.m1);
909
910                                         vlv_calc_dpll_params(refclk, &clock);
911
912                                         if (!intel_PLL_is_valid(dev, limit,
913                                                                 &clock))
914                                                 continue;
915
916                                         if (!vlv_PLL_is_optimal(dev, target,
917                                                                 &clock,
918                                                                 best_clock,
919                                                                 bestppm, &ppm))
920                                                 continue;
921
922                                         *best_clock = clock;
923                                         bestppm = ppm;
924                                         found = true;
925                                 }
926                         }
927                 }
928         }
929
930         return found;
931 }
932
933 /*
934  * Returns a set of divisors for the desired target clock with the given
935  * refclk, or FALSE.  The returned values represent the clock equation:
936  * reflck * (5 * (m1 + 2) + (m2 + 2)) / (n + 2) / p1 / p2.
937  */
938 static bool
939 chv_find_best_dpll(const struct intel_limit *limit,
940                    struct intel_crtc_state *crtc_state,
941                    int target, int refclk, struct dpll *match_clock,
942                    struct dpll *best_clock)
943 {
944         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
945         struct drm_device *dev = crtc->base.dev;
946         unsigned int best_error_ppm;
947         struct dpll clock;
948         uint64_t m2;
949         int found = false;
950
951         memset(best_clock, 0, sizeof(*best_clock));
952         best_error_ppm = 1000000;
953
954         /*
955          * Based on hardware doc, the n always set to 1, and m1 always
956          * set to 2.  If requires to support 200Mhz refclk, we need to
957          * revisit this because n may not 1 anymore.
958          */
959         clock.n = 1, clock.m1 = 2;
960         target *= 5;    /* fast clock */
961
962         for (clock.p1 = limit->p1.max; clock.p1 >= limit->p1.min; clock.p1--) {
963                 for (clock.p2 = limit->p2.p2_fast;
964                                 clock.p2 >= limit->p2.p2_slow;
965                                 clock.p2 -= clock.p2 > 10 ? 2 : 1) {
966                         unsigned int error_ppm;
967
968                         clock.p = clock.p1 * clock.p2;
969
970                         m2 = DIV_ROUND_CLOSEST_ULL(((uint64_t)target * clock.p *
971                                         clock.n) << 22, refclk * clock.m1);
972
973                         if (m2 > INT_MAX/clock.m1)
974                                 continue;
975
976                         clock.m2 = m2;
977
978                         chv_calc_dpll_params(refclk, &clock);
979
980                         if (!intel_PLL_is_valid(dev, limit, &clock))
981                                 continue;
982
983                         if (!vlv_PLL_is_optimal(dev, target, &clock, best_clock,
984                                                 best_error_ppm, &error_ppm))
985                                 continue;
986
987                         *best_clock = clock;
988                         best_error_ppm = error_ppm;
989                         found = true;
990                 }
991         }
992
993         return found;
994 }
995
996 bool bxt_find_best_dpll(struct intel_crtc_state *crtc_state, int target_clock,
997                         struct dpll *best_clock)
998 {
999         int refclk = 100000;
1000         const struct intel_limit *limit = &intel_limits_bxt;
1001
1002         return chv_find_best_dpll(limit, crtc_state,
1003                                   target_clock, refclk, NULL, best_clock);
1004 }
1005
1006 bool intel_crtc_active(struct drm_crtc *crtc)
1007 {
1008         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
1009
1010         /* Be paranoid as we can arrive here with only partial
1011          * state retrieved from the hardware during setup.
1012          *
1013          * We can ditch the adjusted_mode.crtc_clock check as soon
1014          * as Haswell has gained clock readout/fastboot support.
1015          *
1016          * We can ditch the crtc->primary->fb check as soon as we can
1017          * properly reconstruct framebuffers.
1018          *
1019          * FIXME: The intel_crtc->active here should be switched to
1020          * crtc->state->active once we have proper CRTC states wired up
1021          * for atomic.
1022          */
1023         return intel_crtc->active && crtc->primary->state->fb &&
1024                 intel_crtc->config->base.adjusted_mode.crtc_clock;
1025 }
1026
1027 enum transcoder intel_pipe_to_cpu_transcoder(struct drm_i915_private *dev_priv,
1028                                              enum pipe pipe)
1029 {
1030         struct drm_crtc *crtc = dev_priv->pipe_to_crtc_mapping[pipe];
1031         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
1032
1033         return intel_crtc->config->cpu_transcoder;
1034 }
1035
1036 static bool pipe_dsl_stopped(struct drm_device *dev, enum pipe pipe)
1037 {
1038         struct drm_i915_private *dev_priv = to_i915(dev);
1039         i915_reg_t reg = PIPEDSL(pipe);
1040         u32 line1, line2;
1041         u32 line_mask;
1042
1043         if (IS_GEN2(dev))
1044                 line_mask = DSL_LINEMASK_GEN2;
1045         else
1046                 line_mask = DSL_LINEMASK_GEN3;
1047
1048         line1 = I915_READ(reg) & line_mask;
1049         msleep(5);
1050         line2 = I915_READ(reg) & line_mask;
1051
1052         return line1 == line2;
1053 }
1054
1055 /*
1056  * intel_wait_for_pipe_off - wait for pipe to turn off
1057  * @crtc: crtc whose pipe to wait for
1058  *
1059  * After disabling a pipe, we can't wait for vblank in the usual way,
1060  * spinning on the vblank interrupt status bit, since we won't actually
1061  * see an interrupt when the pipe is disabled.
1062  *
1063  * On Gen4 and above:
1064  *   wait for the pipe register state bit to turn off
1065  *
1066  * Otherwise:
1067  *   wait for the display line value to settle (it usually
1068  *   ends up stopping at the start of the next frame).
1069  *
1070  */
1071 static void intel_wait_for_pipe_off(struct intel_crtc *crtc)
1072 {
1073         struct drm_device *dev = crtc->base.dev;
1074         struct drm_i915_private *dev_priv = to_i915(dev);
1075         enum transcoder cpu_transcoder = crtc->config->cpu_transcoder;
1076         enum pipe pipe = crtc->pipe;
1077
1078         if (INTEL_INFO(dev)->gen >= 4) {
1079                 i915_reg_t reg = PIPECONF(cpu_transcoder);
1080
1081                 /* Wait for the Pipe State to go off */
1082                 if (intel_wait_for_register(dev_priv,
1083                                             reg, I965_PIPECONF_ACTIVE, 0,
1084                                             100))
1085                         WARN(1, "pipe_off wait timed out\n");
1086         } else {
1087                 /* Wait for the display line to settle */
1088                 if (wait_for(pipe_dsl_stopped(dev, pipe), 100))
1089                         WARN(1, "pipe_off wait timed out\n");
1090         }
1091 }
1092
1093 /* Only for pre-ILK configs */
1094 void assert_pll(struct drm_i915_private *dev_priv,
1095                 enum pipe pipe, bool state)
1096 {
1097         u32 val;
1098         bool cur_state;
1099
1100         val = I915_READ(DPLL(pipe));
1101         cur_state = !!(val & DPLL_VCO_ENABLE);
1102         I915_STATE_WARN(cur_state != state,
1103              "PLL state assertion failure (expected %s, current %s)\n",
1104                         onoff(state), onoff(cur_state));
1105 }
1106
1107 /* XXX: the dsi pll is shared between MIPI DSI ports */
1108 void assert_dsi_pll(struct drm_i915_private *dev_priv, bool state)
1109 {
1110         u32 val;
1111         bool cur_state;
1112
1113         mutex_lock(&dev_priv->sb_lock);
1114         val = vlv_cck_read(dev_priv, CCK_REG_DSI_PLL_CONTROL);
1115         mutex_unlock(&dev_priv->sb_lock);
1116
1117         cur_state = val & DSI_PLL_VCO_EN;
1118         I915_STATE_WARN(cur_state != state,
1119              "DSI PLL state assertion failure (expected %s, current %s)\n",
1120                         onoff(state), onoff(cur_state));
1121 }
1122
1123 static void assert_fdi_tx(struct drm_i915_private *dev_priv,
1124                           enum pipe pipe, bool state)
1125 {
1126         bool cur_state;
1127         enum transcoder cpu_transcoder = intel_pipe_to_cpu_transcoder(dev_priv,
1128                                                                       pipe);
1129
1130         if (HAS_DDI(dev_priv)) {
1131                 /* DDI does not have a specific FDI_TX register */
1132                 u32 val = I915_READ(TRANS_DDI_FUNC_CTL(cpu_transcoder));
1133                 cur_state = !!(val & TRANS_DDI_FUNC_ENABLE);
1134         } else {
1135                 u32 val = I915_READ(FDI_TX_CTL(pipe));
1136                 cur_state = !!(val & FDI_TX_ENABLE);
1137         }
1138         I915_STATE_WARN(cur_state != state,
1139              "FDI TX state assertion failure (expected %s, current %s)\n",
1140                         onoff(state), onoff(cur_state));
1141 }
1142 #define assert_fdi_tx_enabled(d, p) assert_fdi_tx(d, p, true)
1143 #define assert_fdi_tx_disabled(d, p) assert_fdi_tx(d, p, false)
1144
1145 static void assert_fdi_rx(struct drm_i915_private *dev_priv,
1146                           enum pipe pipe, bool state)
1147 {
1148         u32 val;
1149         bool cur_state;
1150
1151         val = I915_READ(FDI_RX_CTL(pipe));
1152         cur_state = !!(val & FDI_RX_ENABLE);
1153         I915_STATE_WARN(cur_state != state,
1154              "FDI RX state assertion failure (expected %s, current %s)\n",
1155                         onoff(state), onoff(cur_state));
1156 }
1157 #define assert_fdi_rx_enabled(d, p) assert_fdi_rx(d, p, true)
1158 #define assert_fdi_rx_disabled(d, p) assert_fdi_rx(d, p, false)
1159
1160 static void assert_fdi_tx_pll_enabled(struct drm_i915_private *dev_priv,
1161                                       enum pipe pipe)
1162 {
1163         u32 val;
1164
1165         /* ILK FDI PLL is always enabled */
1166         if (IS_GEN5(dev_priv))
1167                 return;
1168
1169         /* On Haswell, DDI ports are responsible for the FDI PLL setup */
1170         if (HAS_DDI(dev_priv))
1171                 return;
1172
1173         val = I915_READ(FDI_TX_CTL(pipe));
1174         I915_STATE_WARN(!(val & FDI_TX_PLL_ENABLE), "FDI TX PLL assertion failure, should be active but is disabled\n");
1175 }
1176
1177 void assert_fdi_rx_pll(struct drm_i915_private *dev_priv,
1178                        enum pipe pipe, bool state)
1179 {
1180         u32 val;
1181         bool cur_state;
1182
1183         val = I915_READ(FDI_RX_CTL(pipe));
1184         cur_state = !!(val & FDI_RX_PLL_ENABLE);
1185         I915_STATE_WARN(cur_state != state,
1186              "FDI RX PLL assertion failure (expected %s, current %s)\n",
1187                         onoff(state), onoff(cur_state));
1188 }
1189
1190 void assert_panel_unlocked(struct drm_i915_private *dev_priv,
1191                            enum pipe pipe)
1192 {
1193         struct drm_device *dev = &dev_priv->drm;
1194         i915_reg_t pp_reg;
1195         u32 val;
1196         enum pipe panel_pipe = PIPE_A;
1197         bool locked = true;
1198
1199         if (WARN_ON(HAS_DDI(dev)))
1200                 return;
1201
1202         if (HAS_PCH_SPLIT(dev)) {
1203                 u32 port_sel;
1204
1205                 pp_reg = PCH_PP_CONTROL;
1206                 port_sel = I915_READ(PCH_PP_ON_DELAYS) & PANEL_PORT_SELECT_MASK;
1207
1208                 if (port_sel == PANEL_PORT_SELECT_LVDS &&
1209                     I915_READ(PCH_LVDS) & LVDS_PIPEB_SELECT)
1210                         panel_pipe = PIPE_B;
1211                 /* XXX: else fix for eDP */
1212         } else if (IS_VALLEYVIEW(dev) || IS_CHERRYVIEW(dev)) {
1213                 /* presumably write lock depends on pipe, not port select */
1214                 pp_reg = VLV_PIPE_PP_CONTROL(pipe);
1215                 panel_pipe = pipe;
1216         } else {
1217                 pp_reg = PP_CONTROL;
1218                 if (I915_READ(LVDS) & LVDS_PIPEB_SELECT)
1219                         panel_pipe = PIPE_B;
1220         }
1221
1222         val = I915_READ(pp_reg);
1223         if (!(val & PANEL_POWER_ON) ||
1224             ((val & PANEL_UNLOCK_MASK) == PANEL_UNLOCK_REGS))
1225                 locked = false;
1226
1227         I915_STATE_WARN(panel_pipe == pipe && locked,
1228              "panel assertion failure, pipe %c regs locked\n",
1229              pipe_name(pipe));
1230 }
1231
1232 static void assert_cursor(struct drm_i915_private *dev_priv,
1233                           enum pipe pipe, bool state)
1234 {
1235         struct drm_device *dev = &dev_priv->drm;
1236         bool cur_state;
1237
1238         if (IS_845G(dev) || IS_I865G(dev))
1239                 cur_state = I915_READ(CURCNTR(PIPE_A)) & CURSOR_ENABLE;
1240         else
1241                 cur_state = I915_READ(CURCNTR(pipe)) & CURSOR_MODE;
1242
1243         I915_STATE_WARN(cur_state != state,
1244              "cursor on pipe %c assertion failure (expected %s, current %s)\n",
1245                         pipe_name(pipe), onoff(state), onoff(cur_state));
1246 }
1247 #define assert_cursor_enabled(d, p) assert_cursor(d, p, true)
1248 #define assert_cursor_disabled(d, p) assert_cursor(d, p, false)
1249
1250 void assert_pipe(struct drm_i915_private *dev_priv,
1251                  enum pipe pipe, bool state)
1252 {
1253         bool cur_state;
1254         enum transcoder cpu_transcoder = intel_pipe_to_cpu_transcoder(dev_priv,
1255                                                                       pipe);
1256         enum intel_display_power_domain power_domain;
1257
1258         /* if we need the pipe quirk it must be always on */
1259         if ((pipe == PIPE_A && dev_priv->quirks & QUIRK_PIPEA_FORCE) ||
1260             (pipe == PIPE_B && dev_priv->quirks & QUIRK_PIPEB_FORCE))
1261                 state = true;
1262
1263         power_domain = POWER_DOMAIN_TRANSCODER(cpu_transcoder);
1264         if (intel_display_power_get_if_enabled(dev_priv, power_domain)) {
1265                 u32 val = I915_READ(PIPECONF(cpu_transcoder));
1266                 cur_state = !!(val & PIPECONF_ENABLE);
1267
1268                 intel_display_power_put(dev_priv, power_domain);
1269         } else {
1270                 cur_state = false;
1271         }
1272
1273         I915_STATE_WARN(cur_state != state,
1274              "pipe %c assertion failure (expected %s, current %s)\n",
1275                         pipe_name(pipe), onoff(state), onoff(cur_state));
1276 }
1277
1278 static void assert_plane(struct drm_i915_private *dev_priv,
1279                          enum plane plane, bool state)
1280 {
1281         u32 val;
1282         bool cur_state;
1283
1284         val = I915_READ(DSPCNTR(plane));
1285         cur_state = !!(val & DISPLAY_PLANE_ENABLE);
1286         I915_STATE_WARN(cur_state != state,
1287              "plane %c assertion failure (expected %s, current %s)\n",
1288                         plane_name(plane), onoff(state), onoff(cur_state));
1289 }
1290
1291 #define assert_plane_enabled(d, p) assert_plane(d, p, true)
1292 #define assert_plane_disabled(d, p) assert_plane(d, p, false)
1293
1294 static void assert_planes_disabled(struct drm_i915_private *dev_priv,
1295                                    enum pipe pipe)
1296 {
1297         struct drm_device *dev = &dev_priv->drm;
1298         int i;
1299
1300         /* Primary planes are fixed to pipes on gen4+ */
1301         if (INTEL_INFO(dev)->gen >= 4) {
1302                 u32 val = I915_READ(DSPCNTR(pipe));
1303                 I915_STATE_WARN(val & DISPLAY_PLANE_ENABLE,
1304                      "plane %c assertion failure, should be disabled but not\n",
1305                      plane_name(pipe));
1306                 return;
1307         }
1308
1309         /* Need to check both planes against the pipe */
1310         for_each_pipe(dev_priv, i) {
1311                 u32 val = I915_READ(DSPCNTR(i));
1312                 enum pipe cur_pipe = (val & DISPPLANE_SEL_PIPE_MASK) >>
1313                         DISPPLANE_SEL_PIPE_SHIFT;
1314                 I915_STATE_WARN((val & DISPLAY_PLANE_ENABLE) && pipe == cur_pipe,
1315                      "plane %c assertion failure, should be off on pipe %c but is still active\n",
1316                      plane_name(i), pipe_name(pipe));
1317         }
1318 }
1319
1320 static void assert_sprites_disabled(struct drm_i915_private *dev_priv,
1321                                     enum pipe pipe)
1322 {
1323         struct drm_device *dev = &dev_priv->drm;
1324         int sprite;
1325
1326         if (INTEL_INFO(dev)->gen >= 9) {
1327                 for_each_sprite(dev_priv, pipe, sprite) {
1328                         u32 val = I915_READ(PLANE_CTL(pipe, sprite));
1329                         I915_STATE_WARN(val & PLANE_CTL_ENABLE,
1330                              "plane %d assertion failure, should be off on pipe %c but is still active\n",
1331                              sprite, pipe_name(pipe));
1332                 }
1333         } else if (IS_VALLEYVIEW(dev) || IS_CHERRYVIEW(dev)) {
1334                 for_each_sprite(dev_priv, pipe, sprite) {
1335                         u32 val = I915_READ(SPCNTR(pipe, sprite));
1336                         I915_STATE_WARN(val & SP_ENABLE,
1337                              "sprite %c assertion failure, should be off on pipe %c but is still active\n",
1338                              sprite_name(pipe, sprite), pipe_name(pipe));
1339                 }
1340         } else if (INTEL_INFO(dev)->gen >= 7) {
1341                 u32 val = I915_READ(SPRCTL(pipe));
1342                 I915_STATE_WARN(val & SPRITE_ENABLE,
1343                      "sprite %c assertion failure, should be off on pipe %c but is still active\n",
1344                      plane_name(pipe), pipe_name(pipe));
1345         } else if (INTEL_INFO(dev)->gen >= 5) {
1346                 u32 val = I915_READ(DVSCNTR(pipe));
1347                 I915_STATE_WARN(val & DVS_ENABLE,
1348                      "sprite %c assertion failure, should be off on pipe %c but is still active\n",
1349                      plane_name(pipe), pipe_name(pipe));
1350         }
1351 }
1352
1353 static void assert_vblank_disabled(struct drm_crtc *crtc)
1354 {
1355         if (I915_STATE_WARN_ON(drm_crtc_vblank_get(crtc) == 0))
1356                 drm_crtc_vblank_put(crtc);
1357 }
1358
1359 void assert_pch_transcoder_disabled(struct drm_i915_private *dev_priv,
1360                                     enum pipe pipe)
1361 {
1362         u32 val;
1363         bool enabled;
1364
1365         val = I915_READ(PCH_TRANSCONF(pipe));
1366         enabled = !!(val & TRANS_ENABLE);
1367         I915_STATE_WARN(enabled,
1368              "transcoder assertion failed, should be off on pipe %c but is still active\n",
1369              pipe_name(pipe));
1370 }
1371
1372 static bool dp_pipe_enabled(struct drm_i915_private *dev_priv,
1373                             enum pipe pipe, u32 port_sel, u32 val)
1374 {
1375         if ((val & DP_PORT_EN) == 0)
1376                 return false;
1377
1378         if (HAS_PCH_CPT(dev_priv)) {
1379                 u32 trans_dp_ctl = I915_READ(TRANS_DP_CTL(pipe));
1380                 if ((trans_dp_ctl & TRANS_DP_PORT_SEL_MASK) != port_sel)
1381                         return false;
1382         } else if (IS_CHERRYVIEW(dev_priv)) {
1383                 if ((val & DP_PIPE_MASK_CHV) != DP_PIPE_SELECT_CHV(pipe))
1384                         return false;
1385         } else {
1386                 if ((val & DP_PIPE_MASK) != (pipe << 30))
1387                         return false;
1388         }
1389         return true;
1390 }
1391
1392 static bool hdmi_pipe_enabled(struct drm_i915_private *dev_priv,
1393                               enum pipe pipe, u32 val)
1394 {
1395         if ((val & SDVO_ENABLE) == 0)
1396                 return false;
1397
1398         if (HAS_PCH_CPT(dev_priv)) {
1399                 if ((val & SDVO_PIPE_SEL_MASK_CPT) != SDVO_PIPE_SEL_CPT(pipe))
1400                         return false;
1401         } else if (IS_CHERRYVIEW(dev_priv)) {
1402                 if ((val & SDVO_PIPE_SEL_MASK_CHV) != SDVO_PIPE_SEL_CHV(pipe))
1403                         return false;
1404         } else {
1405                 if ((val & SDVO_PIPE_SEL_MASK) != SDVO_PIPE_SEL(pipe))
1406                         return false;
1407         }
1408         return true;
1409 }
1410
1411 static bool lvds_pipe_enabled(struct drm_i915_private *dev_priv,
1412                               enum pipe pipe, u32 val)
1413 {
1414         if ((val & LVDS_PORT_EN) == 0)
1415                 return false;
1416
1417         if (HAS_PCH_CPT(dev_priv)) {
1418                 if ((val & PORT_TRANS_SEL_MASK) != PORT_TRANS_SEL_CPT(pipe))
1419                         return false;
1420         } else {
1421                 if ((val & LVDS_PIPE_MASK) != LVDS_PIPE(pipe))
1422                         return false;
1423         }
1424         return true;
1425 }
1426
1427 static bool adpa_pipe_enabled(struct drm_i915_private *dev_priv,
1428                               enum pipe pipe, u32 val)
1429 {
1430         if ((val & ADPA_DAC_ENABLE) == 0)
1431                 return false;
1432         if (HAS_PCH_CPT(dev_priv)) {
1433                 if ((val & PORT_TRANS_SEL_MASK) != PORT_TRANS_SEL_CPT(pipe))
1434                         return false;
1435         } else {
1436                 if ((val & ADPA_PIPE_SELECT_MASK) != ADPA_PIPE_SELECT(pipe))
1437                         return false;
1438         }
1439         return true;
1440 }
1441
1442 static void assert_pch_dp_disabled(struct drm_i915_private *dev_priv,
1443                                    enum pipe pipe, i915_reg_t reg,
1444                                    u32 port_sel)
1445 {
1446         u32 val = I915_READ(reg);
1447         I915_STATE_WARN(dp_pipe_enabled(dev_priv, pipe, port_sel, val),
1448              "PCH DP (0x%08x) enabled on transcoder %c, should be disabled\n",
1449              i915_mmio_reg_offset(reg), pipe_name(pipe));
1450
1451         I915_STATE_WARN(HAS_PCH_IBX(dev_priv) && (val & DP_PORT_EN) == 0
1452              && (val & DP_PIPEB_SELECT),
1453              "IBX PCH dp port still using transcoder B\n");
1454 }
1455
1456 static void assert_pch_hdmi_disabled(struct drm_i915_private *dev_priv,
1457                                      enum pipe pipe, i915_reg_t reg)
1458 {
1459         u32 val = I915_READ(reg);
1460         I915_STATE_WARN(hdmi_pipe_enabled(dev_priv, pipe, val),
1461              "PCH HDMI (0x%08x) enabled on transcoder %c, should be disabled\n",
1462              i915_mmio_reg_offset(reg), pipe_name(pipe));
1463
1464         I915_STATE_WARN(HAS_PCH_IBX(dev_priv) && (val & SDVO_ENABLE) == 0
1465              && (val & SDVO_PIPE_B_SELECT),
1466              "IBX PCH hdmi port still using transcoder B\n");
1467 }
1468
1469 static void assert_pch_ports_disabled(struct drm_i915_private *dev_priv,
1470                                       enum pipe pipe)
1471 {
1472         u32 val;
1473
1474         assert_pch_dp_disabled(dev_priv, pipe, PCH_DP_B, TRANS_DP_PORT_SEL_B);
1475         assert_pch_dp_disabled(dev_priv, pipe, PCH_DP_C, TRANS_DP_PORT_SEL_C);
1476         assert_pch_dp_disabled(dev_priv, pipe, PCH_DP_D, TRANS_DP_PORT_SEL_D);
1477
1478         val = I915_READ(PCH_ADPA);
1479         I915_STATE_WARN(adpa_pipe_enabled(dev_priv, pipe, val),
1480              "PCH VGA enabled on transcoder %c, should be disabled\n",
1481              pipe_name(pipe));
1482
1483         val = I915_READ(PCH_LVDS);
1484         I915_STATE_WARN(lvds_pipe_enabled(dev_priv, pipe, val),
1485              "PCH LVDS enabled on transcoder %c, should be disabled\n",
1486              pipe_name(pipe));
1487
1488         assert_pch_hdmi_disabled(dev_priv, pipe, PCH_HDMIB);
1489         assert_pch_hdmi_disabled(dev_priv, pipe, PCH_HDMIC);
1490         assert_pch_hdmi_disabled(dev_priv, pipe, PCH_HDMID);
1491 }
1492
1493 static void _vlv_enable_pll(struct intel_crtc *crtc,
1494                             const struct intel_crtc_state *pipe_config)
1495 {
1496         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
1497         enum pipe pipe = crtc->pipe;
1498
1499         I915_WRITE(DPLL(pipe), pipe_config->dpll_hw_state.dpll);
1500         POSTING_READ(DPLL(pipe));
1501         udelay(150);
1502
1503         if (intel_wait_for_register(dev_priv,
1504                                     DPLL(pipe),
1505                                     DPLL_LOCK_VLV,
1506                                     DPLL_LOCK_VLV,
1507                                     1))
1508                 DRM_ERROR("DPLL %d failed to lock\n", pipe);
1509 }
1510
1511 static void vlv_enable_pll(struct intel_crtc *crtc,
1512                            const struct intel_crtc_state *pipe_config)
1513 {
1514         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
1515         enum pipe pipe = crtc->pipe;
1516
1517         assert_pipe_disabled(dev_priv, pipe);
1518
1519         /* PLL is protected by panel, make sure we can write it */
1520         assert_panel_unlocked(dev_priv, pipe);
1521
1522         if (pipe_config->dpll_hw_state.dpll & DPLL_VCO_ENABLE)
1523                 _vlv_enable_pll(crtc, pipe_config);
1524
1525         I915_WRITE(DPLL_MD(pipe), pipe_config->dpll_hw_state.dpll_md);
1526         POSTING_READ(DPLL_MD(pipe));
1527 }
1528
1529
1530 static void _chv_enable_pll(struct intel_crtc *crtc,
1531                             const struct intel_crtc_state *pipe_config)
1532 {
1533         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
1534         enum pipe pipe = crtc->pipe;
1535         enum dpio_channel port = vlv_pipe_to_channel(pipe);
1536         u32 tmp;
1537
1538         mutex_lock(&dev_priv->sb_lock);
1539
1540         /* Enable back the 10bit clock to display controller */
1541         tmp = vlv_dpio_read(dev_priv, pipe, CHV_CMN_DW14(port));
1542         tmp |= DPIO_DCLKP_EN;
1543         vlv_dpio_write(dev_priv, pipe, CHV_CMN_DW14(port), tmp);
1544
1545         mutex_unlock(&dev_priv->sb_lock);
1546
1547         /*
1548          * Need to wait > 100ns between dclkp clock enable bit and PLL enable.
1549          */
1550         udelay(1);
1551
1552         /* Enable PLL */
1553         I915_WRITE(DPLL(pipe), pipe_config->dpll_hw_state.dpll);
1554
1555         /* Check PLL is locked */
1556         if (intel_wait_for_register(dev_priv,
1557                                     DPLL(pipe), DPLL_LOCK_VLV, DPLL_LOCK_VLV,
1558                                     1))
1559                 DRM_ERROR("PLL %d failed to lock\n", pipe);
1560 }
1561
1562 static void chv_enable_pll(struct intel_crtc *crtc,
1563                            const struct intel_crtc_state *pipe_config)
1564 {
1565         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
1566         enum pipe pipe = crtc->pipe;
1567
1568         assert_pipe_disabled(dev_priv, pipe);
1569
1570         /* PLL is protected by panel, make sure we can write it */
1571         assert_panel_unlocked(dev_priv, pipe);
1572
1573         if (pipe_config->dpll_hw_state.dpll & DPLL_VCO_ENABLE)
1574                 _chv_enable_pll(crtc, pipe_config);
1575
1576         if (pipe != PIPE_A) {
1577                 /*
1578                  * WaPixelRepeatModeFixForC0:chv
1579                  *
1580                  * DPLLCMD is AWOL. Use chicken bits to propagate
1581                  * the value from DPLLBMD to either pipe B or C.
1582                  */
1583                 I915_WRITE(CBR4_VLV, pipe == PIPE_B ? CBR_DPLLBMD_PIPE_B : CBR_DPLLBMD_PIPE_C);
1584                 I915_WRITE(DPLL_MD(PIPE_B), pipe_config->dpll_hw_state.dpll_md);
1585                 I915_WRITE(CBR4_VLV, 0);
1586                 dev_priv->chv_dpll_md[pipe] = pipe_config->dpll_hw_state.dpll_md;
1587
1588                 /*
1589                  * DPLLB VGA mode also seems to cause problems.
1590                  * We should always have it disabled.
1591                  */
1592                 WARN_ON((I915_READ(DPLL(PIPE_B)) & DPLL_VGA_MODE_DIS) == 0);
1593         } else {
1594                 I915_WRITE(DPLL_MD(pipe), pipe_config->dpll_hw_state.dpll_md);
1595                 POSTING_READ(DPLL_MD(pipe));
1596         }
1597 }
1598
1599 static int intel_num_dvo_pipes(struct drm_device *dev)
1600 {
1601         struct intel_crtc *crtc;
1602         int count = 0;
1603
1604         for_each_intel_crtc(dev, crtc) {
1605                 count += crtc->base.state->active &&
1606                         intel_crtc_has_type(crtc->config, INTEL_OUTPUT_DVO);
1607         }
1608
1609         return count;
1610 }
1611
1612 static void i9xx_enable_pll(struct intel_crtc *crtc)
1613 {
1614         struct drm_device *dev = crtc->base.dev;
1615         struct drm_i915_private *dev_priv = to_i915(dev);
1616         i915_reg_t reg = DPLL(crtc->pipe);
1617         u32 dpll = crtc->config->dpll_hw_state.dpll;
1618
1619         assert_pipe_disabled(dev_priv, crtc->pipe);
1620
1621         /* PLL is protected by panel, make sure we can write it */
1622         if (IS_MOBILE(dev) && !IS_I830(dev))
1623                 assert_panel_unlocked(dev_priv, crtc->pipe);
1624
1625         /* Enable DVO 2x clock on both PLLs if necessary */
1626         if (IS_I830(dev) && intel_num_dvo_pipes(dev) > 0) {
1627                 /*
1628                  * It appears to be important that we don't enable this
1629                  * for the current pipe before otherwise configuring the
1630                  * PLL. No idea how this should be handled if multiple
1631                  * DVO outputs are enabled simultaneosly.
1632                  */
1633                 dpll |= DPLL_DVO_2X_MODE;
1634                 I915_WRITE(DPLL(!crtc->pipe),
1635                            I915_READ(DPLL(!crtc->pipe)) | DPLL_DVO_2X_MODE);
1636         }
1637
1638         /*
1639          * Apparently we need to have VGA mode enabled prior to changing
1640          * the P1/P2 dividers. Otherwise the DPLL will keep using the old
1641          * dividers, even though the register value does change.
1642          */
1643         I915_WRITE(reg, 0);
1644
1645         I915_WRITE(reg, dpll);
1646
1647         /* Wait for the clocks to stabilize. */
1648         POSTING_READ(reg);
1649         udelay(150);
1650
1651         if (INTEL_INFO(dev)->gen >= 4) {
1652                 I915_WRITE(DPLL_MD(crtc->pipe),
1653                            crtc->config->dpll_hw_state.dpll_md);
1654         } else {
1655                 /* The pixel multiplier can only be updated once the
1656                  * DPLL is enabled and the clocks are stable.
1657                  *
1658                  * So write it again.
1659                  */
1660                 I915_WRITE(reg, dpll);
1661         }
1662
1663         /* We do this three times for luck */
1664         I915_WRITE(reg, dpll);
1665         POSTING_READ(reg);
1666         udelay(150); /* wait for warmup */
1667         I915_WRITE(reg, dpll);
1668         POSTING_READ(reg);
1669         udelay(150); /* wait for warmup */
1670         I915_WRITE(reg, dpll);
1671         POSTING_READ(reg);
1672         udelay(150); /* wait for warmup */
1673 }
1674
1675 /**
1676  * i9xx_disable_pll - disable a PLL
1677  * @dev_priv: i915 private structure
1678  * @pipe: pipe PLL to disable
1679  *
1680  * Disable the PLL for @pipe, making sure the pipe is off first.
1681  *
1682  * Note!  This is for pre-ILK only.
1683  */
1684 static void i9xx_disable_pll(struct intel_crtc *crtc)
1685 {
1686         struct drm_device *dev = crtc->base.dev;
1687         struct drm_i915_private *dev_priv = to_i915(dev);
1688         enum pipe pipe = crtc->pipe;
1689
1690         /* Disable DVO 2x clock on both PLLs if necessary */
1691         if (IS_I830(dev) &&
1692             intel_crtc_has_type(crtc->config, INTEL_OUTPUT_DVO) &&
1693             !intel_num_dvo_pipes(dev)) {
1694                 I915_WRITE(DPLL(PIPE_B),
1695                            I915_READ(DPLL(PIPE_B)) & ~DPLL_DVO_2X_MODE);
1696                 I915_WRITE(DPLL(PIPE_A),
1697                            I915_READ(DPLL(PIPE_A)) & ~DPLL_DVO_2X_MODE);
1698         }
1699
1700         /* Don't disable pipe or pipe PLLs if needed */
1701         if ((pipe == PIPE_A && dev_priv->quirks & QUIRK_PIPEA_FORCE) ||
1702             (pipe == PIPE_B && dev_priv->quirks & QUIRK_PIPEB_FORCE))
1703                 return;
1704
1705         /* Make sure the pipe isn't still relying on us */
1706         assert_pipe_disabled(dev_priv, pipe);
1707
1708         I915_WRITE(DPLL(pipe), DPLL_VGA_MODE_DIS);
1709         POSTING_READ(DPLL(pipe));
1710 }
1711
1712 static void vlv_disable_pll(struct drm_i915_private *dev_priv, enum pipe pipe)
1713 {
1714         u32 val;
1715
1716         /* Make sure the pipe isn't still relying on us */
1717         assert_pipe_disabled(dev_priv, pipe);
1718
1719         val = DPLL_INTEGRATED_REF_CLK_VLV |
1720                 DPLL_REF_CLK_ENABLE_VLV | DPLL_VGA_MODE_DIS;
1721         if (pipe != PIPE_A)
1722                 val |= DPLL_INTEGRATED_CRI_CLK_VLV;
1723
1724         I915_WRITE(DPLL(pipe), val);
1725         POSTING_READ(DPLL(pipe));
1726 }
1727
1728 static void chv_disable_pll(struct drm_i915_private *dev_priv, enum pipe pipe)
1729 {
1730         enum dpio_channel port = vlv_pipe_to_channel(pipe);
1731         u32 val;
1732
1733         /* Make sure the pipe isn't still relying on us */
1734         assert_pipe_disabled(dev_priv, pipe);
1735
1736         val = DPLL_SSC_REF_CLK_CHV |
1737                 DPLL_REF_CLK_ENABLE_VLV | DPLL_VGA_MODE_DIS;
1738         if (pipe != PIPE_A)
1739                 val |= DPLL_INTEGRATED_CRI_CLK_VLV;
1740
1741         I915_WRITE(DPLL(pipe), val);
1742         POSTING_READ(DPLL(pipe));
1743
1744         mutex_lock(&dev_priv->sb_lock);
1745
1746         /* Disable 10bit clock to display controller */
1747         val = vlv_dpio_read(dev_priv, pipe, CHV_CMN_DW14(port));
1748         val &= ~DPIO_DCLKP_EN;
1749         vlv_dpio_write(dev_priv, pipe, CHV_CMN_DW14(port), val);
1750
1751         mutex_unlock(&dev_priv->sb_lock);
1752 }
1753
1754 void vlv_wait_port_ready(struct drm_i915_private *dev_priv,
1755                          struct intel_digital_port *dport,
1756                          unsigned int expected_mask)
1757 {
1758         u32 port_mask;
1759         i915_reg_t dpll_reg;
1760
1761         switch (dport->port) {
1762         case PORT_B:
1763                 port_mask = DPLL_PORTB_READY_MASK;
1764                 dpll_reg = DPLL(0);
1765                 break;
1766         case PORT_C:
1767                 port_mask = DPLL_PORTC_READY_MASK;
1768                 dpll_reg = DPLL(0);
1769                 expected_mask <<= 4;
1770                 break;
1771         case PORT_D:
1772                 port_mask = DPLL_PORTD_READY_MASK;
1773                 dpll_reg = DPIO_PHY_STATUS;
1774                 break;
1775         default:
1776                 BUG();
1777         }
1778
1779         if (intel_wait_for_register(dev_priv,
1780                                     dpll_reg, port_mask, expected_mask,
1781                                     1000))
1782                 WARN(1, "timed out waiting for port %c ready: got 0x%x, expected 0x%x\n",
1783                      port_name(dport->port), I915_READ(dpll_reg) & port_mask, expected_mask);
1784 }
1785
1786 static void ironlake_enable_pch_transcoder(struct drm_i915_private *dev_priv,
1787                                            enum pipe pipe)
1788 {
1789         struct drm_device *dev = &dev_priv->drm;
1790         struct drm_crtc *crtc = dev_priv->pipe_to_crtc_mapping[pipe];
1791         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
1792         i915_reg_t reg;
1793         uint32_t val, pipeconf_val;
1794
1795         /* Make sure PCH DPLL is enabled */
1796         assert_shared_dpll_enabled(dev_priv, intel_crtc->config->shared_dpll);
1797
1798         /* FDI must be feeding us bits for PCH ports */
1799         assert_fdi_tx_enabled(dev_priv, pipe);
1800         assert_fdi_rx_enabled(dev_priv, pipe);
1801
1802         if (HAS_PCH_CPT(dev)) {
1803                 /* Workaround: Set the timing override bit before enabling the
1804                  * pch transcoder. */
1805                 reg = TRANS_CHICKEN2(pipe);
1806                 val = I915_READ(reg);
1807                 val |= TRANS_CHICKEN2_TIMING_OVERRIDE;
1808                 I915_WRITE(reg, val);
1809         }
1810
1811         reg = PCH_TRANSCONF(pipe);
1812         val = I915_READ(reg);
1813         pipeconf_val = I915_READ(PIPECONF(pipe));
1814
1815         if (HAS_PCH_IBX(dev_priv)) {
1816                 /*
1817                  * Make the BPC in transcoder be consistent with
1818                  * that in pipeconf reg. For HDMI we must use 8bpc
1819                  * here for both 8bpc and 12bpc.
1820                  */
1821                 val &= ~PIPECONF_BPC_MASK;
1822                 if (intel_crtc_has_type(intel_crtc->config, INTEL_OUTPUT_HDMI))
1823                         val |= PIPECONF_8BPC;
1824                 else
1825                         val |= pipeconf_val & PIPECONF_BPC_MASK;
1826         }
1827
1828         val &= ~TRANS_INTERLACE_MASK;
1829         if ((pipeconf_val & PIPECONF_INTERLACE_MASK) == PIPECONF_INTERLACED_ILK)
1830                 if (HAS_PCH_IBX(dev_priv) &&
1831                     intel_crtc_has_type(intel_crtc->config, INTEL_OUTPUT_SDVO))
1832                         val |= TRANS_LEGACY_INTERLACED_ILK;
1833                 else
1834                         val |= TRANS_INTERLACED;
1835         else
1836                 val |= TRANS_PROGRESSIVE;
1837
1838         I915_WRITE(reg, val | TRANS_ENABLE);
1839         if (intel_wait_for_register(dev_priv,
1840                                     reg, TRANS_STATE_ENABLE, TRANS_STATE_ENABLE,
1841                                     100))
1842                 DRM_ERROR("failed to enable transcoder %c\n", pipe_name(pipe));
1843 }
1844
1845 static void lpt_enable_pch_transcoder(struct drm_i915_private *dev_priv,
1846                                       enum transcoder cpu_transcoder)
1847 {
1848         u32 val, pipeconf_val;
1849
1850         /* FDI must be feeding us bits for PCH ports */
1851         assert_fdi_tx_enabled(dev_priv, (enum pipe) cpu_transcoder);
1852         assert_fdi_rx_enabled(dev_priv, TRANSCODER_A);
1853
1854         /* Workaround: set timing override bit. */
1855         val = I915_READ(TRANS_CHICKEN2(PIPE_A));
1856         val |= TRANS_CHICKEN2_TIMING_OVERRIDE;
1857         I915_WRITE(TRANS_CHICKEN2(PIPE_A), val);
1858
1859         val = TRANS_ENABLE;
1860         pipeconf_val = I915_READ(PIPECONF(cpu_transcoder));
1861
1862         if ((pipeconf_val & PIPECONF_INTERLACE_MASK_HSW) ==
1863             PIPECONF_INTERLACED_ILK)
1864                 val |= TRANS_INTERLACED;
1865         else
1866                 val |= TRANS_PROGRESSIVE;
1867
1868         I915_WRITE(LPT_TRANSCONF, val);
1869         if (intel_wait_for_register(dev_priv,
1870                                     LPT_TRANSCONF,
1871                                     TRANS_STATE_ENABLE,
1872                                     TRANS_STATE_ENABLE,
1873                                     100))
1874                 DRM_ERROR("Failed to enable PCH transcoder\n");
1875 }
1876
1877 static void ironlake_disable_pch_transcoder(struct drm_i915_private *dev_priv,
1878                                             enum pipe pipe)
1879 {
1880         struct drm_device *dev = &dev_priv->drm;
1881         i915_reg_t reg;
1882         uint32_t val;
1883
1884         /* FDI relies on the transcoder */
1885         assert_fdi_tx_disabled(dev_priv, pipe);
1886         assert_fdi_rx_disabled(dev_priv, pipe);
1887
1888         /* Ports must be off as well */
1889         assert_pch_ports_disabled(dev_priv, pipe);
1890
1891         reg = PCH_TRANSCONF(pipe);
1892         val = I915_READ(reg);
1893         val &= ~TRANS_ENABLE;
1894         I915_WRITE(reg, val);
1895         /* wait for PCH transcoder off, transcoder state */
1896         if (intel_wait_for_register(dev_priv,
1897                                     reg, TRANS_STATE_ENABLE, 0,
1898                                     50))
1899                 DRM_ERROR("failed to disable transcoder %c\n", pipe_name(pipe));
1900
1901         if (HAS_PCH_CPT(dev)) {
1902                 /* Workaround: Clear the timing override chicken bit again. */
1903                 reg = TRANS_CHICKEN2(pipe);
1904                 val = I915_READ(reg);
1905                 val &= ~TRANS_CHICKEN2_TIMING_OVERRIDE;
1906                 I915_WRITE(reg, val);
1907         }
1908 }
1909
1910 static void lpt_disable_pch_transcoder(struct drm_i915_private *dev_priv)
1911 {
1912         u32 val;
1913
1914         val = I915_READ(LPT_TRANSCONF);
1915         val &= ~TRANS_ENABLE;
1916         I915_WRITE(LPT_TRANSCONF, val);
1917         /* wait for PCH transcoder off, transcoder state */
1918         if (intel_wait_for_register(dev_priv,
1919                                     LPT_TRANSCONF, TRANS_STATE_ENABLE, 0,
1920                                     50))
1921                 DRM_ERROR("Failed to disable PCH transcoder\n");
1922
1923         /* Workaround: clear timing override bit. */
1924         val = I915_READ(TRANS_CHICKEN2(PIPE_A));
1925         val &= ~TRANS_CHICKEN2_TIMING_OVERRIDE;
1926         I915_WRITE(TRANS_CHICKEN2(PIPE_A), val);
1927 }
1928
1929 /**
1930  * intel_enable_pipe - enable a pipe, asserting requirements
1931  * @crtc: crtc responsible for the pipe
1932  *
1933  * Enable @crtc's pipe, making sure that various hardware specific requirements
1934  * are met, if applicable, e.g. PLL enabled, LVDS pairs enabled, etc.
1935  */
1936 static void intel_enable_pipe(struct intel_crtc *crtc)
1937 {
1938         struct drm_device *dev = crtc->base.dev;
1939         struct drm_i915_private *dev_priv = to_i915(dev);
1940         enum pipe pipe = crtc->pipe;
1941         enum transcoder cpu_transcoder = crtc->config->cpu_transcoder;
1942         enum pipe pch_transcoder;
1943         i915_reg_t reg;
1944         u32 val;
1945
1946         DRM_DEBUG_KMS("enabling pipe %c\n", pipe_name(pipe));
1947
1948         assert_planes_disabled(dev_priv, pipe);
1949         assert_cursor_disabled(dev_priv, pipe);
1950         assert_sprites_disabled(dev_priv, pipe);
1951
1952         if (HAS_PCH_LPT(dev_priv))
1953                 pch_transcoder = TRANSCODER_A;
1954         else
1955                 pch_transcoder = pipe;
1956
1957         /*
1958          * A pipe without a PLL won't actually be able to drive bits from
1959          * a plane.  On ILK+ the pipe PLLs are integrated, so we don't
1960          * need the check.
1961          */
1962         if (HAS_GMCH_DISPLAY(dev_priv)) {
1963                 if (intel_crtc_has_type(crtc->config, INTEL_OUTPUT_DSI))
1964                         assert_dsi_pll_enabled(dev_priv);
1965                 else
1966                         assert_pll_enabled(dev_priv, pipe);
1967         } else {
1968                 if (crtc->config->has_pch_encoder) {
1969                         /* if driving the PCH, we need FDI enabled */
1970                         assert_fdi_rx_pll_enabled(dev_priv, pch_transcoder);
1971                         assert_fdi_tx_pll_enabled(dev_priv,
1972                                                   (enum pipe) cpu_transcoder);
1973                 }
1974                 /* FIXME: assert CPU port conditions for SNB+ */
1975         }
1976
1977         reg = PIPECONF(cpu_transcoder);
1978         val = I915_READ(reg);
1979         if (val & PIPECONF_ENABLE) {
1980                 WARN_ON(!((pipe == PIPE_A && dev_priv->quirks & QUIRK_PIPEA_FORCE) ||
1981                           (pipe == PIPE_B && dev_priv->quirks & QUIRK_PIPEB_FORCE)));
1982                 return;
1983         }
1984
1985         I915_WRITE(reg, val | PIPECONF_ENABLE);
1986         POSTING_READ(reg);
1987
1988         /*
1989          * Until the pipe starts DSL will read as 0, which would cause
1990          * an apparent vblank timestamp jump, which messes up also the
1991          * frame count when it's derived from the timestamps. So let's
1992          * wait for the pipe to start properly before we call
1993          * drm_crtc_vblank_on()
1994          */
1995         if (dev->max_vblank_count == 0 &&
1996             wait_for(intel_get_crtc_scanline(crtc) != crtc->scanline_offset, 50))
1997                 DRM_ERROR("pipe %c didn't start\n", pipe_name(pipe));
1998 }
1999
2000 /**
2001  * intel_disable_pipe - disable a pipe, asserting requirements
2002  * @crtc: crtc whose pipes is to be disabled
2003  *
2004  * Disable the pipe of @crtc, making sure that various hardware
2005  * specific requirements are met, if applicable, e.g. plane
2006  * disabled, panel fitter off, etc.
2007  *
2008  * Will wait until the pipe has shut down before returning.
2009  */
2010 static void intel_disable_pipe(struct intel_crtc *crtc)
2011 {
2012         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
2013         enum transcoder cpu_transcoder = crtc->config->cpu_transcoder;
2014         enum pipe pipe = crtc->pipe;
2015         i915_reg_t reg;
2016         u32 val;
2017
2018         DRM_DEBUG_KMS("disabling pipe %c\n", pipe_name(pipe));
2019
2020         /*
2021          * Make sure planes won't keep trying to pump pixels to us,
2022          * or we might hang the display.
2023          */
2024         assert_planes_disabled(dev_priv, pipe);
2025         assert_cursor_disabled(dev_priv, pipe);
2026         assert_sprites_disabled(dev_priv, pipe);
2027
2028         reg = PIPECONF(cpu_transcoder);
2029         val = I915_READ(reg);
2030         if ((val & PIPECONF_ENABLE) == 0)
2031                 return;
2032
2033         /*
2034          * Double wide has implications for planes
2035          * so best keep it disabled when not needed.
2036          */
2037         if (crtc->config->double_wide)
2038                 val &= ~PIPECONF_DOUBLE_WIDE;
2039
2040         /* Don't disable pipe or pipe PLLs if needed */
2041         if (!(pipe == PIPE_A && dev_priv->quirks & QUIRK_PIPEA_FORCE) &&
2042             !(pipe == PIPE_B && dev_priv->quirks & QUIRK_PIPEB_FORCE))
2043                 val &= ~PIPECONF_ENABLE;
2044
2045         I915_WRITE(reg, val);
2046         if ((val & PIPECONF_ENABLE) == 0)
2047                 intel_wait_for_pipe_off(crtc);
2048 }
2049
2050 static unsigned int intel_tile_size(const struct drm_i915_private *dev_priv)
2051 {
2052         return IS_GEN2(dev_priv) ? 2048 : 4096;
2053 }
2054
2055 static unsigned int intel_tile_width_bytes(const struct drm_i915_private *dev_priv,
2056                                            uint64_t fb_modifier, unsigned int cpp)
2057 {
2058         switch (fb_modifier) {
2059         case DRM_FORMAT_MOD_NONE:
2060                 return cpp;
2061         case I915_FORMAT_MOD_X_TILED:
2062                 if (IS_GEN2(dev_priv))
2063                         return 128;
2064                 else
2065                         return 512;
2066         case I915_FORMAT_MOD_Y_TILED:
2067                 if (IS_GEN2(dev_priv) || HAS_128_BYTE_Y_TILING(dev_priv))
2068                         return 128;
2069                 else
2070                         return 512;
2071         case I915_FORMAT_MOD_Yf_TILED:
2072                 switch (cpp) {
2073                 case 1:
2074                         return 64;
2075                 case 2:
2076                 case 4:
2077                         return 128;
2078                 case 8:
2079                 case 16:
2080                         return 256;
2081                 default:
2082                         MISSING_CASE(cpp);
2083                         return cpp;
2084                 }
2085                 break;
2086         default:
2087                 MISSING_CASE(fb_modifier);
2088                 return cpp;
2089         }
2090 }
2091
2092 unsigned int intel_tile_height(const struct drm_i915_private *dev_priv,
2093                                uint64_t fb_modifier, unsigned int cpp)
2094 {
2095         if (fb_modifier == DRM_FORMAT_MOD_NONE)
2096                 return 1;
2097         else
2098                 return intel_tile_size(dev_priv) /
2099                         intel_tile_width_bytes(dev_priv, fb_modifier, cpp);
2100 }
2101
2102 /* Return the tile dimensions in pixel units */
2103 static void intel_tile_dims(const struct drm_i915_private *dev_priv,
2104                             unsigned int *tile_width,
2105                             unsigned int *tile_height,
2106                             uint64_t fb_modifier,
2107                             unsigned int cpp)
2108 {
2109         unsigned int tile_width_bytes =
2110                 intel_tile_width_bytes(dev_priv, fb_modifier, cpp);
2111
2112         *tile_width = tile_width_bytes / cpp;
2113         *tile_height = intel_tile_size(dev_priv) / tile_width_bytes;
2114 }
2115
2116 unsigned int
2117 intel_fb_align_height(struct drm_device *dev, unsigned int height,
2118                       uint32_t pixel_format, uint64_t fb_modifier)
2119 {
2120         unsigned int cpp = drm_format_plane_cpp(pixel_format, 0);
2121         unsigned int tile_height = intel_tile_height(to_i915(dev), fb_modifier, cpp);
2122
2123         return ALIGN(height, tile_height);
2124 }
2125
2126 unsigned int intel_rotation_info_size(const struct intel_rotation_info *rot_info)
2127 {
2128         unsigned int size = 0;
2129         int i;
2130
2131         for (i = 0 ; i < ARRAY_SIZE(rot_info->plane); i++)
2132                 size += rot_info->plane[i].width * rot_info->plane[i].height;
2133
2134         return size;
2135 }
2136
2137 static void
2138 intel_fill_fb_ggtt_view(struct i915_ggtt_view *view,
2139                         const struct drm_framebuffer *fb,
2140                         unsigned int rotation)
2141 {
2142         if (intel_rotation_90_or_270(rotation)) {
2143                 *view = i915_ggtt_view_rotated;
2144                 view->params.rotated = to_intel_framebuffer(fb)->rot_info;
2145         } else {
2146                 *view = i915_ggtt_view_normal;
2147         }
2148 }
2149
2150 static void
2151 intel_fill_fb_info(struct drm_i915_private *dev_priv,
2152                    struct drm_framebuffer *fb)
2153 {
2154         struct intel_rotation_info *info = &to_intel_framebuffer(fb)->rot_info;
2155         unsigned int tile_size, tile_width, tile_height, cpp;
2156
2157         tile_size = intel_tile_size(dev_priv);
2158
2159         cpp = drm_format_plane_cpp(fb->pixel_format, 0);
2160         intel_tile_dims(dev_priv, &tile_width, &tile_height,
2161                         fb->modifier[0], cpp);
2162
2163         info->plane[0].width = DIV_ROUND_UP(fb->pitches[0], tile_width * cpp);
2164         info->plane[0].height = DIV_ROUND_UP(fb->height, tile_height);
2165
2166         if (info->pixel_format == DRM_FORMAT_NV12) {
2167                 cpp = drm_format_plane_cpp(fb->pixel_format, 1);
2168                 intel_tile_dims(dev_priv, &tile_width, &tile_height,
2169                                 fb->modifier[1], cpp);
2170
2171                 info->uv_offset = fb->offsets[1];
2172                 info->plane[1].width = DIV_ROUND_UP(fb->pitches[1], tile_width * cpp);
2173                 info->plane[1].height = DIV_ROUND_UP(fb->height / 2, tile_height);
2174         }
2175 }
2176
2177 static unsigned int intel_linear_alignment(const struct drm_i915_private *dev_priv)
2178 {
2179         if (INTEL_INFO(dev_priv)->gen >= 9)
2180                 return 256 * 1024;
2181         else if (IS_BROADWATER(dev_priv) || IS_CRESTLINE(dev_priv) ||
2182                  IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv))
2183                 return 128 * 1024;
2184         else if (INTEL_INFO(dev_priv)->gen >= 4)
2185                 return 4 * 1024;
2186         else
2187                 return 0;
2188 }
2189
2190 static unsigned int intel_surf_alignment(const struct drm_i915_private *dev_priv,
2191                                          uint64_t fb_modifier)
2192 {
2193         switch (fb_modifier) {
2194         case DRM_FORMAT_MOD_NONE:
2195                 return intel_linear_alignment(dev_priv);
2196         case I915_FORMAT_MOD_X_TILED:
2197                 if (INTEL_INFO(dev_priv)->gen >= 9)
2198                         return 256 * 1024;
2199                 return 0;
2200         case I915_FORMAT_MOD_Y_TILED:
2201         case I915_FORMAT_MOD_Yf_TILED:
2202                 return 1 * 1024 * 1024;
2203         default:
2204                 MISSING_CASE(fb_modifier);
2205                 return 0;
2206         }
2207 }
2208
2209 int
2210 intel_pin_and_fence_fb_obj(struct drm_framebuffer *fb,
2211                            unsigned int rotation)
2212 {
2213         struct drm_device *dev = fb->dev;
2214         struct drm_i915_private *dev_priv = to_i915(dev);
2215         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
2216         struct i915_ggtt_view view;
2217         u32 alignment;
2218         int ret;
2219
2220         WARN_ON(!mutex_is_locked(&dev->struct_mutex));
2221
2222         alignment = intel_surf_alignment(dev_priv, fb->modifier[0]);
2223
2224         intel_fill_fb_ggtt_view(&view, fb, rotation);
2225
2226         /* Note that the w/a also requires 64 PTE of padding following the
2227          * bo. We currently fill all unused PTE with the shadow page and so
2228          * we should always have valid PTE following the scanout preventing
2229          * the VT-d warning.
2230          */
2231         if (intel_scanout_needs_vtd_wa(dev_priv) && alignment < 256 * 1024)
2232                 alignment = 256 * 1024;
2233
2234         /*
2235          * Global gtt pte registers are special registers which actually forward
2236          * writes to a chunk of system memory. Which means that there is no risk
2237          * that the register values disappear as soon as we call
2238          * intel_runtime_pm_put(), so it is correct to wrap only the
2239          * pin/unpin/fence and not more.
2240          */
2241         intel_runtime_pm_get(dev_priv);
2242
2243         ret = i915_gem_object_pin_to_display_plane(obj, alignment,
2244                                                    &view);
2245         if (ret)
2246                 goto err_pm;
2247
2248         /* Install a fence for tiled scan-out. Pre-i965 always needs a
2249          * fence, whereas 965+ only requires a fence if using
2250          * framebuffer compression.  For simplicity, we always install
2251          * a fence as the cost is not that onerous.
2252          */
2253         if (view.type == I915_GGTT_VIEW_NORMAL) {
2254                 ret = i915_gem_object_get_fence(obj);
2255                 if (ret == -EDEADLK) {
2256                         /*
2257                          * -EDEADLK means there are no free fences
2258                          * no pending flips.
2259                          *
2260                          * This is propagated to atomic, but it uses
2261                          * -EDEADLK to force a locking recovery, so
2262                          * change the returned error to -EBUSY.
2263                          */
2264                         ret = -EBUSY;
2265                         goto err_unpin;
2266                 } else if (ret)
2267                         goto err_unpin;
2268
2269                 i915_gem_object_pin_fence(obj);
2270         }
2271
2272         intel_runtime_pm_put(dev_priv);
2273         return 0;
2274
2275 err_unpin:
2276         i915_gem_object_unpin_from_display_plane(obj, &view);
2277 err_pm:
2278         intel_runtime_pm_put(dev_priv);
2279         return ret;
2280 }
2281
2282 void intel_unpin_fb_obj(struct drm_framebuffer *fb, unsigned int rotation)
2283 {
2284         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
2285         struct i915_ggtt_view view;
2286
2287         WARN_ON(!mutex_is_locked(&obj->base.dev->struct_mutex));
2288
2289         intel_fill_fb_ggtt_view(&view, fb, rotation);
2290
2291         if (view.type == I915_GGTT_VIEW_NORMAL)
2292                 i915_gem_object_unpin_fence(obj);
2293
2294         i915_gem_object_unpin_from_display_plane(obj, &view);
2295 }
2296
2297 /*
2298  * Adjust the tile offset by moving the difference into
2299  * the x/y offsets.
2300  *
2301  * Input tile dimensions and pitch must already be
2302  * rotated to match x and y, and in pixel units.
2303  */
2304 static u32 intel_adjust_tile_offset(int *x, int *y,
2305                                     unsigned int tile_width,
2306                                     unsigned int tile_height,
2307                                     unsigned int tile_size,
2308                                     unsigned int pitch_tiles,
2309                                     u32 old_offset,
2310                                     u32 new_offset)
2311 {
2312         unsigned int tiles;
2313
2314         WARN_ON(old_offset & (tile_size - 1));
2315         WARN_ON(new_offset & (tile_size - 1));
2316         WARN_ON(new_offset > old_offset);
2317
2318         tiles = (old_offset - new_offset) / tile_size;
2319
2320         *y += tiles / pitch_tiles * tile_height;
2321         *x += tiles % pitch_tiles * tile_width;
2322
2323         return new_offset;
2324 }
2325
2326 /*
2327  * Computes the linear offset to the base tile and adjusts
2328  * x, y. bytes per pixel is assumed to be a power-of-two.
2329  *
2330  * In the 90/270 rotated case, x and y are assumed
2331  * to be already rotated to match the rotated GTT view, and
2332  * pitch is the tile_height aligned framebuffer height.
2333  */
2334 u32 intel_compute_tile_offset(int *x, int *y,
2335                               const struct drm_framebuffer *fb, int plane,
2336                               unsigned int pitch,
2337                               unsigned int rotation)
2338 {
2339         const struct drm_i915_private *dev_priv = to_i915(fb->dev);
2340         uint64_t fb_modifier = fb->modifier[plane];
2341         unsigned int cpp = drm_format_plane_cpp(fb->pixel_format, plane);
2342         u32 offset, offset_aligned, alignment;
2343
2344         alignment = intel_surf_alignment(dev_priv, fb_modifier);
2345         if (alignment)
2346                 alignment--;
2347
2348         if (fb_modifier != DRM_FORMAT_MOD_NONE) {
2349                 unsigned int tile_size, tile_width, tile_height;
2350                 unsigned int tile_rows, tiles, pitch_tiles;
2351
2352                 tile_size = intel_tile_size(dev_priv);
2353                 intel_tile_dims(dev_priv, &tile_width, &tile_height,
2354                                 fb_modifier, cpp);
2355
2356                 if (intel_rotation_90_or_270(rotation)) {
2357                         pitch_tiles = pitch / tile_height;
2358                         swap(tile_width, tile_height);
2359                 } else {
2360                         pitch_tiles = pitch / (tile_width * cpp);
2361                 }
2362
2363                 tile_rows = *y / tile_height;
2364                 *y %= tile_height;
2365
2366                 tiles = *x / tile_width;
2367                 *x %= tile_width;
2368
2369                 offset = (tile_rows * pitch_tiles + tiles) * tile_size;
2370                 offset_aligned = offset & ~alignment;
2371
2372                 intel_adjust_tile_offset(x, y, tile_width, tile_height,
2373                                          tile_size, pitch_tiles,
2374                                          offset, offset_aligned);
2375         } else {
2376                 offset = *y * pitch + *x * cpp;
2377                 offset_aligned = offset & ~alignment;
2378
2379                 *y = (offset & alignment) / pitch;
2380                 *x = ((offset & alignment) - *y * pitch) / cpp;
2381         }
2382
2383         return offset_aligned;
2384 }
2385
2386 static int i9xx_format_to_fourcc(int format)
2387 {
2388         switch (format) {
2389         case DISPPLANE_8BPP:
2390                 return DRM_FORMAT_C8;
2391         case DISPPLANE_BGRX555:
2392                 return DRM_FORMAT_XRGB1555;
2393         case DISPPLANE_BGRX565:
2394                 return DRM_FORMAT_RGB565;
2395         default:
2396         case DISPPLANE_BGRX888:
2397                 return DRM_FORMAT_XRGB8888;
2398         case DISPPLANE_RGBX888:
2399                 return DRM_FORMAT_XBGR8888;
2400         case DISPPLANE_BGRX101010:
2401                 return DRM_FORMAT_XRGB2101010;
2402         case DISPPLANE_RGBX101010:
2403                 return DRM_FORMAT_XBGR2101010;
2404         }
2405 }
2406
2407 static int skl_format_to_fourcc(int format, bool rgb_order, bool alpha)
2408 {
2409         switch (format) {
2410         case PLANE_CTL_FORMAT_RGB_565:
2411                 return DRM_FORMAT_RGB565;
2412         default:
2413         case PLANE_CTL_FORMAT_XRGB_8888:
2414                 if (rgb_order) {
2415                         if (alpha)
2416                                 return DRM_FORMAT_ABGR8888;
2417                         else
2418                                 return DRM_FORMAT_XBGR8888;
2419                 } else {
2420                         if (alpha)
2421                                 return DRM_FORMAT_ARGB8888;
2422                         else
2423                                 return DRM_FORMAT_XRGB8888;
2424                 }
2425         case PLANE_CTL_FORMAT_XRGB_2101010:
2426                 if (rgb_order)
2427                         return DRM_FORMAT_XBGR2101010;
2428                 else
2429                         return DRM_FORMAT_XRGB2101010;
2430         }
2431 }
2432
2433 static bool
2434 intel_alloc_initial_plane_obj(struct intel_crtc *crtc,
2435                               struct intel_initial_plane_config *plane_config)
2436 {
2437         struct drm_device *dev = crtc->base.dev;
2438         struct drm_i915_private *dev_priv = to_i915(dev);
2439         struct i915_ggtt *ggtt = &dev_priv->ggtt;
2440         struct drm_i915_gem_object *obj = NULL;
2441         struct drm_mode_fb_cmd2 mode_cmd = { 0 };
2442         struct drm_framebuffer *fb = &plane_config->fb->base;
2443         u32 base_aligned = round_down(plane_config->base, PAGE_SIZE);
2444         u32 size_aligned = round_up(plane_config->base + plane_config->size,
2445                                     PAGE_SIZE);
2446
2447         size_aligned -= base_aligned;
2448
2449         if (plane_config->size == 0)
2450                 return false;
2451
2452         /* If the FB is too big, just don't use it since fbdev is not very
2453          * important and we should probably use that space with FBC or other
2454          * features. */
2455         if (size_aligned * 2 > ggtt->stolen_usable_size)
2456                 return false;
2457
2458         mutex_lock(&dev->struct_mutex);
2459
2460         obj = i915_gem_object_create_stolen_for_preallocated(dev,
2461                                                              base_aligned,
2462                                                              base_aligned,
2463                                                              size_aligned);
2464         if (!obj) {
2465                 mutex_unlock(&dev->struct_mutex);
2466                 return false;
2467         }
2468
2469         if (plane_config->tiling == I915_TILING_X)
2470                 obj->tiling_and_stride = fb->pitches[0] | I915_TILING_X;
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         i915_gem_object_put(obj);
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 (i915_gem_object_is_tiled(obj))
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         atomic_or(to_intel_plane(primary)->frontbuffer_bit,
2604                   &obj->frontbuffer_bits);
2605 }
2606
2607 static void i9xx_update_primary_plane(struct drm_plane *primary,
2608                                       const struct intel_crtc_state *crtc_state,
2609                                       const struct intel_plane_state *plane_state)
2610 {
2611         struct drm_device *dev = primary->dev;
2612         struct drm_i915_private *dev_priv = to_i915(dev);
2613         struct intel_crtc *intel_crtc = to_intel_crtc(crtc_state->base.crtc);
2614         struct drm_framebuffer *fb = plane_state->base.fb;
2615         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
2616         int plane = intel_crtc->plane;
2617         u32 linear_offset;
2618         u32 dspcntr;
2619         i915_reg_t reg = DSPCNTR(plane);
2620         unsigned int rotation = plane_state->base.rotation;
2621         int cpp = drm_format_plane_cpp(fb->pixel_format, 0);
2622         int x = plane_state->src.x1 >> 16;
2623         int y = plane_state->src.y1 >> 16;
2624
2625         dspcntr = DISPPLANE_GAMMA_ENABLE;
2626
2627         dspcntr |= DISPLAY_PLANE_ENABLE;
2628
2629         if (INTEL_INFO(dev)->gen < 4) {
2630                 if (intel_crtc->pipe == PIPE_B)
2631                         dspcntr |= DISPPLANE_SEL_PIPE_B;
2632
2633                 /* pipesrc and dspsize control the size that is scaled from,
2634                  * which should always be the user's requested size.
2635                  */
2636                 I915_WRITE(DSPSIZE(plane),
2637                            ((crtc_state->pipe_src_h - 1) << 16) |
2638                            (crtc_state->pipe_src_w - 1));
2639                 I915_WRITE(DSPPOS(plane), 0);
2640         } else if (IS_CHERRYVIEW(dev) && plane == PLANE_B) {
2641                 I915_WRITE(PRIMSIZE(plane),
2642                            ((crtc_state->pipe_src_h - 1) << 16) |
2643                            (crtc_state->pipe_src_w - 1));
2644                 I915_WRITE(PRIMPOS(plane), 0);
2645                 I915_WRITE(PRIMCNSTALPHA(plane), 0);
2646         }
2647
2648         switch (fb->pixel_format) {
2649         case DRM_FORMAT_C8:
2650                 dspcntr |= DISPPLANE_8BPP;
2651                 break;
2652         case DRM_FORMAT_XRGB1555:
2653                 dspcntr |= DISPPLANE_BGRX555;
2654                 break;
2655         case DRM_FORMAT_RGB565:
2656                 dspcntr |= DISPPLANE_BGRX565;
2657                 break;
2658         case DRM_FORMAT_XRGB8888:
2659                 dspcntr |= DISPPLANE_BGRX888;
2660                 break;
2661         case DRM_FORMAT_XBGR8888:
2662                 dspcntr |= DISPPLANE_RGBX888;
2663                 break;
2664         case DRM_FORMAT_XRGB2101010:
2665                 dspcntr |= DISPPLANE_BGRX101010;
2666                 break;
2667         case DRM_FORMAT_XBGR2101010:
2668                 dspcntr |= DISPPLANE_RGBX101010;
2669                 break;
2670         default:
2671                 BUG();
2672         }
2673
2674         if (INTEL_INFO(dev)->gen >= 4 && i915_gem_object_is_tiled(obj))
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 (i915_gem_object_is_tiled(obj))
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 static bool gpu_reset_clobbers_display(struct drm_i915_private *dev_priv)
3139 {
3140         return INTEL_GEN(dev_priv) < 5 && !IS_G4X(dev_priv);
3141 }
3142
3143 void intel_prepare_reset(struct drm_i915_private *dev_priv)
3144 {
3145         struct drm_device *dev = &dev_priv->drm;
3146         struct drm_modeset_acquire_ctx *ctx = &dev_priv->reset_ctx;
3147         struct drm_atomic_state *state;
3148         int ret;
3149
3150         /* no reset support for gen2 */
3151         if (IS_GEN2(dev_priv))
3152                 return;
3153
3154         /*
3155          * Need mode_config.mutex so that we don't
3156          * trample ongoing ->detect() and whatnot.
3157          */
3158         mutex_lock(&dev->mode_config.mutex);
3159         drm_modeset_acquire_init(ctx, 0);
3160         while (1) {
3161                 ret = drm_modeset_lock_all_ctx(dev, ctx);
3162                 if (ret != -EDEADLK)
3163                         break;
3164
3165                 drm_modeset_backoff(ctx);
3166         }
3167
3168         /* reset doesn't touch the display, but flips might get nuked anyway, */
3169         if (!i915.force_reset_modeset_test &&
3170             !gpu_reset_clobbers_display(dev_priv))
3171                 return;
3172
3173         /*
3174          * Disabling the crtcs gracefully seems nicer. Also the
3175          * g33 docs say we should at least disable all the planes.
3176          */
3177         state = drm_atomic_helper_duplicate_state(dev, ctx);
3178         if (IS_ERR(state)) {
3179                 ret = PTR_ERR(state);
3180                 state = NULL;
3181                 DRM_ERROR("Duplicating state failed with %i\n", ret);
3182                 goto err;
3183         }
3184
3185         ret = drm_atomic_helper_disable_all(dev, ctx);
3186         if (ret) {
3187                 DRM_ERROR("Suspending crtc's failed with %i\n", ret);
3188                 goto err;
3189         }
3190
3191         dev_priv->modeset_restore_state = state;
3192         state->acquire_ctx = ctx;
3193         return;
3194
3195 err:
3196         drm_atomic_state_free(state);
3197 }
3198
3199 void intel_finish_reset(struct drm_i915_private *dev_priv)
3200 {
3201         struct drm_device *dev = &dev_priv->drm;
3202         struct drm_modeset_acquire_ctx *ctx = &dev_priv->reset_ctx;
3203         struct drm_atomic_state *state = dev_priv->modeset_restore_state;
3204         int ret;
3205
3206         /*
3207          * Flips in the rings will be nuked by the reset,
3208          * so complete all pending flips so that user space
3209          * will get its events and not get stuck.
3210          */
3211         intel_complete_page_flips(dev_priv);
3212
3213         /* no reset support for gen2 */
3214         if (IS_GEN2(dev_priv))
3215                 return;
3216
3217         dev_priv->modeset_restore_state = NULL;
3218
3219         /* reset doesn't touch the display */
3220         if (!gpu_reset_clobbers_display(dev_priv)) {
3221                 if (!state) {
3222                         /*
3223                          * Flips in the rings have been nuked by the reset,
3224                          * so update the base address of all primary
3225                          * planes to the the last fb to make sure we're
3226                          * showing the correct fb after a reset.
3227                          *
3228                          * FIXME: Atomic will make this obsolete since we won't schedule
3229                          * CS-based flips (which might get lost in gpu resets) any more.
3230                          */
3231                         intel_update_primary_planes(dev);
3232                 } else {
3233                         ret = __intel_display_resume(dev, state);
3234                         if (ret)
3235                                 DRM_ERROR("Restoring old state failed with %i\n", ret);
3236                 }
3237         } else {
3238                 /*
3239                  * The display has been reset as well,
3240                  * so need a full re-initialization.
3241                  */
3242                 intel_runtime_pm_disable_interrupts(dev_priv);
3243                 intel_runtime_pm_enable_interrupts(dev_priv);
3244
3245                 intel_modeset_init_hw(dev);
3246
3247                 spin_lock_irq(&dev_priv->irq_lock);
3248                 if (dev_priv->display.hpd_irq_setup)
3249                         dev_priv->display.hpd_irq_setup(dev_priv);
3250                 spin_unlock_irq(&dev_priv->irq_lock);
3251
3252                 ret = __intel_display_resume(dev, state);
3253                 if (ret)
3254                         DRM_ERROR("Restoring old state failed with %i\n", ret);
3255
3256                 intel_hpd_init(dev_priv);
3257         }
3258
3259         drm_modeset_drop_locks(ctx);
3260         drm_modeset_acquire_fini(ctx);
3261         mutex_unlock(&dev->mode_config.mutex);
3262 }
3263
3264 static bool intel_crtc_has_pending_flip(struct drm_crtc *crtc)
3265 {
3266         struct drm_device *dev = crtc->dev;
3267         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
3268         unsigned reset_counter;
3269         bool pending;
3270
3271         reset_counter = i915_reset_counter(&to_i915(dev)->gpu_error);
3272         if (intel_crtc->reset_counter != reset_counter)
3273                 return false;
3274
3275         spin_lock_irq(&dev->event_lock);
3276         pending = to_intel_crtc(crtc)->flip_work != NULL;
3277         spin_unlock_irq(&dev->event_lock);
3278
3279         return pending;
3280 }
3281
3282 static void intel_update_pipe_config(struct intel_crtc *crtc,
3283                                      struct intel_crtc_state *old_crtc_state)
3284 {
3285         struct drm_device *dev = crtc->base.dev;
3286         struct drm_i915_private *dev_priv = to_i915(dev);
3287         struct intel_crtc_state *pipe_config =
3288                 to_intel_crtc_state(crtc->base.state);
3289
3290         /* drm_atomic_helper_update_legacy_modeset_state might not be called. */
3291         crtc->base.mode = crtc->base.state->mode;
3292
3293         DRM_DEBUG_KMS("Updating pipe size %ix%i -> %ix%i\n",
3294                       old_crtc_state->pipe_src_w, old_crtc_state->pipe_src_h,
3295                       pipe_config->pipe_src_w, pipe_config->pipe_src_h);
3296
3297         /*
3298          * Update pipe size and adjust fitter if needed: the reason for this is
3299          * that in compute_mode_changes we check the native mode (not the pfit
3300          * mode) to see if we can flip rather than do a full mode set. In the
3301          * fastboot case, we'll flip, but if we don't update the pipesrc and
3302          * pfit state, we'll end up with a big fb scanned out into the wrong
3303          * sized surface.
3304          */
3305
3306         I915_WRITE(PIPESRC(crtc->pipe),
3307                    ((pipe_config->pipe_src_w - 1) << 16) |
3308                    (pipe_config->pipe_src_h - 1));
3309
3310         /* on skylake this is done by detaching scalers */
3311         if (INTEL_INFO(dev)->gen >= 9) {
3312                 skl_detach_scalers(crtc);
3313
3314                 if (pipe_config->pch_pfit.enabled)
3315                         skylake_pfit_enable(crtc);
3316         } else if (HAS_PCH_SPLIT(dev)) {
3317                 if (pipe_config->pch_pfit.enabled)
3318                         ironlake_pfit_enable(crtc);
3319                 else if (old_crtc_state->pch_pfit.enabled)
3320                         ironlake_pfit_disable(crtc, true);
3321         }
3322 }
3323
3324 static void intel_fdi_normal_train(struct drm_crtc *crtc)
3325 {
3326         struct drm_device *dev = crtc->dev;
3327         struct drm_i915_private *dev_priv = to_i915(dev);
3328         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
3329         int pipe = intel_crtc->pipe;
3330         i915_reg_t reg;
3331         u32 temp;
3332
3333         /* enable normal train */
3334         reg = FDI_TX_CTL(pipe);
3335         temp = I915_READ(reg);
3336         if (IS_IVYBRIDGE(dev)) {
3337                 temp &= ~FDI_LINK_TRAIN_NONE_IVB;
3338                 temp |= FDI_LINK_TRAIN_NONE_IVB | FDI_TX_ENHANCE_FRAME_ENABLE;
3339         } else {
3340                 temp &= ~FDI_LINK_TRAIN_NONE;
3341                 temp |= FDI_LINK_TRAIN_NONE | FDI_TX_ENHANCE_FRAME_ENABLE;
3342         }
3343         I915_WRITE(reg, temp);
3344
3345         reg = FDI_RX_CTL(pipe);
3346         temp = I915_READ(reg);
3347         if (HAS_PCH_CPT(dev)) {
3348                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
3349                 temp |= FDI_LINK_TRAIN_NORMAL_CPT;
3350         } else {
3351                 temp &= ~FDI_LINK_TRAIN_NONE;
3352                 temp |= FDI_LINK_TRAIN_NONE;
3353         }
3354         I915_WRITE(reg, temp | FDI_RX_ENHANCE_FRAME_ENABLE);
3355
3356         /* wait one idle pattern time */
3357         POSTING_READ(reg);
3358         udelay(1000);
3359
3360         /* IVB wants error correction enabled */
3361         if (IS_IVYBRIDGE(dev))
3362                 I915_WRITE(reg, I915_READ(reg) | FDI_FS_ERRC_ENABLE |
3363                            FDI_FE_ERRC_ENABLE);
3364 }
3365
3366 /* The FDI link training functions for ILK/Ibexpeak. */
3367 static void ironlake_fdi_link_train(struct drm_crtc *crtc)
3368 {
3369         struct drm_device *dev = crtc->dev;
3370         struct drm_i915_private *dev_priv = to_i915(dev);
3371         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
3372         int pipe = intel_crtc->pipe;
3373         i915_reg_t reg;
3374         u32 temp, tries;
3375
3376         /* FDI needs bits from pipe first */
3377         assert_pipe_enabled(dev_priv, pipe);
3378
3379         /* Train 1: umask FDI RX Interrupt symbol_lock and bit_lock bit
3380            for train result */
3381         reg = FDI_RX_IMR(pipe);
3382         temp = I915_READ(reg);
3383         temp &= ~FDI_RX_SYMBOL_LOCK;
3384         temp &= ~FDI_RX_BIT_LOCK;
3385         I915_WRITE(reg, temp);
3386         I915_READ(reg);
3387         udelay(150);
3388
3389         /* enable CPU FDI TX and PCH FDI RX */
3390         reg = FDI_TX_CTL(pipe);
3391         temp = I915_READ(reg);
3392         temp &= ~FDI_DP_PORT_WIDTH_MASK;
3393         temp |= FDI_DP_PORT_WIDTH(intel_crtc->config->fdi_lanes);
3394         temp &= ~FDI_LINK_TRAIN_NONE;
3395         temp |= FDI_LINK_TRAIN_PATTERN_1;
3396         I915_WRITE(reg, temp | FDI_TX_ENABLE);
3397
3398         reg = FDI_RX_CTL(pipe);
3399         temp = I915_READ(reg);
3400         temp &= ~FDI_LINK_TRAIN_NONE;
3401         temp |= FDI_LINK_TRAIN_PATTERN_1;
3402         I915_WRITE(reg, temp | FDI_RX_ENABLE);
3403
3404         POSTING_READ(reg);
3405         udelay(150);
3406
3407         /* Ironlake workaround, enable clock pointer after FDI enable*/
3408         I915_WRITE(FDI_RX_CHICKEN(pipe), FDI_RX_PHASE_SYNC_POINTER_OVR);
3409         I915_WRITE(FDI_RX_CHICKEN(pipe), FDI_RX_PHASE_SYNC_POINTER_OVR |
3410                    FDI_RX_PHASE_SYNC_POINTER_EN);
3411
3412         reg = FDI_RX_IIR(pipe);
3413         for (tries = 0; tries < 5; tries++) {
3414                 temp = I915_READ(reg);
3415                 DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
3416
3417                 if ((temp & FDI_RX_BIT_LOCK)) {
3418                         DRM_DEBUG_KMS("FDI train 1 done.\n");
3419                         I915_WRITE(reg, temp | FDI_RX_BIT_LOCK);
3420                         break;
3421                 }
3422         }
3423         if (tries == 5)
3424                 DRM_ERROR("FDI train 1 fail!\n");
3425
3426         /* Train 2 */
3427         reg = FDI_TX_CTL(pipe);
3428         temp = I915_READ(reg);
3429         temp &= ~FDI_LINK_TRAIN_NONE;
3430         temp |= FDI_LINK_TRAIN_PATTERN_2;
3431         I915_WRITE(reg, temp);
3432
3433         reg = FDI_RX_CTL(pipe);
3434         temp = I915_READ(reg);
3435         temp &= ~FDI_LINK_TRAIN_NONE;
3436         temp |= FDI_LINK_TRAIN_PATTERN_2;
3437         I915_WRITE(reg, temp);
3438
3439         POSTING_READ(reg);
3440         udelay(150);
3441
3442         reg = FDI_RX_IIR(pipe);
3443         for (tries = 0; tries < 5; tries++) {
3444                 temp = I915_READ(reg);
3445                 DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
3446
3447                 if (temp & FDI_RX_SYMBOL_LOCK) {
3448                         I915_WRITE(reg, temp | FDI_RX_SYMBOL_LOCK);
3449                         DRM_DEBUG_KMS("FDI train 2 done.\n");
3450                         break;
3451                 }
3452         }
3453         if (tries == 5)
3454                 DRM_ERROR("FDI train 2 fail!\n");
3455
3456         DRM_DEBUG_KMS("FDI train done\n");
3457
3458 }
3459
3460 static const int snb_b_fdi_train_param[] = {
3461         FDI_LINK_TRAIN_400MV_0DB_SNB_B,
3462         FDI_LINK_TRAIN_400MV_6DB_SNB_B,
3463         FDI_LINK_TRAIN_600MV_3_5DB_SNB_B,
3464         FDI_LINK_TRAIN_800MV_0DB_SNB_B,
3465 };
3466
3467 /* The FDI link training functions for SNB/Cougarpoint. */
3468 static void gen6_fdi_link_train(struct drm_crtc *crtc)
3469 {
3470         struct drm_device *dev = crtc->dev;
3471         struct drm_i915_private *dev_priv = to_i915(dev);
3472         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
3473         int pipe = intel_crtc->pipe;
3474         i915_reg_t reg;
3475         u32 temp, i, retry;
3476
3477         /* Train 1: umask FDI RX Interrupt symbol_lock and bit_lock bit
3478            for train result */
3479         reg = FDI_RX_IMR(pipe);
3480         temp = I915_READ(reg);
3481         temp &= ~FDI_RX_SYMBOL_LOCK;
3482         temp &= ~FDI_RX_BIT_LOCK;
3483         I915_WRITE(reg, temp);
3484
3485         POSTING_READ(reg);
3486         udelay(150);
3487
3488         /* enable CPU FDI TX and PCH FDI RX */
3489         reg = FDI_TX_CTL(pipe);
3490         temp = I915_READ(reg);
3491         temp &= ~FDI_DP_PORT_WIDTH_MASK;
3492         temp |= FDI_DP_PORT_WIDTH(intel_crtc->config->fdi_lanes);
3493         temp &= ~FDI_LINK_TRAIN_NONE;
3494         temp |= FDI_LINK_TRAIN_PATTERN_1;
3495         temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
3496         /* SNB-B */
3497         temp |= FDI_LINK_TRAIN_400MV_0DB_SNB_B;
3498         I915_WRITE(reg, temp | FDI_TX_ENABLE);
3499
3500         I915_WRITE(FDI_RX_MISC(pipe),
3501                    FDI_RX_TP1_TO_TP2_48 | FDI_RX_FDI_DELAY_90);
3502
3503         reg = FDI_RX_CTL(pipe);
3504         temp = I915_READ(reg);
3505         if (HAS_PCH_CPT(dev)) {
3506                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
3507                 temp |= FDI_LINK_TRAIN_PATTERN_1_CPT;
3508         } else {
3509                 temp &= ~FDI_LINK_TRAIN_NONE;
3510                 temp |= FDI_LINK_TRAIN_PATTERN_1;
3511         }
3512         I915_WRITE(reg, temp | FDI_RX_ENABLE);
3513
3514         POSTING_READ(reg);
3515         udelay(150);
3516
3517         for (i = 0; i < 4; i++) {
3518                 reg = FDI_TX_CTL(pipe);
3519                 temp = I915_READ(reg);
3520                 temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
3521                 temp |= snb_b_fdi_train_param[i];
3522                 I915_WRITE(reg, temp);
3523
3524                 POSTING_READ(reg);
3525                 udelay(500);
3526
3527                 for (retry = 0; retry < 5; retry++) {
3528                         reg = FDI_RX_IIR(pipe);
3529                         temp = I915_READ(reg);
3530                         DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
3531                         if (temp & FDI_RX_BIT_LOCK) {
3532                                 I915_WRITE(reg, temp | FDI_RX_BIT_LOCK);
3533                                 DRM_DEBUG_KMS("FDI train 1 done.\n");
3534                                 break;
3535                         }
3536                         udelay(50);
3537                 }
3538                 if (retry < 5)
3539                         break;
3540         }
3541         if (i == 4)
3542                 DRM_ERROR("FDI train 1 fail!\n");
3543
3544         /* Train 2 */
3545         reg = FDI_TX_CTL(pipe);
3546         temp = I915_READ(reg);
3547         temp &= ~FDI_LINK_TRAIN_NONE;
3548         temp |= FDI_LINK_TRAIN_PATTERN_2;
3549         if (IS_GEN6(dev)) {
3550                 temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
3551                 /* SNB-B */
3552                 temp |= FDI_LINK_TRAIN_400MV_0DB_SNB_B;
3553         }
3554         I915_WRITE(reg, temp);
3555
3556         reg = FDI_RX_CTL(pipe);
3557         temp = I915_READ(reg);
3558         if (HAS_PCH_CPT(dev)) {
3559                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
3560                 temp |= FDI_LINK_TRAIN_PATTERN_2_CPT;
3561         } else {
3562                 temp &= ~FDI_LINK_TRAIN_NONE;
3563                 temp |= FDI_LINK_TRAIN_PATTERN_2;
3564         }
3565         I915_WRITE(reg, temp);
3566
3567         POSTING_READ(reg);
3568         udelay(150);
3569
3570         for (i = 0; i < 4; i++) {
3571                 reg = FDI_TX_CTL(pipe);
3572                 temp = I915_READ(reg);
3573                 temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
3574                 temp |= snb_b_fdi_train_param[i];
3575                 I915_WRITE(reg, temp);
3576
3577                 POSTING_READ(reg);
3578                 udelay(500);
3579
3580                 for (retry = 0; retry < 5; retry++) {
3581                         reg = FDI_RX_IIR(pipe);
3582                         temp = I915_READ(reg);
3583                         DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
3584                         if (temp & FDI_RX_SYMBOL_LOCK) {
3585                                 I915_WRITE(reg, temp | FDI_RX_SYMBOL_LOCK);
3586                                 DRM_DEBUG_KMS("FDI train 2 done.\n");
3587                                 break;
3588                         }
3589                         udelay(50);
3590                 }
3591                 if (retry < 5)
3592                         break;
3593         }
3594         if (i == 4)
3595                 DRM_ERROR("FDI train 2 fail!\n");
3596
3597         DRM_DEBUG_KMS("FDI train done.\n");
3598 }
3599
3600 /* Manual link training for Ivy Bridge A0 parts */
3601 static void ivb_manual_fdi_link_train(struct drm_crtc *crtc)
3602 {
3603         struct drm_device *dev = crtc->dev;
3604         struct drm_i915_private *dev_priv = to_i915(dev);
3605         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
3606         int pipe = intel_crtc->pipe;
3607         i915_reg_t reg;
3608         u32 temp, i, j;
3609
3610         /* Train 1: umask FDI RX Interrupt symbol_lock and bit_lock bit
3611            for train result */
3612         reg = FDI_RX_IMR(pipe);
3613         temp = I915_READ(reg);
3614         temp &= ~FDI_RX_SYMBOL_LOCK;
3615         temp &= ~FDI_RX_BIT_LOCK;
3616         I915_WRITE(reg, temp);
3617
3618         POSTING_READ(reg);
3619         udelay(150);
3620
3621         DRM_DEBUG_KMS("FDI_RX_IIR before link train 0x%x\n",
3622                       I915_READ(FDI_RX_IIR(pipe)));
3623
3624         /* Try each vswing and preemphasis setting twice before moving on */
3625         for (j = 0; j < ARRAY_SIZE(snb_b_fdi_train_param) * 2; j++) {
3626                 /* disable first in case we need to retry */
3627                 reg = FDI_TX_CTL(pipe);
3628                 temp = I915_READ(reg);
3629                 temp &= ~(FDI_LINK_TRAIN_AUTO | FDI_LINK_TRAIN_NONE_IVB);
3630                 temp &= ~FDI_TX_ENABLE;
3631                 I915_WRITE(reg, temp);
3632
3633                 reg = FDI_RX_CTL(pipe);
3634                 temp = I915_READ(reg);
3635                 temp &= ~FDI_LINK_TRAIN_AUTO;
3636                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
3637                 temp &= ~FDI_RX_ENABLE;
3638                 I915_WRITE(reg, temp);
3639
3640                 /* enable CPU FDI TX and PCH FDI RX */
3641                 reg = FDI_TX_CTL(pipe);
3642                 temp = I915_READ(reg);
3643                 temp &= ~FDI_DP_PORT_WIDTH_MASK;
3644                 temp |= FDI_DP_PORT_WIDTH(intel_crtc->config->fdi_lanes);
3645                 temp |= FDI_LINK_TRAIN_PATTERN_1_IVB;
3646                 temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
3647                 temp |= snb_b_fdi_train_param[j/2];
3648                 temp |= FDI_COMPOSITE_SYNC;
3649                 I915_WRITE(reg, temp | FDI_TX_ENABLE);
3650
3651                 I915_WRITE(FDI_RX_MISC(pipe),
3652                            FDI_RX_TP1_TO_TP2_48 | FDI_RX_FDI_DELAY_90);
3653
3654                 reg = FDI_RX_CTL(pipe);
3655                 temp = I915_READ(reg);
3656                 temp |= FDI_LINK_TRAIN_PATTERN_1_CPT;
3657                 temp |= FDI_COMPOSITE_SYNC;
3658                 I915_WRITE(reg, temp | FDI_RX_ENABLE);
3659
3660                 POSTING_READ(reg);
3661                 udelay(1); /* should be 0.5us */
3662
3663                 for (i = 0; i < 4; i++) {
3664                         reg = FDI_RX_IIR(pipe);
3665                         temp = I915_READ(reg);
3666                         DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
3667
3668                         if (temp & FDI_RX_BIT_LOCK ||
3669                             (I915_READ(reg) & FDI_RX_BIT_LOCK)) {
3670                                 I915_WRITE(reg, temp | FDI_RX_BIT_LOCK);
3671                                 DRM_DEBUG_KMS("FDI train 1 done, level %i.\n",
3672                                               i);
3673                                 break;
3674                         }
3675                         udelay(1); /* should be 0.5us */
3676                 }
3677                 if (i == 4) {
3678                         DRM_DEBUG_KMS("FDI train 1 fail on vswing %d\n", j / 2);
3679                         continue;
3680                 }
3681
3682                 /* Train 2 */
3683                 reg = FDI_TX_CTL(pipe);
3684                 temp = I915_READ(reg);
3685                 temp &= ~FDI_LINK_TRAIN_NONE_IVB;
3686                 temp |= FDI_LINK_TRAIN_PATTERN_2_IVB;
3687                 I915_WRITE(reg, temp);
3688
3689                 reg = FDI_RX_CTL(pipe);
3690                 temp = I915_READ(reg);
3691                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
3692                 temp |= FDI_LINK_TRAIN_PATTERN_2_CPT;
3693                 I915_WRITE(reg, temp);
3694
3695                 POSTING_READ(reg);
3696                 udelay(2); /* should be 1.5us */
3697
3698                 for (i = 0; i < 4; i++) {
3699                         reg = FDI_RX_IIR(pipe);
3700                         temp = I915_READ(reg);
3701                         DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
3702
3703                         if (temp & FDI_RX_SYMBOL_LOCK ||
3704                             (I915_READ(reg) & FDI_RX_SYMBOL_LOCK)) {
3705                                 I915_WRITE(reg, temp | FDI_RX_SYMBOL_LOCK);
3706                                 DRM_DEBUG_KMS("FDI train 2 done, level %i.\n",
3707                                               i);
3708                                 goto train_done;
3709                         }
3710                         udelay(2); /* should be 1.5us */
3711                 }
3712                 if (i == 4)
3713                         DRM_DEBUG_KMS("FDI train 2 fail on vswing %d\n", j / 2);
3714         }
3715
3716 train_done:
3717         DRM_DEBUG_KMS("FDI train done.\n");
3718 }
3719
3720 static void ironlake_fdi_pll_enable(struct intel_crtc *intel_crtc)
3721 {
3722         struct drm_device *dev = intel_crtc->base.dev;
3723         struct drm_i915_private *dev_priv = to_i915(dev);
3724         int pipe = intel_crtc->pipe;
3725         i915_reg_t reg;
3726         u32 temp;
3727
3728         /* enable PCH FDI RX PLL, wait warmup plus DMI latency */
3729         reg = FDI_RX_CTL(pipe);
3730         temp = I915_READ(reg);
3731         temp &= ~(FDI_DP_PORT_WIDTH_MASK | (0x7 << 16));
3732         temp |= FDI_DP_PORT_WIDTH(intel_crtc->config->fdi_lanes);
3733         temp |= (I915_READ(PIPECONF(pipe)) & PIPECONF_BPC_MASK) << 11;
3734         I915_WRITE(reg, temp | FDI_RX_PLL_ENABLE);
3735
3736         POSTING_READ(reg);
3737         udelay(200);
3738
3739         /* Switch from Rawclk to PCDclk */
3740         temp = I915_READ(reg);
3741         I915_WRITE(reg, temp | FDI_PCDCLK);
3742
3743         POSTING_READ(reg);
3744         udelay(200);
3745
3746         /* Enable CPU FDI TX PLL, always on for Ironlake */
3747         reg = FDI_TX_CTL(pipe);
3748         temp = I915_READ(reg);
3749         if ((temp & FDI_TX_PLL_ENABLE) == 0) {
3750                 I915_WRITE(reg, temp | FDI_TX_PLL_ENABLE);
3751
3752                 POSTING_READ(reg);
3753                 udelay(100);
3754         }
3755 }
3756
3757 static void ironlake_fdi_pll_disable(struct intel_crtc *intel_crtc)
3758 {
3759         struct drm_device *dev = intel_crtc->base.dev;
3760         struct drm_i915_private *dev_priv = to_i915(dev);
3761         int pipe = intel_crtc->pipe;
3762         i915_reg_t reg;
3763         u32 temp;
3764
3765         /* Switch from PCDclk to Rawclk */
3766         reg = FDI_RX_CTL(pipe);
3767         temp = I915_READ(reg);
3768         I915_WRITE(reg, temp & ~FDI_PCDCLK);
3769
3770         /* Disable CPU FDI TX PLL */
3771         reg = FDI_TX_CTL(pipe);
3772         temp = I915_READ(reg);
3773         I915_WRITE(reg, temp & ~FDI_TX_PLL_ENABLE);
3774
3775         POSTING_READ(reg);
3776         udelay(100);
3777
3778         reg = FDI_RX_CTL(pipe);
3779         temp = I915_READ(reg);
3780         I915_WRITE(reg, temp & ~FDI_RX_PLL_ENABLE);
3781
3782         /* Wait for the clocks to turn off. */
3783         POSTING_READ(reg);
3784         udelay(100);
3785 }
3786
3787 static void ironlake_fdi_disable(struct drm_crtc *crtc)
3788 {
3789         struct drm_device *dev = crtc->dev;
3790         struct drm_i915_private *dev_priv = to_i915(dev);
3791         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
3792         int pipe = intel_crtc->pipe;
3793         i915_reg_t reg;
3794         u32 temp;
3795
3796         /* disable CPU FDI tx and PCH FDI rx */
3797         reg = FDI_TX_CTL(pipe);
3798         temp = I915_READ(reg);
3799         I915_WRITE(reg, temp & ~FDI_TX_ENABLE);
3800         POSTING_READ(reg);
3801
3802         reg = FDI_RX_CTL(pipe);
3803         temp = I915_READ(reg);
3804         temp &= ~(0x7 << 16);
3805         temp |= (I915_READ(PIPECONF(pipe)) & PIPECONF_BPC_MASK) << 11;
3806         I915_WRITE(reg, temp & ~FDI_RX_ENABLE);
3807
3808         POSTING_READ(reg);
3809         udelay(100);
3810
3811         /* Ironlake workaround, disable clock pointer after downing FDI */
3812         if (HAS_PCH_IBX(dev))
3813                 I915_WRITE(FDI_RX_CHICKEN(pipe), FDI_RX_PHASE_SYNC_POINTER_OVR);
3814
3815         /* still set train pattern 1 */
3816         reg = FDI_TX_CTL(pipe);
3817         temp = I915_READ(reg);
3818         temp &= ~FDI_LINK_TRAIN_NONE;
3819         temp |= FDI_LINK_TRAIN_PATTERN_1;
3820         I915_WRITE(reg, temp);
3821
3822         reg = FDI_RX_CTL(pipe);
3823         temp = I915_READ(reg);
3824         if (HAS_PCH_CPT(dev)) {
3825                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
3826                 temp |= FDI_LINK_TRAIN_PATTERN_1_CPT;
3827         } else {
3828                 temp &= ~FDI_LINK_TRAIN_NONE;
3829                 temp |= FDI_LINK_TRAIN_PATTERN_1;
3830         }
3831         /* BPC in FDI rx is consistent with that in PIPECONF */
3832         temp &= ~(0x07 << 16);
3833         temp |= (I915_READ(PIPECONF(pipe)) & PIPECONF_BPC_MASK) << 11;
3834         I915_WRITE(reg, temp);
3835
3836         POSTING_READ(reg);
3837         udelay(100);
3838 }
3839
3840 bool intel_has_pending_fb_unpin(struct drm_device *dev)
3841 {
3842         struct intel_crtc *crtc;
3843
3844         /* Note that we don't need to be called with mode_config.lock here
3845          * as our list of CRTC objects is static for the lifetime of the
3846          * device and so cannot disappear as we iterate. Similarly, we can
3847          * happily treat the predicates as racy, atomic checks as userspace
3848          * cannot claim and pin a new fb without at least acquring the
3849          * struct_mutex and so serialising with us.
3850          */
3851         for_each_intel_crtc(dev, crtc) {
3852                 if (atomic_read(&crtc->unpin_work_count) == 0)
3853                         continue;
3854
3855                 if (crtc->flip_work)
3856                         intel_wait_for_vblank(dev, crtc->pipe);
3857
3858                 return true;
3859         }
3860
3861         return false;
3862 }
3863
3864 static void page_flip_completed(struct intel_crtc *intel_crtc)
3865 {
3866         struct drm_i915_private *dev_priv = to_i915(intel_crtc->base.dev);
3867         struct intel_flip_work *work = intel_crtc->flip_work;
3868
3869         intel_crtc->flip_work = NULL;
3870
3871         if (work->event)
3872                 drm_crtc_send_vblank_event(&intel_crtc->base, work->event);
3873
3874         drm_crtc_vblank_put(&intel_crtc->base);
3875
3876         wake_up_all(&dev_priv->pending_flip_queue);
3877         queue_work(dev_priv->wq, &work->unpin_work);
3878
3879         trace_i915_flip_complete(intel_crtc->plane,
3880                                  work->pending_flip_obj);
3881 }
3882
3883 static int intel_crtc_wait_for_pending_flips(struct drm_crtc *crtc)
3884 {
3885         struct drm_device *dev = crtc->dev;
3886         struct drm_i915_private *dev_priv = to_i915(dev);
3887         long ret;
3888
3889         WARN_ON(waitqueue_active(&dev_priv->pending_flip_queue));
3890
3891         ret = wait_event_interruptible_timeout(
3892                                         dev_priv->pending_flip_queue,
3893                                         !intel_crtc_has_pending_flip(crtc),
3894                                         60*HZ);
3895
3896         if (ret < 0)
3897                 return ret;
3898
3899         if (ret == 0) {
3900                 struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
3901                 struct intel_flip_work *work;
3902
3903                 spin_lock_irq(&dev->event_lock);
3904                 work = intel_crtc->flip_work;
3905                 if (work && !is_mmio_work(work)) {
3906                         WARN_ONCE(1, "Removing stuck page flip\n");
3907                         page_flip_completed(intel_crtc);
3908                 }
3909                 spin_unlock_irq(&dev->event_lock);
3910         }
3911
3912         return 0;
3913 }
3914
3915 static void lpt_disable_iclkip(struct drm_i915_private *dev_priv)
3916 {
3917         u32 temp;
3918
3919         I915_WRITE(PIXCLK_GATE, PIXCLK_GATE_GATE);
3920
3921         mutex_lock(&dev_priv->sb_lock);
3922
3923         temp = intel_sbi_read(dev_priv, SBI_SSCCTL6, SBI_ICLK);
3924         temp |= SBI_SSCCTL_DISABLE;
3925         intel_sbi_write(dev_priv, SBI_SSCCTL6, temp, SBI_ICLK);
3926
3927         mutex_unlock(&dev_priv->sb_lock);
3928 }
3929
3930 /* Program iCLKIP clock to the desired frequency */
3931 static void lpt_program_iclkip(struct drm_crtc *crtc)
3932 {
3933         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
3934         int clock = to_intel_crtc(crtc)->config->base.adjusted_mode.crtc_clock;
3935         u32 divsel, phaseinc, auxdiv, phasedir = 0;
3936         u32 temp;
3937
3938         lpt_disable_iclkip(dev_priv);
3939
3940         /* The iCLK virtual clock root frequency is in MHz,
3941          * but the adjusted_mode->crtc_clock in in KHz. To get the
3942          * divisors, it is necessary to divide one by another, so we
3943          * convert the virtual clock precision to KHz here for higher
3944          * precision.
3945          */
3946         for (auxdiv = 0; auxdiv < 2; auxdiv++) {
3947                 u32 iclk_virtual_root_freq = 172800 * 1000;
3948                 u32 iclk_pi_range = 64;
3949                 u32 desired_divisor;
3950
3951                 desired_divisor = DIV_ROUND_CLOSEST(iclk_virtual_root_freq,
3952                                                     clock << auxdiv);
3953                 divsel = (desired_divisor / iclk_pi_range) - 2;
3954                 phaseinc = desired_divisor % iclk_pi_range;
3955
3956                 /*
3957                  * Near 20MHz is a corner case which is
3958                  * out of range for the 7-bit divisor
3959                  */
3960                 if (divsel <= 0x7f)
3961                         break;
3962         }
3963
3964         /* This should not happen with any sane values */
3965         WARN_ON(SBI_SSCDIVINTPHASE_DIVSEL(divsel) &
3966                 ~SBI_SSCDIVINTPHASE_DIVSEL_MASK);
3967         WARN_ON(SBI_SSCDIVINTPHASE_DIR(phasedir) &
3968                 ~SBI_SSCDIVINTPHASE_INCVAL_MASK);
3969
3970         DRM_DEBUG_KMS("iCLKIP clock: found settings for %dKHz refresh rate: auxdiv=%x, divsel=%x, phasedir=%x, phaseinc=%x\n",
3971                         clock,
3972                         auxdiv,
3973                         divsel,
3974                         phasedir,
3975                         phaseinc);
3976
3977         mutex_lock(&dev_priv->sb_lock);
3978
3979         /* Program SSCDIVINTPHASE6 */
3980         temp = intel_sbi_read(dev_priv, SBI_SSCDIVINTPHASE6, SBI_ICLK);
3981         temp &= ~SBI_SSCDIVINTPHASE_DIVSEL_MASK;
3982         temp |= SBI_SSCDIVINTPHASE_DIVSEL(divsel);
3983         temp &= ~SBI_SSCDIVINTPHASE_INCVAL_MASK;
3984         temp |= SBI_SSCDIVINTPHASE_INCVAL(phaseinc);
3985         temp |= SBI_SSCDIVINTPHASE_DIR(phasedir);
3986         temp |= SBI_SSCDIVINTPHASE_PROPAGATE;
3987         intel_sbi_write(dev_priv, SBI_SSCDIVINTPHASE6, temp, SBI_ICLK);
3988
3989         /* Program SSCAUXDIV */
3990         temp = intel_sbi_read(dev_priv, SBI_SSCAUXDIV6, SBI_ICLK);
3991         temp &= ~SBI_SSCAUXDIV_FINALDIV2SEL(1);
3992         temp |= SBI_SSCAUXDIV_FINALDIV2SEL(auxdiv);
3993         intel_sbi_write(dev_priv, SBI_SSCAUXDIV6, temp, SBI_ICLK);
3994
3995         /* Enable modulator and associated divider */
3996         temp = intel_sbi_read(dev_priv, SBI_SSCCTL6, SBI_ICLK);
3997         temp &= ~SBI_SSCCTL_DISABLE;
3998         intel_sbi_write(dev_priv, SBI_SSCCTL6, temp, SBI_ICLK);
3999
4000         mutex_unlock(&dev_priv->sb_lock);
4001
4002         /* Wait for initialization time */
4003         udelay(24);
4004
4005         I915_WRITE(PIXCLK_GATE, PIXCLK_GATE_UNGATE);
4006 }
4007
4008 int lpt_get_iclkip(struct drm_i915_private *dev_priv)
4009 {
4010         u32 divsel, phaseinc, auxdiv;
4011         u32 iclk_virtual_root_freq = 172800 * 1000;
4012         u32 iclk_pi_range = 64;
4013         u32 desired_divisor;
4014         u32 temp;
4015
4016         if ((I915_READ(PIXCLK_GATE) & PIXCLK_GATE_UNGATE) == 0)
4017                 return 0;
4018
4019         mutex_lock(&dev_priv->sb_lock);
4020
4021         temp = intel_sbi_read(dev_priv, SBI_SSCCTL6, SBI_ICLK);
4022         if (temp & SBI_SSCCTL_DISABLE) {
4023                 mutex_unlock(&dev_priv->sb_lock);
4024                 return 0;
4025         }
4026
4027         temp = intel_sbi_read(dev_priv, SBI_SSCDIVINTPHASE6, SBI_ICLK);
4028         divsel = (temp & SBI_SSCDIVINTPHASE_DIVSEL_MASK) >>
4029                 SBI_SSCDIVINTPHASE_DIVSEL_SHIFT;
4030         phaseinc = (temp & SBI_SSCDIVINTPHASE_INCVAL_MASK) >>
4031                 SBI_SSCDIVINTPHASE_INCVAL_SHIFT;
4032
4033         temp = intel_sbi_read(dev_priv, SBI_SSCAUXDIV6, SBI_ICLK);
4034         auxdiv = (temp & SBI_SSCAUXDIV_FINALDIV2SEL_MASK) >>
4035                 SBI_SSCAUXDIV_FINALDIV2SEL_SHIFT;
4036
4037         mutex_unlock(&dev_priv->sb_lock);
4038
4039         desired_divisor = (divsel + 2) * iclk_pi_range + phaseinc;
4040
4041         return DIV_ROUND_CLOSEST(iclk_virtual_root_freq,
4042                                  desired_divisor << auxdiv);
4043 }
4044
4045 static void ironlake_pch_transcoder_set_timings(struct intel_crtc *crtc,
4046                                                 enum pipe pch_transcoder)
4047 {
4048         struct drm_device *dev = crtc->base.dev;
4049         struct drm_i915_private *dev_priv = to_i915(dev);
4050         enum transcoder cpu_transcoder = crtc->config->cpu_transcoder;
4051
4052         I915_WRITE(PCH_TRANS_HTOTAL(pch_transcoder),
4053                    I915_READ(HTOTAL(cpu_transcoder)));
4054         I915_WRITE(PCH_TRANS_HBLANK(pch_transcoder),
4055                    I915_READ(HBLANK(cpu_transcoder)));
4056         I915_WRITE(PCH_TRANS_HSYNC(pch_transcoder),
4057                    I915_READ(HSYNC(cpu_transcoder)));
4058
4059         I915_WRITE(PCH_TRANS_VTOTAL(pch_transcoder),
4060                    I915_READ(VTOTAL(cpu_transcoder)));
4061         I915_WRITE(PCH_TRANS_VBLANK(pch_transcoder),
4062                    I915_READ(VBLANK(cpu_transcoder)));
4063         I915_WRITE(PCH_TRANS_VSYNC(pch_transcoder),
4064                    I915_READ(VSYNC(cpu_transcoder)));
4065         I915_WRITE(PCH_TRANS_VSYNCSHIFT(pch_transcoder),
4066                    I915_READ(VSYNCSHIFT(cpu_transcoder)));
4067 }
4068
4069 static void cpt_set_fdi_bc_bifurcation(struct drm_device *dev, bool enable)
4070 {
4071         struct drm_i915_private *dev_priv = to_i915(dev);
4072         uint32_t temp;
4073
4074         temp = I915_READ(SOUTH_CHICKEN1);
4075         if (!!(temp & FDI_BC_BIFURCATION_SELECT) == enable)
4076                 return;
4077
4078         WARN_ON(I915_READ(FDI_RX_CTL(PIPE_B)) & FDI_RX_ENABLE);
4079         WARN_ON(I915_READ(FDI_RX_CTL(PIPE_C)) & FDI_RX_ENABLE);
4080
4081         temp &= ~FDI_BC_BIFURCATION_SELECT;
4082         if (enable)
4083                 temp |= FDI_BC_BIFURCATION_SELECT;
4084
4085         DRM_DEBUG_KMS("%sabling fdi C rx\n", enable ? "en" : "dis");
4086         I915_WRITE(SOUTH_CHICKEN1, temp);
4087         POSTING_READ(SOUTH_CHICKEN1);
4088 }
4089
4090 static void ivybridge_update_fdi_bc_bifurcation(struct intel_crtc *intel_crtc)
4091 {
4092         struct drm_device *dev = intel_crtc->base.dev;
4093
4094         switch (intel_crtc->pipe) {
4095         case PIPE_A:
4096                 break;
4097         case PIPE_B:
4098                 if (intel_crtc->config->fdi_lanes > 2)
4099                         cpt_set_fdi_bc_bifurcation(dev, false);
4100                 else
4101                         cpt_set_fdi_bc_bifurcation(dev, true);
4102
4103                 break;
4104         case PIPE_C:
4105                 cpt_set_fdi_bc_bifurcation(dev, true);
4106
4107                 break;
4108         default:
4109                 BUG();
4110         }
4111 }
4112
4113 /* Return which DP Port should be selected for Transcoder DP control */
4114 static enum port
4115 intel_trans_dp_port_sel(struct drm_crtc *crtc)
4116 {
4117         struct drm_device *dev = crtc->dev;
4118         struct intel_encoder *encoder;
4119
4120         for_each_encoder_on_crtc(dev, crtc, encoder) {
4121                 if (encoder->type == INTEL_OUTPUT_DP ||
4122                     encoder->type == INTEL_OUTPUT_EDP)
4123                         return enc_to_dig_port(&encoder->base)->port;
4124         }
4125
4126         return -1;
4127 }
4128
4129 /*
4130  * Enable PCH resources required for PCH ports:
4131  *   - PCH PLLs
4132  *   - FDI training & RX/TX
4133  *   - update transcoder timings
4134  *   - DP transcoding bits
4135  *   - transcoder
4136  */
4137 static void ironlake_pch_enable(struct drm_crtc *crtc)
4138 {
4139         struct drm_device *dev = crtc->dev;
4140         struct drm_i915_private *dev_priv = to_i915(dev);
4141         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4142         int pipe = intel_crtc->pipe;
4143         u32 temp;
4144
4145         assert_pch_transcoder_disabled(dev_priv, pipe);
4146
4147         if (IS_IVYBRIDGE(dev))
4148                 ivybridge_update_fdi_bc_bifurcation(intel_crtc);
4149
4150         /* Write the TU size bits before fdi link training, so that error
4151          * detection works. */
4152         I915_WRITE(FDI_RX_TUSIZE1(pipe),
4153                    I915_READ(PIPE_DATA_M1(pipe)) & TU_SIZE_MASK);
4154
4155         /* For PCH output, training FDI link */
4156         dev_priv->display.fdi_link_train(crtc);
4157
4158         /* We need to program the right clock selection before writing the pixel
4159          * mutliplier into the DPLL. */
4160         if (HAS_PCH_CPT(dev)) {
4161                 u32 sel;
4162
4163                 temp = I915_READ(PCH_DPLL_SEL);
4164                 temp |= TRANS_DPLL_ENABLE(pipe);
4165                 sel = TRANS_DPLLB_SEL(pipe);
4166                 if (intel_crtc->config->shared_dpll ==
4167                     intel_get_shared_dpll_by_id(dev_priv, DPLL_ID_PCH_PLL_B))
4168                         temp |= sel;
4169                 else
4170                         temp &= ~sel;
4171                 I915_WRITE(PCH_DPLL_SEL, temp);
4172         }
4173
4174         /* XXX: pch pll's can be enabled any time before we enable the PCH
4175          * transcoder, and we actually should do this to not upset any PCH
4176          * transcoder that already use the clock when we share it.
4177          *
4178          * Note that enable_shared_dpll tries to do the right thing, but
4179          * get_shared_dpll unconditionally resets the pll - we need that to have
4180          * the right LVDS enable sequence. */
4181         intel_enable_shared_dpll(intel_crtc);
4182
4183         /* set transcoder timing, panel must allow it */
4184         assert_panel_unlocked(dev_priv, pipe);
4185         ironlake_pch_transcoder_set_timings(intel_crtc, pipe);
4186
4187         intel_fdi_normal_train(crtc);
4188
4189         /* For PCH DP, enable TRANS_DP_CTL */
4190         if (HAS_PCH_CPT(dev) && intel_crtc_has_dp_encoder(intel_crtc->config)) {
4191                 const struct drm_display_mode *adjusted_mode =
4192                         &intel_crtc->config->base.adjusted_mode;
4193                 u32 bpc = (I915_READ(PIPECONF(pipe)) & PIPECONF_BPC_MASK) >> 5;
4194                 i915_reg_t reg = TRANS_DP_CTL(pipe);
4195                 temp = I915_READ(reg);
4196                 temp &= ~(TRANS_DP_PORT_SEL_MASK |
4197                           TRANS_DP_SYNC_MASK |
4198                           TRANS_DP_BPC_MASK);
4199                 temp |= TRANS_DP_OUTPUT_ENABLE;
4200                 temp |= bpc << 9; /* same format but at 11:9 */
4201
4202                 if (adjusted_mode->flags & DRM_MODE_FLAG_PHSYNC)
4203                         temp |= TRANS_DP_HSYNC_ACTIVE_HIGH;
4204                 if (adjusted_mode->flags & DRM_MODE_FLAG_PVSYNC)
4205                         temp |= TRANS_DP_VSYNC_ACTIVE_HIGH;
4206
4207                 switch (intel_trans_dp_port_sel(crtc)) {
4208                 case PORT_B:
4209                         temp |= TRANS_DP_PORT_SEL_B;
4210                         break;
4211                 case PORT_C:
4212                         temp |= TRANS_DP_PORT_SEL_C;
4213                         break;
4214                 case PORT_D:
4215                         temp |= TRANS_DP_PORT_SEL_D;
4216                         break;
4217                 default:
4218                         BUG();
4219                 }
4220
4221                 I915_WRITE(reg, temp);
4222         }
4223
4224         ironlake_enable_pch_transcoder(dev_priv, pipe);
4225 }
4226
4227 static void lpt_pch_enable(struct drm_crtc *crtc)
4228 {
4229         struct drm_device *dev = crtc->dev;
4230         struct drm_i915_private *dev_priv = to_i915(dev);
4231         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4232         enum transcoder cpu_transcoder = intel_crtc->config->cpu_transcoder;
4233
4234         assert_pch_transcoder_disabled(dev_priv, TRANSCODER_A);
4235
4236         lpt_program_iclkip(crtc);
4237
4238         /* Set transcoder timing. */
4239         ironlake_pch_transcoder_set_timings(intel_crtc, PIPE_A);
4240
4241         lpt_enable_pch_transcoder(dev_priv, cpu_transcoder);
4242 }
4243
4244 static void cpt_verify_modeset(struct drm_device *dev, int pipe)
4245 {
4246         struct drm_i915_private *dev_priv = to_i915(dev);
4247         i915_reg_t dslreg = PIPEDSL(pipe);
4248         u32 temp;
4249
4250         temp = I915_READ(dslreg);
4251         udelay(500);
4252         if (wait_for(I915_READ(dslreg) != temp, 5)) {
4253                 if (wait_for(I915_READ(dslreg) != temp, 5))
4254                         DRM_ERROR("mode set failed: pipe %c stuck\n", pipe_name(pipe));
4255         }
4256 }
4257
4258 static int
4259 skl_update_scaler(struct intel_crtc_state *crtc_state, bool force_detach,
4260                   unsigned scaler_user, int *scaler_id, unsigned int rotation,
4261                   int src_w, int src_h, int dst_w, int dst_h)
4262 {
4263         struct intel_crtc_scaler_state *scaler_state =
4264                 &crtc_state->scaler_state;
4265         struct intel_crtc *intel_crtc =
4266                 to_intel_crtc(crtc_state->base.crtc);
4267         int need_scaling;
4268
4269         need_scaling = intel_rotation_90_or_270(rotation) ?
4270                 (src_h != dst_w || src_w != dst_h):
4271                 (src_w != dst_w || src_h != dst_h);
4272
4273         /*
4274          * if plane is being disabled or scaler is no more required or force detach
4275          *  - free scaler binded to this plane/crtc
4276          *  - in order to do this, update crtc->scaler_usage
4277          *
4278          * Here scaler state in crtc_state is set free so that
4279          * scaler can be assigned to other user. Actual register
4280          * update to free the scaler is done in plane/panel-fit programming.
4281          * For this purpose crtc/plane_state->scaler_id isn't reset here.
4282          */
4283         if (force_detach || !need_scaling) {
4284                 if (*scaler_id >= 0) {
4285                         scaler_state->scaler_users &= ~(1 << scaler_user);
4286                         scaler_state->scalers[*scaler_id].in_use = 0;
4287
4288                         DRM_DEBUG_KMS("scaler_user index %u.%u: "
4289                                 "Staged freeing scaler id %d scaler_users = 0x%x\n",
4290                                 intel_crtc->pipe, scaler_user, *scaler_id,
4291                                 scaler_state->scaler_users);
4292                         *scaler_id = -1;
4293                 }
4294                 return 0;
4295         }
4296
4297         /* range checks */
4298         if (src_w < SKL_MIN_SRC_W || src_h < SKL_MIN_SRC_H ||
4299                 dst_w < SKL_MIN_DST_W || dst_h < SKL_MIN_DST_H ||
4300
4301                 src_w > SKL_MAX_SRC_W || src_h > SKL_MAX_SRC_H ||
4302                 dst_w > SKL_MAX_DST_W || dst_h > SKL_MAX_DST_H) {
4303                 DRM_DEBUG_KMS("scaler_user index %u.%u: src %ux%u dst %ux%u "
4304                         "size is out of scaler range\n",
4305                         intel_crtc->pipe, scaler_user, src_w, src_h, dst_w, dst_h);
4306                 return -EINVAL;
4307         }
4308
4309         /* mark this plane as a scaler user in crtc_state */
4310         scaler_state->scaler_users |= (1 << scaler_user);
4311         DRM_DEBUG_KMS("scaler_user index %u.%u: "
4312                 "staged scaling request for %ux%u->%ux%u scaler_users = 0x%x\n",
4313                 intel_crtc->pipe, scaler_user, src_w, src_h, dst_w, dst_h,
4314                 scaler_state->scaler_users);
4315
4316         return 0;
4317 }
4318
4319 /**
4320  * skl_update_scaler_crtc - Stages update to scaler state for a given crtc.
4321  *
4322  * @state: crtc's scaler state
4323  *
4324  * Return
4325  *     0 - scaler_usage updated successfully
4326  *    error - requested scaling cannot be supported or other error condition
4327  */
4328 int skl_update_scaler_crtc(struct intel_crtc_state *state)
4329 {
4330         struct intel_crtc *intel_crtc = to_intel_crtc(state->base.crtc);
4331         const struct drm_display_mode *adjusted_mode = &state->base.adjusted_mode;
4332
4333         DRM_DEBUG_KMS("Updating scaler for [CRTC:%d:%s] scaler_user index %u.%u\n",
4334                       intel_crtc->base.base.id, intel_crtc->base.name,
4335                       intel_crtc->pipe, SKL_CRTC_INDEX);
4336
4337         return skl_update_scaler(state, !state->base.active, SKL_CRTC_INDEX,
4338                 &state->scaler_state.scaler_id, BIT(DRM_ROTATE_0),
4339                 state->pipe_src_w, state->pipe_src_h,
4340                 adjusted_mode->crtc_hdisplay, adjusted_mode->crtc_vdisplay);
4341 }
4342
4343 /**
4344  * skl_update_scaler_plane - Stages update to scaler state for a given plane.
4345  *
4346  * @state: crtc's scaler state
4347  * @plane_state: atomic plane state to update
4348  *
4349  * Return
4350  *     0 - scaler_usage updated successfully
4351  *    error - requested scaling cannot be supported or other error condition
4352  */
4353 static int skl_update_scaler_plane(struct intel_crtc_state *crtc_state,
4354                                    struct intel_plane_state *plane_state)
4355 {
4356
4357         struct intel_crtc *intel_crtc = to_intel_crtc(crtc_state->base.crtc);
4358         struct intel_plane *intel_plane =
4359                 to_intel_plane(plane_state->base.plane);
4360         struct drm_framebuffer *fb = plane_state->base.fb;
4361         int ret;
4362
4363         bool force_detach = !fb || !plane_state->visible;
4364
4365         DRM_DEBUG_KMS("Updating scaler for [PLANE:%d:%s] scaler_user index %u.%u\n",
4366                       intel_plane->base.base.id, intel_plane->base.name,
4367                       intel_crtc->pipe, drm_plane_index(&intel_plane->base));
4368
4369         ret = skl_update_scaler(crtc_state, force_detach,
4370                                 drm_plane_index(&intel_plane->base),
4371                                 &plane_state->scaler_id,
4372                                 plane_state->base.rotation,
4373                                 drm_rect_width(&plane_state->src) >> 16,
4374                                 drm_rect_height(&plane_state->src) >> 16,
4375                                 drm_rect_width(&plane_state->dst),
4376                                 drm_rect_height(&plane_state->dst));
4377
4378         if (ret || plane_state->scaler_id < 0)
4379                 return ret;
4380
4381         /* check colorkey */
4382         if (plane_state->ckey.flags != I915_SET_COLORKEY_NONE) {
4383                 DRM_DEBUG_KMS("[PLANE:%d:%s] scaling with color key not allowed",
4384                               intel_plane->base.base.id,
4385                               intel_plane->base.name);
4386                 return -EINVAL;
4387         }
4388
4389         /* Check src format */
4390         switch (fb->pixel_format) {
4391         case DRM_FORMAT_RGB565:
4392         case DRM_FORMAT_XBGR8888:
4393         case DRM_FORMAT_XRGB8888:
4394         case DRM_FORMAT_ABGR8888:
4395         case DRM_FORMAT_ARGB8888:
4396         case DRM_FORMAT_XRGB2101010:
4397         case DRM_FORMAT_XBGR2101010:
4398         case DRM_FORMAT_YUYV:
4399         case DRM_FORMAT_YVYU:
4400         case DRM_FORMAT_UYVY:
4401         case DRM_FORMAT_VYUY:
4402                 break;
4403         default:
4404                 DRM_DEBUG_KMS("[PLANE:%d:%s] FB:%d unsupported scaling format 0x%x\n",
4405                               intel_plane->base.base.id, intel_plane->base.name,
4406                               fb->base.id, fb->pixel_format);
4407                 return -EINVAL;
4408         }
4409
4410         return 0;
4411 }
4412
4413 static void skylake_scaler_disable(struct intel_crtc *crtc)
4414 {
4415         int i;
4416
4417         for (i = 0; i < crtc->num_scalers; i++)
4418                 skl_detach_scaler(crtc, i);
4419 }
4420
4421 static void skylake_pfit_enable(struct intel_crtc *crtc)
4422 {
4423         struct drm_device *dev = crtc->base.dev;
4424         struct drm_i915_private *dev_priv = to_i915(dev);
4425         int pipe = crtc->pipe;
4426         struct intel_crtc_scaler_state *scaler_state =
4427                 &crtc->config->scaler_state;
4428
4429         DRM_DEBUG_KMS("for crtc_state = %p\n", crtc->config);
4430
4431         if (crtc->config->pch_pfit.enabled) {
4432                 int id;
4433
4434                 if (WARN_ON(crtc->config->scaler_state.scaler_id < 0)) {
4435                         DRM_ERROR("Requesting pfit without getting a scaler first\n");
4436                         return;
4437                 }
4438
4439                 id = scaler_state->scaler_id;
4440                 I915_WRITE(SKL_PS_CTRL(pipe, id), PS_SCALER_EN |
4441                         PS_FILTER_MEDIUM | scaler_state->scalers[id].mode);
4442                 I915_WRITE(SKL_PS_WIN_POS(pipe, id), crtc->config->pch_pfit.pos);
4443                 I915_WRITE(SKL_PS_WIN_SZ(pipe, id), crtc->config->pch_pfit.size);
4444
4445                 DRM_DEBUG_KMS("for crtc_state = %p scaler_id = %d\n", crtc->config, id);
4446         }
4447 }
4448
4449 static void ironlake_pfit_enable(struct intel_crtc *crtc)
4450 {
4451         struct drm_device *dev = crtc->base.dev;
4452         struct drm_i915_private *dev_priv = to_i915(dev);
4453         int pipe = crtc->pipe;
4454
4455         if (crtc->config->pch_pfit.enabled) {
4456                 /* Force use of hard-coded filter coefficients
4457                  * as some pre-programmed values are broken,
4458                  * e.g. x201.
4459                  */
4460                 if (IS_IVYBRIDGE(dev) || IS_HASWELL(dev))
4461                         I915_WRITE(PF_CTL(pipe), PF_ENABLE | PF_FILTER_MED_3x3 |
4462                                                  PF_PIPE_SEL_IVB(pipe));
4463                 else
4464                         I915_WRITE(PF_CTL(pipe), PF_ENABLE | PF_FILTER_MED_3x3);
4465                 I915_WRITE(PF_WIN_POS(pipe), crtc->config->pch_pfit.pos);
4466                 I915_WRITE(PF_WIN_SZ(pipe), crtc->config->pch_pfit.size);
4467         }
4468 }
4469
4470 void hsw_enable_ips(struct intel_crtc *crtc)
4471 {
4472         struct drm_device *dev = crtc->base.dev;
4473         struct drm_i915_private *dev_priv = to_i915(dev);
4474
4475         if (!crtc->config->ips_enabled)
4476                 return;
4477
4478         /*
4479          * We can only enable IPS after we enable a plane and wait for a vblank
4480          * This function is called from post_plane_update, which is run after
4481          * a vblank wait.
4482          */
4483
4484         assert_plane_enabled(dev_priv, crtc->plane);
4485         if (IS_BROADWELL(dev)) {
4486                 mutex_lock(&dev_priv->rps.hw_lock);
4487                 WARN_ON(sandybridge_pcode_write(dev_priv, DISPLAY_IPS_CONTROL, 0xc0000000));
4488                 mutex_unlock(&dev_priv->rps.hw_lock);
4489                 /* Quoting Art Runyan: "its not safe to expect any particular
4490                  * value in IPS_CTL bit 31 after enabling IPS through the
4491                  * mailbox." Moreover, the mailbox may return a bogus state,
4492                  * so we need to just enable it and continue on.
4493                  */
4494         } else {
4495                 I915_WRITE(IPS_CTL, IPS_ENABLE);
4496                 /* The bit only becomes 1 in the next vblank, so this wait here
4497                  * is essentially intel_wait_for_vblank. If we don't have this
4498                  * and don't wait for vblanks until the end of crtc_enable, then
4499                  * the HW state readout code will complain that the expected
4500                  * IPS_CTL value is not the one we read. */
4501                 if (intel_wait_for_register(dev_priv,
4502                                             IPS_CTL, IPS_ENABLE, IPS_ENABLE,
4503                                             50))
4504                         DRM_ERROR("Timed out waiting for IPS enable\n");
4505         }
4506 }
4507
4508 void hsw_disable_ips(struct intel_crtc *crtc)
4509 {
4510         struct drm_device *dev = crtc->base.dev;
4511         struct drm_i915_private *dev_priv = to_i915(dev);
4512
4513         if (!crtc->config->ips_enabled)
4514                 return;
4515
4516         assert_plane_enabled(dev_priv, crtc->plane);
4517         if (IS_BROADWELL(dev)) {
4518                 mutex_lock(&dev_priv->rps.hw_lock);
4519                 WARN_ON(sandybridge_pcode_write(dev_priv, DISPLAY_IPS_CONTROL, 0));
4520                 mutex_unlock(&dev_priv->rps.hw_lock);
4521                 /* wait for pcode to finish disabling IPS, which may take up to 42ms */
4522                 if (intel_wait_for_register(dev_priv,
4523                                             IPS_CTL, IPS_ENABLE, 0,
4524                                             42))
4525                         DRM_ERROR("Timed out waiting for IPS disable\n");
4526         } else {
4527                 I915_WRITE(IPS_CTL, 0);
4528                 POSTING_READ(IPS_CTL);
4529         }
4530
4531         /* We need to wait for a vblank before we can disable the plane. */
4532         intel_wait_for_vblank(dev, crtc->pipe);
4533 }
4534
4535 static void intel_crtc_dpms_overlay_disable(struct intel_crtc *intel_crtc)
4536 {
4537         if (intel_crtc->overlay) {
4538                 struct drm_device *dev = intel_crtc->base.dev;
4539                 struct drm_i915_private *dev_priv = to_i915(dev);
4540
4541                 mutex_lock(&dev->struct_mutex);
4542                 dev_priv->mm.interruptible = false;
4543                 (void) intel_overlay_switch_off(intel_crtc->overlay);
4544                 dev_priv->mm.interruptible = true;
4545                 mutex_unlock(&dev->struct_mutex);
4546         }
4547
4548         /* Let userspace switch the overlay on again. In most cases userspace
4549          * has to recompute where to put it anyway.
4550          */
4551 }
4552
4553 /**
4554  * intel_post_enable_primary - Perform operations after enabling primary plane
4555  * @crtc: the CRTC whose primary plane was just enabled
4556  *
4557  * Performs potentially sleeping operations that must be done after the primary
4558  * plane is enabled, such as updating FBC and IPS.  Note that this may be
4559  * called due to an explicit primary plane update, or due to an implicit
4560  * re-enable that is caused when a sprite plane is updated to no longer
4561  * completely hide the primary plane.
4562  */
4563 static void
4564 intel_post_enable_primary(struct drm_crtc *crtc)
4565 {
4566         struct drm_device *dev = crtc->dev;
4567         struct drm_i915_private *dev_priv = to_i915(dev);
4568         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4569         int pipe = intel_crtc->pipe;
4570
4571         /*
4572          * FIXME IPS should be fine as long as one plane is
4573          * enabled, but in practice it seems to have problems
4574          * when going from primary only to sprite only and vice
4575          * versa.
4576          */
4577         hsw_enable_ips(intel_crtc);
4578
4579         /*
4580          * Gen2 reports pipe underruns whenever all planes are disabled.
4581          * So don't enable underrun reporting before at least some planes
4582          * are enabled.
4583          * FIXME: Need to fix the logic to work when we turn off all planes
4584          * but leave the pipe running.
4585          */
4586         if (IS_GEN2(dev))
4587                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
4588
4589         /* Underruns don't always raise interrupts, so check manually. */
4590         intel_check_cpu_fifo_underruns(dev_priv);
4591         intel_check_pch_fifo_underruns(dev_priv);
4592 }
4593
4594 /* FIXME move all this to pre_plane_update() with proper state tracking */
4595 static void
4596 intel_pre_disable_primary(struct drm_crtc *crtc)
4597 {
4598         struct drm_device *dev = crtc->dev;
4599         struct drm_i915_private *dev_priv = to_i915(dev);
4600         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4601         int pipe = intel_crtc->pipe;
4602
4603         /*
4604          * Gen2 reports pipe underruns whenever all planes are disabled.
4605          * So diasble underrun reporting before all the planes get disabled.
4606          * FIXME: Need to fix the logic to work when we turn off all planes
4607          * but leave the pipe running.
4608          */
4609         if (IS_GEN2(dev))
4610                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, false);
4611
4612         /*
4613          * FIXME IPS should be fine as long as one plane is
4614          * enabled, but in practice it seems to have problems
4615          * when going from primary only to sprite only and vice
4616          * versa.
4617          */
4618         hsw_disable_ips(intel_crtc);
4619 }
4620
4621 /* FIXME get rid of this and use pre_plane_update */
4622 static void
4623 intel_pre_disable_primary_noatomic(struct drm_crtc *crtc)
4624 {
4625         struct drm_device *dev = crtc->dev;
4626         struct drm_i915_private *dev_priv = to_i915(dev);
4627         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4628         int pipe = intel_crtc->pipe;
4629
4630         intel_pre_disable_primary(crtc);
4631
4632         /*
4633          * Vblank time updates from the shadow to live plane control register
4634          * are blocked if the memory self-refresh mode is active at that
4635          * moment. So to make sure the plane gets truly disabled, disable
4636          * first the self-refresh mode. The self-refresh enable bit in turn
4637          * will be checked/applied by the HW only at the next frame start
4638          * event which is after the vblank start event, so we need to have a
4639          * wait-for-vblank between disabling the plane and the pipe.
4640          */
4641         if (HAS_GMCH_DISPLAY(dev)) {
4642                 intel_set_memory_cxsr(dev_priv, false);
4643                 dev_priv->wm.vlv.cxsr = false;
4644                 intel_wait_for_vblank(dev, pipe);
4645         }
4646 }
4647
4648 static void intel_post_plane_update(struct intel_crtc_state *old_crtc_state)
4649 {
4650         struct intel_crtc *crtc = to_intel_crtc(old_crtc_state->base.crtc);
4651         struct drm_atomic_state *old_state = old_crtc_state->base.state;
4652         struct intel_crtc_state *pipe_config =
4653                 to_intel_crtc_state(crtc->base.state);
4654         struct drm_plane *primary = crtc->base.primary;
4655         struct drm_plane_state *old_pri_state =
4656                 drm_atomic_get_existing_plane_state(old_state, primary);
4657
4658         intel_frontbuffer_flip(to_i915(crtc->base.dev), pipe_config->fb_bits);
4659
4660         crtc->wm.cxsr_allowed = true;
4661
4662         if (pipe_config->update_wm_post && pipe_config->base.active)
4663                 intel_update_watermarks(&crtc->base);
4664
4665         if (old_pri_state) {
4666                 struct intel_plane_state *primary_state =
4667                         to_intel_plane_state(primary->state);
4668                 struct intel_plane_state *old_primary_state =
4669                         to_intel_plane_state(old_pri_state);
4670
4671                 intel_fbc_post_update(crtc);
4672
4673                 if (primary_state->visible &&
4674                     (needs_modeset(&pipe_config->base) ||
4675                      !old_primary_state->visible))
4676                         intel_post_enable_primary(&crtc->base);
4677         }
4678 }
4679
4680 static void intel_pre_plane_update(struct intel_crtc_state *old_crtc_state)
4681 {
4682         struct intel_crtc *crtc = to_intel_crtc(old_crtc_state->base.crtc);
4683         struct drm_device *dev = crtc->base.dev;
4684         struct drm_i915_private *dev_priv = to_i915(dev);
4685         struct intel_crtc_state *pipe_config =
4686                 to_intel_crtc_state(crtc->base.state);
4687         struct drm_atomic_state *old_state = old_crtc_state->base.state;
4688         struct drm_plane *primary = crtc->base.primary;
4689         struct drm_plane_state *old_pri_state =
4690                 drm_atomic_get_existing_plane_state(old_state, primary);
4691         bool modeset = needs_modeset(&pipe_config->base);
4692
4693         if (old_pri_state) {
4694                 struct intel_plane_state *primary_state =
4695                         to_intel_plane_state(primary->state);
4696                 struct intel_plane_state *old_primary_state =
4697                         to_intel_plane_state(old_pri_state);
4698
4699                 intel_fbc_pre_update(crtc, pipe_config, primary_state);
4700
4701                 if (old_primary_state->visible &&
4702                     (modeset || !primary_state->visible))
4703                         intel_pre_disable_primary(&crtc->base);
4704         }
4705
4706         if (pipe_config->disable_cxsr && HAS_GMCH_DISPLAY(dev)) {
4707                 crtc->wm.cxsr_allowed = false;
4708
4709                 /*
4710                  * Vblank time updates from the shadow to live plane control register
4711                  * are blocked if the memory self-refresh mode is active at that
4712                  * moment. So to make sure the plane gets truly disabled, disable
4713                  * first the self-refresh mode. The self-refresh enable bit in turn
4714                  * will be checked/applied by the HW only at the next frame start
4715                  * event which is after the vblank start event, so we need to have a
4716                  * wait-for-vblank between disabling the plane and the pipe.
4717                  */
4718                 if (old_crtc_state->base.active) {
4719                         intel_set_memory_cxsr(dev_priv, false);
4720                         dev_priv->wm.vlv.cxsr = false;
4721                         intel_wait_for_vblank(dev, crtc->pipe);
4722                 }
4723         }
4724
4725         /*
4726          * IVB workaround: must disable low power watermarks for at least
4727          * one frame before enabling scaling.  LP watermarks can be re-enabled
4728          * when scaling is disabled.
4729          *
4730          * WaCxSRDisabledForSpriteScaling:ivb
4731          */
4732         if (pipe_config->disable_lp_wm) {
4733                 ilk_disable_lp_wm(dev);
4734                 intel_wait_for_vblank(dev, crtc->pipe);
4735         }
4736
4737         /*
4738          * If we're doing a modeset, we're done.  No need to do any pre-vblank
4739          * watermark programming here.
4740          */
4741         if (needs_modeset(&pipe_config->base))
4742                 return;
4743
4744         /*
4745          * For platforms that support atomic watermarks, program the
4746          * 'intermediate' watermarks immediately.  On pre-gen9 platforms, these
4747          * will be the intermediate values that are safe for both pre- and
4748          * post- vblank; when vblank happens, the 'active' values will be set
4749          * to the final 'target' values and we'll do this again to get the
4750          * optimal watermarks.  For gen9+ platforms, the values we program here
4751          * will be the final target values which will get automatically latched
4752          * at vblank time; no further programming will be necessary.
4753          *
4754          * If a platform hasn't been transitioned to atomic watermarks yet,
4755          * we'll continue to update watermarks the old way, if flags tell
4756          * us to.
4757          */
4758         if (dev_priv->display.initial_watermarks != NULL)
4759                 dev_priv->display.initial_watermarks(pipe_config);
4760         else if (pipe_config->update_wm_pre)
4761                 intel_update_watermarks(&crtc->base);
4762 }
4763
4764 static void intel_crtc_disable_planes(struct drm_crtc *crtc, unsigned plane_mask)
4765 {
4766         struct drm_device *dev = crtc->dev;
4767         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4768         struct drm_plane *p;
4769         int pipe = intel_crtc->pipe;
4770
4771         intel_crtc_dpms_overlay_disable(intel_crtc);
4772
4773         drm_for_each_plane_mask(p, dev, plane_mask)
4774                 to_intel_plane(p)->disable_plane(p, crtc);
4775
4776         /*
4777          * FIXME: Once we grow proper nuclear flip support out of this we need
4778          * to compute the mask of flip planes precisely. For the time being
4779          * consider this a flip to a NULL plane.
4780          */
4781         intel_frontbuffer_flip(to_i915(dev), INTEL_FRONTBUFFER_ALL_MASK(pipe));
4782 }
4783
4784 static void ironlake_crtc_enable(struct drm_crtc *crtc)
4785 {
4786         struct drm_device *dev = crtc->dev;
4787         struct drm_i915_private *dev_priv = to_i915(dev);
4788         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4789         struct intel_encoder *encoder;
4790         int pipe = intel_crtc->pipe;
4791         struct intel_crtc_state *pipe_config =
4792                 to_intel_crtc_state(crtc->state);
4793
4794         if (WARN_ON(intel_crtc->active))
4795                 return;
4796
4797         /*
4798          * Sometimes spurious CPU pipe underruns happen during FDI
4799          * training, at least with VGA+HDMI cloning. Suppress them.
4800          *
4801          * On ILK we get an occasional spurious CPU pipe underruns
4802          * between eDP port A enable and vdd enable. Also PCH port
4803          * enable seems to result in the occasional CPU pipe underrun.
4804          *
4805          * Spurious PCH underruns also occur during PCH enabling.
4806          */
4807         if (intel_crtc->config->has_pch_encoder || IS_GEN5(dev_priv))
4808                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, false);
4809         if (intel_crtc->config->has_pch_encoder)
4810                 intel_set_pch_fifo_underrun_reporting(dev_priv, pipe, false);
4811
4812         if (intel_crtc->config->has_pch_encoder)
4813                 intel_prepare_shared_dpll(intel_crtc);
4814
4815         if (intel_crtc_has_dp_encoder(intel_crtc->config))
4816                 intel_dp_set_m_n(intel_crtc, M1_N1);
4817
4818         intel_set_pipe_timings(intel_crtc);
4819         intel_set_pipe_src_size(intel_crtc);
4820
4821         if (intel_crtc->config->has_pch_encoder) {
4822                 intel_cpu_transcoder_set_m_n(intel_crtc,
4823                                      &intel_crtc->config->fdi_m_n, NULL);
4824         }
4825
4826         ironlake_set_pipeconf(crtc);
4827
4828         intel_crtc->active = true;
4829
4830         for_each_encoder_on_crtc(dev, crtc, encoder)
4831                 if (encoder->pre_enable)
4832                         encoder->pre_enable(encoder);
4833
4834         if (intel_crtc->config->has_pch_encoder) {
4835                 /* Note: FDI PLL enabling _must_ be done before we enable the
4836                  * cpu pipes, hence this is separate from all the other fdi/pch
4837                  * enabling. */
4838                 ironlake_fdi_pll_enable(intel_crtc);
4839         } else {
4840                 assert_fdi_tx_disabled(dev_priv, pipe);
4841                 assert_fdi_rx_disabled(dev_priv, pipe);
4842         }
4843
4844         ironlake_pfit_enable(intel_crtc);
4845
4846         /*
4847          * On ILK+ LUT must be loaded before the pipe is running but with
4848          * clocks enabled
4849          */
4850         intel_color_load_luts(&pipe_config->base);
4851
4852         if (dev_priv->display.initial_watermarks != NULL)
4853                 dev_priv->display.initial_watermarks(intel_crtc->config);
4854         intel_enable_pipe(intel_crtc);
4855
4856         if (intel_crtc->config->has_pch_encoder)
4857                 ironlake_pch_enable(crtc);
4858
4859         assert_vblank_disabled(crtc);
4860         drm_crtc_vblank_on(crtc);
4861
4862         for_each_encoder_on_crtc(dev, crtc, encoder)
4863                 encoder->enable(encoder);
4864
4865         if (HAS_PCH_CPT(dev))
4866                 cpt_verify_modeset(dev, intel_crtc->pipe);
4867
4868         /* Must wait for vblank to avoid spurious PCH FIFO underruns */
4869         if (intel_crtc->config->has_pch_encoder)
4870                 intel_wait_for_vblank(dev, pipe);
4871         intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
4872         intel_set_pch_fifo_underrun_reporting(dev_priv, pipe, true);
4873 }
4874
4875 /* IPS only exists on ULT machines and is tied to pipe A. */
4876 static bool hsw_crtc_supports_ips(struct intel_crtc *crtc)
4877 {
4878         return HAS_IPS(crtc->base.dev) && crtc->pipe == PIPE_A;
4879 }
4880
4881 static void haswell_crtc_enable(struct drm_crtc *crtc)
4882 {
4883         struct drm_device *dev = crtc->dev;
4884         struct drm_i915_private *dev_priv = to_i915(dev);
4885         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4886         struct intel_encoder *encoder;
4887         int pipe = intel_crtc->pipe, hsw_workaround_pipe;
4888         enum transcoder cpu_transcoder = intel_crtc->config->cpu_transcoder;
4889         struct intel_crtc_state *pipe_config =
4890                 to_intel_crtc_state(crtc->state);
4891
4892         if (WARN_ON(intel_crtc->active))
4893                 return;
4894
4895         if (intel_crtc->config->has_pch_encoder)
4896                 intel_set_pch_fifo_underrun_reporting(dev_priv, TRANSCODER_A,
4897                                                       false);
4898
4899         for_each_encoder_on_crtc(dev, crtc, encoder)
4900                 if (encoder->pre_pll_enable)
4901                         encoder->pre_pll_enable(encoder);
4902
4903         if (intel_crtc->config->shared_dpll)
4904                 intel_enable_shared_dpll(intel_crtc);
4905
4906         if (intel_crtc_has_dp_encoder(intel_crtc->config))
4907                 intel_dp_set_m_n(intel_crtc, M1_N1);
4908
4909         if (!transcoder_is_dsi(cpu_transcoder))
4910                 intel_set_pipe_timings(intel_crtc);
4911
4912         intel_set_pipe_src_size(intel_crtc);
4913
4914         if (cpu_transcoder != TRANSCODER_EDP &&
4915             !transcoder_is_dsi(cpu_transcoder)) {
4916                 I915_WRITE(PIPE_MULT(cpu_transcoder),
4917                            intel_crtc->config->pixel_multiplier - 1);
4918         }
4919
4920         if (intel_crtc->config->has_pch_encoder) {
4921                 intel_cpu_transcoder_set_m_n(intel_crtc,
4922                                      &intel_crtc->config->fdi_m_n, NULL);
4923         }
4924
4925         if (!transcoder_is_dsi(cpu_transcoder))
4926                 haswell_set_pipeconf(crtc);
4927
4928         haswell_set_pipemisc(crtc);
4929
4930         intel_color_set_csc(&pipe_config->base);
4931
4932         intel_crtc->active = true;
4933
4934         if (intel_crtc->config->has_pch_encoder)
4935                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, false);
4936         else
4937                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
4938
4939         for_each_encoder_on_crtc(dev, crtc, encoder) {
4940                 if (encoder->pre_enable)
4941                         encoder->pre_enable(encoder);
4942         }
4943
4944         if (intel_crtc->config->has_pch_encoder)
4945                 dev_priv->display.fdi_link_train(crtc);
4946
4947         if (!transcoder_is_dsi(cpu_transcoder))
4948                 intel_ddi_enable_pipe_clock(intel_crtc);
4949
4950         if (INTEL_INFO(dev)->gen >= 9)
4951                 skylake_pfit_enable(intel_crtc);
4952         else
4953                 ironlake_pfit_enable(intel_crtc);
4954
4955         /*
4956          * On ILK+ LUT must be loaded before the pipe is running but with
4957          * clocks enabled
4958          */
4959         intel_color_load_luts(&pipe_config->base);
4960
4961         intel_ddi_set_pipe_settings(crtc);
4962         if (!transcoder_is_dsi(cpu_transcoder))
4963                 intel_ddi_enable_transcoder_func(crtc);
4964
4965         if (dev_priv->display.initial_watermarks != NULL)
4966                 dev_priv->display.initial_watermarks(pipe_config);
4967         else
4968                 intel_update_watermarks(crtc);
4969
4970         /* XXX: Do the pipe assertions at the right place for BXT DSI. */
4971         if (!transcoder_is_dsi(cpu_transcoder))
4972                 intel_enable_pipe(intel_crtc);
4973
4974         if (intel_crtc->config->has_pch_encoder)
4975                 lpt_pch_enable(crtc);
4976
4977         if (intel_crtc->config->dp_encoder_is_mst)
4978                 intel_ddi_set_vc_payload_alloc(crtc, true);
4979
4980         assert_vblank_disabled(crtc);
4981         drm_crtc_vblank_on(crtc);
4982
4983         for_each_encoder_on_crtc(dev, crtc, encoder) {
4984                 encoder->enable(encoder);
4985                 intel_opregion_notify_encoder(encoder, true);
4986         }
4987
4988         if (intel_crtc->config->has_pch_encoder) {
4989                 intel_wait_for_vblank(dev, pipe);
4990                 intel_wait_for_vblank(dev, pipe);
4991                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
4992                 intel_set_pch_fifo_underrun_reporting(dev_priv, TRANSCODER_A,
4993                                                       true);
4994         }
4995
4996         /* If we change the relative order between pipe/planes enabling, we need
4997          * to change the workaround. */
4998         hsw_workaround_pipe = pipe_config->hsw_workaround_pipe;
4999         if (IS_HASWELL(dev) && hsw_workaround_pipe != INVALID_PIPE) {
5000                 intel_wait_for_vblank(dev, hsw_workaround_pipe);
5001                 intel_wait_for_vblank(dev, hsw_workaround_pipe);
5002         }
5003 }
5004
5005 static void ironlake_pfit_disable(struct intel_crtc *crtc, bool force)
5006 {
5007         struct drm_device *dev = crtc->base.dev;
5008         struct drm_i915_private *dev_priv = to_i915(dev);
5009         int pipe = crtc->pipe;
5010
5011         /* To avoid upsetting the power well on haswell only disable the pfit if
5012          * it's in use. The hw state code will make sure we get this right. */
5013         if (force || crtc->config->pch_pfit.enabled) {
5014                 I915_WRITE(PF_CTL(pipe), 0);
5015                 I915_WRITE(PF_WIN_POS(pipe), 0);
5016                 I915_WRITE(PF_WIN_SZ(pipe), 0);
5017         }
5018 }
5019
5020 static void ironlake_crtc_disable(struct drm_crtc *crtc)
5021 {
5022         struct drm_device *dev = crtc->dev;
5023         struct drm_i915_private *dev_priv = to_i915(dev);
5024         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5025         struct intel_encoder *encoder;
5026         int pipe = intel_crtc->pipe;
5027
5028         /*
5029          * Sometimes spurious CPU pipe underruns happen when the
5030          * pipe is already disabled, but FDI RX/TX is still enabled.
5031          * Happens at least with VGA+HDMI cloning. Suppress them.
5032          */
5033         if (intel_crtc->config->has_pch_encoder) {
5034                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, false);
5035                 intel_set_pch_fifo_underrun_reporting(dev_priv, pipe, false);
5036         }
5037
5038         for_each_encoder_on_crtc(dev, crtc, encoder)
5039                 encoder->disable(encoder);
5040
5041         drm_crtc_vblank_off(crtc);
5042         assert_vblank_disabled(crtc);
5043
5044         intel_disable_pipe(intel_crtc);
5045
5046         ironlake_pfit_disable(intel_crtc, false);
5047
5048         if (intel_crtc->config->has_pch_encoder)
5049                 ironlake_fdi_disable(crtc);
5050
5051         for_each_encoder_on_crtc(dev, crtc, encoder)
5052                 if (encoder->post_disable)
5053                         encoder->post_disable(encoder);
5054
5055         if (intel_crtc->config->has_pch_encoder) {
5056                 ironlake_disable_pch_transcoder(dev_priv, pipe);
5057
5058                 if (HAS_PCH_CPT(dev)) {
5059                         i915_reg_t reg;
5060                         u32 temp;
5061
5062                         /* disable TRANS_DP_CTL */
5063                         reg = TRANS_DP_CTL(pipe);
5064                         temp = I915_READ(reg);
5065                         temp &= ~(TRANS_DP_OUTPUT_ENABLE |
5066                                   TRANS_DP_PORT_SEL_MASK);
5067                         temp |= TRANS_DP_PORT_SEL_NONE;
5068                         I915_WRITE(reg, temp);
5069
5070                         /* disable DPLL_SEL */
5071                         temp = I915_READ(PCH_DPLL_SEL);
5072                         temp &= ~(TRANS_DPLL_ENABLE(pipe) | TRANS_DPLLB_SEL(pipe));
5073                         I915_WRITE(PCH_DPLL_SEL, temp);
5074                 }
5075
5076                 ironlake_fdi_pll_disable(intel_crtc);
5077         }
5078
5079         intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
5080         intel_set_pch_fifo_underrun_reporting(dev_priv, pipe, true);
5081 }
5082
5083 static void haswell_crtc_disable(struct drm_crtc *crtc)
5084 {
5085         struct drm_device *dev = crtc->dev;
5086         struct drm_i915_private *dev_priv = to_i915(dev);
5087         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5088         struct intel_encoder *encoder;
5089         enum transcoder cpu_transcoder = intel_crtc->config->cpu_transcoder;
5090
5091         if (intel_crtc->config->has_pch_encoder)
5092                 intel_set_pch_fifo_underrun_reporting(dev_priv, TRANSCODER_A,
5093                                                       false);
5094
5095         for_each_encoder_on_crtc(dev, crtc, encoder) {
5096                 intel_opregion_notify_encoder(encoder, false);
5097                 encoder->disable(encoder);
5098         }
5099
5100         drm_crtc_vblank_off(crtc);
5101         assert_vblank_disabled(crtc);
5102
5103         /* XXX: Do the pipe assertions at the right place for BXT DSI. */
5104         if (!transcoder_is_dsi(cpu_transcoder))
5105                 intel_disable_pipe(intel_crtc);
5106
5107         if (intel_crtc->config->dp_encoder_is_mst)
5108                 intel_ddi_set_vc_payload_alloc(crtc, false);
5109
5110         if (!transcoder_is_dsi(cpu_transcoder))
5111                 intel_ddi_disable_transcoder_func(dev_priv, cpu_transcoder);
5112
5113         if (INTEL_INFO(dev)->gen >= 9)
5114                 skylake_scaler_disable(intel_crtc);
5115         else
5116                 ironlake_pfit_disable(intel_crtc, false);
5117
5118         if (!transcoder_is_dsi(cpu_transcoder))
5119                 intel_ddi_disable_pipe_clock(intel_crtc);
5120
5121         for_each_encoder_on_crtc(dev, crtc, encoder)
5122                 if (encoder->post_disable)
5123                         encoder->post_disable(encoder);
5124
5125         if (intel_crtc->config->has_pch_encoder) {
5126                 lpt_disable_pch_transcoder(dev_priv);
5127                 lpt_disable_iclkip(dev_priv);
5128                 intel_ddi_fdi_disable(crtc);
5129
5130                 intel_set_pch_fifo_underrun_reporting(dev_priv, TRANSCODER_A,
5131                                                       true);
5132         }
5133 }
5134
5135 static void i9xx_pfit_enable(struct intel_crtc *crtc)
5136 {
5137         struct drm_device *dev = crtc->base.dev;
5138         struct drm_i915_private *dev_priv = to_i915(dev);
5139         struct intel_crtc_state *pipe_config = crtc->config;
5140
5141         if (!pipe_config->gmch_pfit.control)
5142                 return;
5143
5144         /*
5145          * The panel fitter should only be adjusted whilst the pipe is disabled,
5146          * according to register description and PRM.
5147          */
5148         WARN_ON(I915_READ(PFIT_CONTROL) & PFIT_ENABLE);
5149         assert_pipe_disabled(dev_priv, crtc->pipe);
5150
5151         I915_WRITE(PFIT_PGM_RATIOS, pipe_config->gmch_pfit.pgm_ratios);
5152         I915_WRITE(PFIT_CONTROL, pipe_config->gmch_pfit.control);
5153
5154         /* Border color in case we don't scale up to the full screen. Black by
5155          * default, change to something else for debugging. */
5156         I915_WRITE(BCLRPAT(crtc->pipe), 0);
5157 }
5158
5159 static enum intel_display_power_domain port_to_power_domain(enum port port)
5160 {
5161         switch (port) {
5162         case PORT_A:
5163                 return POWER_DOMAIN_PORT_DDI_A_LANES;
5164         case PORT_B:
5165                 return POWER_DOMAIN_PORT_DDI_B_LANES;
5166         case PORT_C:
5167                 return POWER_DOMAIN_PORT_DDI_C_LANES;
5168         case PORT_D:
5169                 return POWER_DOMAIN_PORT_DDI_D_LANES;
5170         case PORT_E:
5171                 return POWER_DOMAIN_PORT_DDI_E_LANES;
5172         default:
5173                 MISSING_CASE(port);
5174                 return POWER_DOMAIN_PORT_OTHER;
5175         }
5176 }
5177
5178 static enum intel_display_power_domain port_to_aux_power_domain(enum port port)
5179 {
5180         switch (port) {
5181         case PORT_A:
5182                 return POWER_DOMAIN_AUX_A;
5183         case PORT_B:
5184                 return POWER_DOMAIN_AUX_B;
5185         case PORT_C:
5186                 return POWER_DOMAIN_AUX_C;
5187         case PORT_D:
5188                 return POWER_DOMAIN_AUX_D;
5189         case PORT_E:
5190                 /* FIXME: Check VBT for actual wiring of PORT E */
5191                 return POWER_DOMAIN_AUX_D;
5192         default:
5193                 MISSING_CASE(port);
5194                 return POWER_DOMAIN_AUX_A;
5195         }
5196 }
5197
5198 enum intel_display_power_domain
5199 intel_display_port_power_domain(struct intel_encoder *intel_encoder)
5200 {
5201         struct drm_device *dev = intel_encoder->base.dev;
5202         struct intel_digital_port *intel_dig_port;
5203
5204         switch (intel_encoder->type) {
5205         case INTEL_OUTPUT_UNKNOWN:
5206                 /* Only DDI platforms should ever use this output type */
5207                 WARN_ON_ONCE(!HAS_DDI(dev));
5208         case INTEL_OUTPUT_DP:
5209         case INTEL_OUTPUT_HDMI:
5210         case INTEL_OUTPUT_EDP:
5211                 intel_dig_port = enc_to_dig_port(&intel_encoder->base);
5212                 return port_to_power_domain(intel_dig_port->port);
5213         case INTEL_OUTPUT_DP_MST:
5214                 intel_dig_port = enc_to_mst(&intel_encoder->base)->primary;
5215                 return port_to_power_domain(intel_dig_port->port);
5216         case INTEL_OUTPUT_ANALOG:
5217                 return POWER_DOMAIN_PORT_CRT;
5218         case INTEL_OUTPUT_DSI:
5219                 return POWER_DOMAIN_PORT_DSI;
5220         default:
5221                 return POWER_DOMAIN_PORT_OTHER;
5222         }
5223 }
5224
5225 enum intel_display_power_domain
5226 intel_display_port_aux_power_domain(struct intel_encoder *intel_encoder)
5227 {
5228         struct drm_device *dev = intel_encoder->base.dev;
5229         struct intel_digital_port *intel_dig_port;
5230
5231         switch (intel_encoder->type) {
5232         case INTEL_OUTPUT_UNKNOWN:
5233         case INTEL_OUTPUT_HDMI:
5234                 /*
5235                  * Only DDI platforms should ever use these output types.
5236                  * We can get here after the HDMI detect code has already set
5237                  * the type of the shared encoder. Since we can't be sure
5238                  * what's the status of the given connectors, play safe and
5239                  * run the DP detection too.
5240                  */
5241                 WARN_ON_ONCE(!HAS_DDI(dev));
5242         case INTEL_OUTPUT_DP:
5243         case INTEL_OUTPUT_EDP:
5244                 intel_dig_port = enc_to_dig_port(&intel_encoder->base);
5245                 return port_to_aux_power_domain(intel_dig_port->port);
5246         case INTEL_OUTPUT_DP_MST:
5247                 intel_dig_port = enc_to_mst(&intel_encoder->base)->primary;
5248                 return port_to_aux_power_domain(intel_dig_port->port);
5249         default:
5250                 MISSING_CASE(intel_encoder->type);
5251                 return POWER_DOMAIN_AUX_A;
5252         }
5253 }
5254
5255 static unsigned long get_crtc_power_domains(struct drm_crtc *crtc,
5256                                             struct intel_crtc_state *crtc_state)
5257 {
5258         struct drm_device *dev = crtc->dev;
5259         struct drm_encoder *encoder;
5260         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5261         enum pipe pipe = intel_crtc->pipe;
5262         unsigned long mask;
5263         enum transcoder transcoder = crtc_state->cpu_transcoder;
5264
5265         if (!crtc_state->base.active)
5266                 return 0;
5267
5268         mask = BIT(POWER_DOMAIN_PIPE(pipe));
5269         mask |= BIT(POWER_DOMAIN_TRANSCODER(transcoder));
5270         if (crtc_state->pch_pfit.enabled ||
5271             crtc_state->pch_pfit.force_thru)
5272                 mask |= BIT(POWER_DOMAIN_PIPE_PANEL_FITTER(pipe));
5273
5274         drm_for_each_encoder_mask(encoder, dev, crtc_state->base.encoder_mask) {
5275                 struct intel_encoder *intel_encoder = to_intel_encoder(encoder);
5276
5277                 mask |= BIT(intel_display_port_power_domain(intel_encoder));
5278         }
5279
5280         if (crtc_state->shared_dpll)
5281                 mask |= BIT(POWER_DOMAIN_PLLS);
5282
5283         return mask;
5284 }
5285
5286 static unsigned long
5287 modeset_get_crtc_power_domains(struct drm_crtc *crtc,
5288                                struct intel_crtc_state *crtc_state)
5289 {
5290         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
5291         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5292         enum intel_display_power_domain domain;
5293         unsigned long domains, new_domains, old_domains;
5294
5295         old_domains = intel_crtc->enabled_power_domains;
5296         intel_crtc->enabled_power_domains = new_domains =
5297                 get_crtc_power_domains(crtc, crtc_state);
5298
5299         domains = new_domains & ~old_domains;
5300
5301         for_each_power_domain(domain, domains)
5302                 intel_display_power_get(dev_priv, domain);
5303
5304         return old_domains & ~new_domains;
5305 }
5306
5307 static void modeset_put_power_domains(struct drm_i915_private *dev_priv,
5308                                       unsigned long domains)
5309 {
5310         enum intel_display_power_domain domain;
5311
5312         for_each_power_domain(domain, domains)
5313                 intel_display_power_put(dev_priv, domain);
5314 }
5315
5316 static int intel_compute_max_dotclk(struct drm_i915_private *dev_priv)
5317 {
5318         int max_cdclk_freq = dev_priv->max_cdclk_freq;
5319
5320         if (INTEL_INFO(dev_priv)->gen >= 9 ||
5321             IS_HASWELL(dev_priv) || IS_BROADWELL(dev_priv))
5322                 return max_cdclk_freq;
5323         else if (IS_CHERRYVIEW(dev_priv))
5324                 return max_cdclk_freq*95/100;
5325         else if (INTEL_INFO(dev_priv)->gen < 4)
5326                 return 2*max_cdclk_freq*90/100;
5327         else
5328                 return max_cdclk_freq*90/100;
5329 }
5330
5331 static int skl_calc_cdclk(int max_pixclk, int vco);
5332
5333 static void intel_update_max_cdclk(struct drm_device *dev)
5334 {
5335         struct drm_i915_private *dev_priv = to_i915(dev);
5336
5337         if (IS_SKYLAKE(dev) || IS_KABYLAKE(dev)) {
5338                 u32 limit = I915_READ(SKL_DFSM) & SKL_DFSM_CDCLK_LIMIT_MASK;
5339                 int max_cdclk, vco;
5340
5341                 vco = dev_priv->skl_preferred_vco_freq;
5342                 WARN_ON(vco != 8100000 && vco != 8640000);
5343
5344                 /*
5345                  * Use the lower (vco 8640) cdclk values as a
5346                  * first guess. skl_calc_cdclk() will correct it
5347                  * if the preferred vco is 8100 instead.
5348                  */
5349                 if (limit == SKL_DFSM_CDCLK_LIMIT_675)
5350                         max_cdclk = 617143;
5351                 else if (limit == SKL_DFSM_CDCLK_LIMIT_540)
5352                         max_cdclk = 540000;
5353                 else if (limit == SKL_DFSM_CDCLK_LIMIT_450)
5354                         max_cdclk = 432000;
5355                 else
5356                         max_cdclk = 308571;
5357
5358                 dev_priv->max_cdclk_freq = skl_calc_cdclk(max_cdclk, vco);
5359         } else if (IS_BROXTON(dev)) {
5360                 dev_priv->max_cdclk_freq = 624000;
5361         } else if (IS_BROADWELL(dev))  {
5362                 /*
5363                  * FIXME with extra cooling we can allow
5364                  * 540 MHz for ULX and 675 Mhz for ULT.
5365                  * How can we know if extra cooling is
5366                  * available? PCI ID, VTB, something else?
5367                  */
5368                 if (I915_READ(FUSE_STRAP) & HSW_CDCLK_LIMIT)
5369                         dev_priv->max_cdclk_freq = 450000;
5370                 else if (IS_BDW_ULX(dev))
5371                         dev_priv->max_cdclk_freq = 450000;
5372                 else if (IS_BDW_ULT(dev))
5373                         dev_priv->max_cdclk_freq = 540000;
5374                 else
5375                         dev_priv->max_cdclk_freq = 675000;
5376         } else if (IS_CHERRYVIEW(dev)) {
5377                 dev_priv->max_cdclk_freq = 320000;
5378         } else if (IS_VALLEYVIEW(dev)) {
5379                 dev_priv->max_cdclk_freq = 400000;
5380         } else {
5381                 /* otherwise assume cdclk is fixed */
5382                 dev_priv->max_cdclk_freq = dev_priv->cdclk_freq;
5383         }
5384
5385         dev_priv->max_dotclk_freq = intel_compute_max_dotclk(dev_priv);
5386
5387         DRM_DEBUG_DRIVER("Max CD clock rate: %d kHz\n",
5388                          dev_priv->max_cdclk_freq);
5389
5390         DRM_DEBUG_DRIVER("Max dotclock rate: %d kHz\n",
5391                          dev_priv->max_dotclk_freq);
5392 }
5393
5394 static void intel_update_cdclk(struct drm_device *dev)
5395 {
5396         struct drm_i915_private *dev_priv = to_i915(dev);
5397
5398         dev_priv->cdclk_freq = dev_priv->display.get_display_clock_speed(dev);
5399
5400         if (INTEL_GEN(dev_priv) >= 9)
5401                 DRM_DEBUG_DRIVER("Current CD clock rate: %d kHz, VCO: %d kHz, ref: %d kHz\n",
5402                                  dev_priv->cdclk_freq, dev_priv->cdclk_pll.vco,
5403                                  dev_priv->cdclk_pll.ref);
5404         else
5405                 DRM_DEBUG_DRIVER("Current CD clock rate: %d kHz\n",
5406                                  dev_priv->cdclk_freq);
5407
5408         /*
5409          * 9:0 CMBUS [sic] CDCLK frequency (cdfreq):
5410          * Programmng [sic] note: bit[9:2] should be programmed to the number
5411          * of cdclk that generates 4MHz reference clock freq which is used to
5412          * generate GMBus clock. This will vary with the cdclk freq.
5413          */
5414         if (IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv))
5415                 I915_WRITE(GMBUSFREQ_VLV, DIV_ROUND_UP(dev_priv->cdclk_freq, 1000));
5416 }
5417
5418 /* convert from kHz to .1 fixpoint MHz with -1MHz offset */
5419 static int skl_cdclk_decimal(int cdclk)
5420 {
5421         return DIV_ROUND_CLOSEST(cdclk - 1000, 500);
5422 }
5423
5424 static int bxt_de_pll_vco(struct drm_i915_private *dev_priv, int cdclk)
5425 {
5426         int ratio;
5427
5428         if (cdclk == dev_priv->cdclk_pll.ref)
5429                 return 0;
5430
5431         switch (cdclk) {
5432         default:
5433                 MISSING_CASE(cdclk);
5434         case 144000:
5435         case 288000:
5436         case 384000:
5437         case 576000:
5438                 ratio = 60;
5439                 break;
5440         case 624000:
5441                 ratio = 65;
5442                 break;
5443         }
5444
5445         return dev_priv->cdclk_pll.ref * ratio;
5446 }
5447
5448 static void bxt_de_pll_disable(struct drm_i915_private *dev_priv)
5449 {
5450         I915_WRITE(BXT_DE_PLL_ENABLE, 0);
5451
5452         /* Timeout 200us */
5453         if (intel_wait_for_register(dev_priv,
5454                                     BXT_DE_PLL_ENABLE, BXT_DE_PLL_LOCK, 0,
5455                                     1))
5456                 DRM_ERROR("timeout waiting for DE PLL unlock\n");
5457
5458         dev_priv->cdclk_pll.vco = 0;
5459 }
5460
5461 static void bxt_de_pll_enable(struct drm_i915_private *dev_priv, int vco)
5462 {
5463         int ratio = DIV_ROUND_CLOSEST(vco, dev_priv->cdclk_pll.ref);
5464         u32 val;
5465
5466         val = I915_READ(BXT_DE_PLL_CTL);
5467         val &= ~BXT_DE_PLL_RATIO_MASK;
5468         val |= BXT_DE_PLL_RATIO(ratio);
5469         I915_WRITE(BXT_DE_PLL_CTL, val);
5470
5471         I915_WRITE(BXT_DE_PLL_ENABLE, BXT_DE_PLL_PLL_ENABLE);
5472
5473         /* Timeout 200us */
5474         if (intel_wait_for_register(dev_priv,
5475                                     BXT_DE_PLL_ENABLE,
5476                                     BXT_DE_PLL_LOCK,
5477                                     BXT_DE_PLL_LOCK,
5478                                     1))
5479                 DRM_ERROR("timeout waiting for DE PLL lock\n");
5480
5481         dev_priv->cdclk_pll.vco = vco;
5482 }
5483
5484 static void bxt_set_cdclk(struct drm_i915_private *dev_priv, int cdclk)
5485 {
5486         u32 val, divider;
5487         int vco, ret;
5488
5489         vco = bxt_de_pll_vco(dev_priv, cdclk);
5490
5491         DRM_DEBUG_DRIVER("Changing CDCLK to %d kHz (VCO %d kHz)\n", cdclk, vco);
5492
5493         /* cdclk = vco / 2 / div{1,1.5,2,4} */
5494         switch (DIV_ROUND_CLOSEST(vco, cdclk)) {
5495         case 8:
5496                 divider = BXT_CDCLK_CD2X_DIV_SEL_4;
5497                 break;
5498         case 4:
5499                 divider = BXT_CDCLK_CD2X_DIV_SEL_2;
5500                 break;
5501         case 3:
5502                 divider = BXT_CDCLK_CD2X_DIV_SEL_1_5;
5503                 break;
5504         case 2:
5505                 divider = BXT_CDCLK_CD2X_DIV_SEL_1;
5506                 break;
5507         default:
5508                 WARN_ON(cdclk != dev_priv->cdclk_pll.ref);
5509                 WARN_ON(vco != 0);
5510
5511                 divider = BXT_CDCLK_CD2X_DIV_SEL_1;
5512                 break;
5513         }
5514
5515         /* Inform power controller of upcoming frequency change */
5516         mutex_lock(&dev_priv->rps.hw_lock);
5517         ret = sandybridge_pcode_write(dev_priv, HSW_PCODE_DE_WRITE_FREQ_REQ,
5518                                       0x80000000);
5519         mutex_unlock(&dev_priv->rps.hw_lock);
5520
5521         if (ret) {
5522                 DRM_ERROR("PCode CDCLK freq change notify failed (err %d, freq %d)\n",
5523                           ret, cdclk);
5524                 return;
5525         }
5526
5527         if (dev_priv->cdclk_pll.vco != 0 &&
5528             dev_priv->cdclk_pll.vco != vco)
5529                 bxt_de_pll_disable(dev_priv);
5530
5531         if (dev_priv->cdclk_pll.vco != vco)
5532                 bxt_de_pll_enable(dev_priv, vco);
5533
5534         val = divider | skl_cdclk_decimal(cdclk);
5535         /*
5536          * FIXME if only the cd2x divider needs changing, it could be done
5537          * without shutting off the pipe (if only one pipe is active).
5538          */
5539         val |= BXT_CDCLK_CD2X_PIPE_NONE;
5540         /*
5541          * Disable SSA Precharge when CD clock frequency < 500 MHz,
5542          * enable otherwise.
5543          */
5544         if (cdclk >= 500000)
5545                 val |= BXT_CDCLK_SSA_PRECHARGE_ENABLE;
5546         I915_WRITE(CDCLK_CTL, val);
5547
5548         mutex_lock(&dev_priv->rps.hw_lock);
5549         ret = sandybridge_pcode_write(dev_priv, HSW_PCODE_DE_WRITE_FREQ_REQ,
5550                                       DIV_ROUND_UP(cdclk, 25000));
5551         mutex_unlock(&dev_priv->rps.hw_lock);
5552
5553         if (ret) {
5554                 DRM_ERROR("PCode CDCLK freq set failed, (err %d, freq %d)\n",
5555                           ret, cdclk);
5556                 return;
5557         }
5558
5559         intel_update_cdclk(&dev_priv->drm);
5560 }
5561
5562 static void bxt_sanitize_cdclk(struct drm_i915_private *dev_priv)
5563 {
5564         u32 cdctl, expected;
5565
5566         intel_update_cdclk(&dev_priv->drm);
5567
5568         if (dev_priv->cdclk_pll.vco == 0 ||
5569             dev_priv->cdclk_freq == dev_priv->cdclk_pll.ref)
5570                 goto sanitize;
5571
5572         /* DPLL okay; verify the cdclock
5573          *
5574          * Some BIOS versions leave an incorrect decimal frequency value and
5575          * set reserved MBZ bits in CDCLK_CTL at least during exiting from S4,
5576          * so sanitize this register.
5577          */
5578         cdctl = I915_READ(CDCLK_CTL);
5579         /*
5580          * Let's ignore the pipe field, since BIOS could have configured the
5581          * dividers both synching to an active pipe, or asynchronously
5582          * (PIPE_NONE).
5583          */
5584         cdctl &= ~BXT_CDCLK_CD2X_PIPE_NONE;
5585
5586         expected = (cdctl & BXT_CDCLK_CD2X_DIV_SEL_MASK) |
5587                    skl_cdclk_decimal(dev_priv->cdclk_freq);
5588         /*
5589          * Disable SSA Precharge when CD clock frequency < 500 MHz,
5590          * enable otherwise.
5591          */
5592         if (dev_priv->cdclk_freq >= 500000)
5593                 expected |= BXT_CDCLK_SSA_PRECHARGE_ENABLE;
5594
5595         if (cdctl == expected)
5596                 /* All well; nothing to sanitize */
5597                 return;
5598
5599 sanitize:
5600         DRM_DEBUG_KMS("Sanitizing cdclk programmed by pre-os\n");
5601
5602         /* force cdclk programming */
5603         dev_priv->cdclk_freq = 0;
5604
5605         /* force full PLL disable + enable */
5606         dev_priv->cdclk_pll.vco = -1;
5607 }
5608
5609 void bxt_init_cdclk(struct drm_i915_private *dev_priv)
5610 {
5611         bxt_sanitize_cdclk(dev_priv);
5612
5613         if (dev_priv->cdclk_freq != 0 && dev_priv->cdclk_pll.vco != 0)
5614                 return;
5615
5616         /*
5617          * FIXME:
5618          * - The initial CDCLK needs to be read from VBT.
5619          *   Need to make this change after VBT has changes for BXT.
5620          */
5621         bxt_set_cdclk(dev_priv, bxt_calc_cdclk(0));
5622 }
5623
5624 void bxt_uninit_cdclk(struct drm_i915_private *dev_priv)
5625 {
5626         bxt_set_cdclk(dev_priv, dev_priv->cdclk_pll.ref);
5627 }
5628
5629 static int skl_calc_cdclk(int max_pixclk, int vco)
5630 {
5631         if (vco == 8640000) {
5632                 if (max_pixclk > 540000)
5633                         return 617143;
5634                 else if (max_pixclk > 432000)
5635                         return 540000;
5636                 else if (max_pixclk > 308571)
5637                         return 432000;
5638                 else
5639                         return 308571;
5640         } else {
5641                 if (max_pixclk > 540000)
5642                         return 675000;
5643                 else if (max_pixclk > 450000)
5644                         return 540000;
5645                 else if (max_pixclk > 337500)
5646                         return 450000;
5647                 else
5648                         return 337500;
5649         }
5650 }
5651
5652 static void
5653 skl_dpll0_update(struct drm_i915_private *dev_priv)
5654 {
5655         u32 val;
5656
5657         dev_priv->cdclk_pll.ref = 24000;
5658         dev_priv->cdclk_pll.vco = 0;
5659
5660         val = I915_READ(LCPLL1_CTL);
5661         if ((val & LCPLL_PLL_ENABLE) == 0)
5662                 return;
5663
5664         if (WARN_ON((val & LCPLL_PLL_LOCK) == 0))
5665                 return;
5666
5667         val = I915_READ(DPLL_CTRL1);
5668
5669         if (WARN_ON((val & (DPLL_CTRL1_HDMI_MODE(SKL_DPLL0) |
5670                             DPLL_CTRL1_SSC(SKL_DPLL0) |
5671                             DPLL_CTRL1_OVERRIDE(SKL_DPLL0))) !=
5672                     DPLL_CTRL1_OVERRIDE(SKL_DPLL0)))
5673                 return;
5674
5675         switch (val & DPLL_CTRL1_LINK_RATE_MASK(SKL_DPLL0)) {
5676         case DPLL_CTRL1_LINK_RATE(DPLL_CTRL1_LINK_RATE_810, SKL_DPLL0):
5677         case DPLL_CTRL1_LINK_RATE(DPLL_CTRL1_LINK_RATE_1350, SKL_DPLL0):
5678         case DPLL_CTRL1_LINK_RATE(DPLL_CTRL1_LINK_RATE_1620, SKL_DPLL0):
5679         case DPLL_CTRL1_LINK_RATE(DPLL_CTRL1_LINK_RATE_2700, SKL_DPLL0):
5680                 dev_priv->cdclk_pll.vco = 8100000;
5681                 break;
5682         case DPLL_CTRL1_LINK_RATE(DPLL_CTRL1_LINK_RATE_1080, SKL_DPLL0):
5683         case DPLL_CTRL1_LINK_RATE(DPLL_CTRL1_LINK_RATE_2160, SKL_DPLL0):
5684                 dev_priv->cdclk_pll.vco = 8640000;
5685                 break;
5686         default:
5687                 MISSING_CASE(val & DPLL_CTRL1_LINK_RATE_MASK(SKL_DPLL0));
5688                 break;
5689         }
5690 }
5691
5692 void skl_set_preferred_cdclk_vco(struct drm_i915_private *dev_priv, int vco)
5693 {
5694         bool changed = dev_priv->skl_preferred_vco_freq != vco;
5695
5696         dev_priv->skl_preferred_vco_freq = vco;
5697
5698         if (changed)
5699                 intel_update_max_cdclk(&dev_priv->drm);
5700 }
5701
5702 static void
5703 skl_dpll0_enable(struct drm_i915_private *dev_priv, int vco)
5704 {
5705         int min_cdclk = skl_calc_cdclk(0, vco);
5706         u32 val;
5707
5708         WARN_ON(vco != 8100000 && vco != 8640000);
5709
5710         /* select the minimum CDCLK before enabling DPLL 0 */
5711         val = CDCLK_FREQ_337_308 | skl_cdclk_decimal(min_cdclk);
5712         I915_WRITE(CDCLK_CTL, val);
5713         POSTING_READ(CDCLK_CTL);
5714
5715         /*
5716          * We always enable DPLL0 with the lowest link rate possible, but still
5717          * taking into account the VCO required to operate the eDP panel at the
5718          * desired frequency. The usual DP link rates operate with a VCO of
5719          * 8100 while the eDP 1.4 alternate link rates need a VCO of 8640.
5720          * The modeset code is responsible for the selection of the exact link
5721          * rate later on, with the constraint of choosing a frequency that
5722          * works with vco.
5723          */
5724         val = I915_READ(DPLL_CTRL1);
5725
5726         val &= ~(DPLL_CTRL1_HDMI_MODE(SKL_DPLL0) | DPLL_CTRL1_SSC(SKL_DPLL0) |
5727                  DPLL_CTRL1_LINK_RATE_MASK(SKL_DPLL0));
5728         val |= DPLL_CTRL1_OVERRIDE(SKL_DPLL0);
5729         if (vco == 8640000)
5730                 val |= DPLL_CTRL1_LINK_RATE(DPLL_CTRL1_LINK_RATE_1080,
5731                                             SKL_DPLL0);
5732         else
5733                 val |= DPLL_CTRL1_LINK_RATE(DPLL_CTRL1_LINK_RATE_810,
5734                                             SKL_DPLL0);
5735
5736         I915_WRITE(DPLL_CTRL1, val);
5737         POSTING_READ(DPLL_CTRL1);
5738
5739         I915_WRITE(LCPLL1_CTL, I915_READ(LCPLL1_CTL) | LCPLL_PLL_ENABLE);
5740
5741         if (intel_wait_for_register(dev_priv,
5742                                     LCPLL1_CTL, LCPLL_PLL_LOCK, LCPLL_PLL_LOCK,
5743                                     5))
5744                 DRM_ERROR("DPLL0 not locked\n");
5745
5746         dev_priv->cdclk_pll.vco = vco;
5747
5748         /* We'll want to keep using the current vco from now on. */
5749         skl_set_preferred_cdclk_vco(dev_priv, vco);
5750 }
5751
5752 static void
5753 skl_dpll0_disable(struct drm_i915_private *dev_priv)
5754 {
5755         I915_WRITE(LCPLL1_CTL, I915_READ(LCPLL1_CTL) & ~LCPLL_PLL_ENABLE);
5756         if (intel_wait_for_register(dev_priv,
5757                                    LCPLL1_CTL, LCPLL_PLL_LOCK, 0,
5758                                    1))
5759                 DRM_ERROR("Couldn't disable DPLL0\n");
5760
5761         dev_priv->cdclk_pll.vco = 0;
5762 }
5763
5764 static bool skl_cdclk_pcu_ready(struct drm_i915_private *dev_priv)
5765 {
5766         int ret;
5767         u32 val;
5768
5769         /* inform PCU we want to change CDCLK */
5770         val = SKL_CDCLK_PREPARE_FOR_CHANGE;
5771         mutex_lock(&dev_priv->rps.hw_lock);
5772         ret = sandybridge_pcode_read(dev_priv, SKL_PCODE_CDCLK_CONTROL, &val);
5773         mutex_unlock(&dev_priv->rps.hw_lock);
5774
5775         return ret == 0 && (val & SKL_CDCLK_READY_FOR_CHANGE);
5776 }
5777
5778 static bool skl_cdclk_wait_for_pcu_ready(struct drm_i915_private *dev_priv)
5779 {
5780         return _wait_for(skl_cdclk_pcu_ready(dev_priv), 3000, 10) == 0;
5781 }
5782
5783 static void skl_set_cdclk(struct drm_i915_private *dev_priv, int cdclk, int vco)
5784 {
5785         struct drm_device *dev = &dev_priv->drm;
5786         u32 freq_select, pcu_ack;
5787
5788         WARN_ON((cdclk == 24000) != (vco == 0));
5789
5790         DRM_DEBUG_DRIVER("Changing CDCLK to %d kHz (VCO %d kHz)\n", cdclk, vco);
5791
5792         if (!skl_cdclk_wait_for_pcu_ready(dev_priv)) {
5793                 DRM_ERROR("failed to inform PCU about cdclk change\n");
5794                 return;
5795         }
5796
5797         /* set CDCLK_CTL */
5798         switch (cdclk) {
5799         case 450000:
5800         case 432000:
5801                 freq_select = CDCLK_FREQ_450_432;
5802                 pcu_ack = 1;
5803                 break;
5804         case 540000:
5805                 freq_select = CDCLK_FREQ_540;
5806                 pcu_ack = 2;
5807                 break;
5808         case 308571:
5809         case 337500:
5810         default:
5811                 freq_select = CDCLK_FREQ_337_308;
5812                 pcu_ack = 0;
5813                 break;
5814         case 617143:
5815         case 675000:
5816                 freq_select = CDCLK_FREQ_675_617;
5817                 pcu_ack = 3;
5818                 break;
5819         }
5820
5821         if (dev_priv->cdclk_pll.vco != 0 &&
5822             dev_priv->cdclk_pll.vco != vco)
5823                 skl_dpll0_disable(dev_priv);
5824
5825         if (dev_priv->cdclk_pll.vco != vco)
5826                 skl_dpll0_enable(dev_priv, vco);
5827
5828         I915_WRITE(CDCLK_CTL, freq_select | skl_cdclk_decimal(cdclk));
5829         POSTING_READ(CDCLK_CTL);
5830
5831         /* inform PCU of the change */
5832         mutex_lock(&dev_priv->rps.hw_lock);
5833         sandybridge_pcode_write(dev_priv, SKL_PCODE_CDCLK_CONTROL, pcu_ack);
5834         mutex_unlock(&dev_priv->rps.hw_lock);
5835
5836         intel_update_cdclk(dev);
5837 }
5838
5839 static void skl_sanitize_cdclk(struct drm_i915_private *dev_priv);
5840
5841 void skl_uninit_cdclk(struct drm_i915_private *dev_priv)
5842 {
5843         skl_set_cdclk(dev_priv, dev_priv->cdclk_pll.ref, 0);
5844 }
5845
5846 void skl_init_cdclk(struct drm_i915_private *dev_priv)
5847 {
5848         int cdclk, vco;
5849
5850         skl_sanitize_cdclk(dev_priv);
5851
5852         if (dev_priv->cdclk_freq != 0 && dev_priv->cdclk_pll.vco != 0) {
5853                 /*
5854                  * Use the current vco as our initial
5855                  * guess as to what the preferred vco is.
5856                  */
5857                 if (dev_priv->skl_preferred_vco_freq == 0)
5858                         skl_set_preferred_cdclk_vco(dev_priv,
5859                                                     dev_priv->cdclk_pll.vco);
5860                 return;
5861         }
5862
5863         vco = dev_priv->skl_preferred_vco_freq;
5864         if (vco == 0)
5865                 vco = 8100000;
5866         cdclk = skl_calc_cdclk(0, vco);
5867
5868         skl_set_cdclk(dev_priv, cdclk, vco);
5869 }
5870
5871 static void skl_sanitize_cdclk(struct drm_i915_private *dev_priv)
5872 {
5873         uint32_t cdctl, expected;
5874
5875         /*
5876          * check if the pre-os intialized the display
5877          * There is SWF18 scratchpad register defined which is set by the
5878          * pre-os which can be used by the OS drivers to check the status
5879          */
5880         if ((I915_READ(SWF_ILK(0x18)) & 0x00FFFFFF) == 0)
5881                 goto sanitize;
5882
5883         intel_update_cdclk(&dev_priv->drm);
5884         /* Is PLL enabled and locked ? */
5885         if (dev_priv->cdclk_pll.vco == 0 ||
5886             dev_priv->cdclk_freq == dev_priv->cdclk_pll.ref)
5887                 goto sanitize;
5888
5889         /* DPLL okay; verify the cdclock
5890          *
5891          * Noticed in some instances that the freq selection is correct but
5892          * decimal part is programmed wrong from BIOS where pre-os does not
5893          * enable display. Verify the same as well.
5894          */
5895         cdctl = I915_READ(CDCLK_CTL);
5896         expected = (cdctl & CDCLK_FREQ_SEL_MASK) |
5897                 skl_cdclk_decimal(dev_priv->cdclk_freq);
5898         if (cdctl == expected)
5899                 /* All well; nothing to sanitize */
5900                 return;
5901
5902 sanitize:
5903         DRM_DEBUG_KMS("Sanitizing cdclk programmed by pre-os\n");
5904
5905         /* force cdclk programming */
5906         dev_priv->cdclk_freq = 0;
5907         /* force full PLL disable + enable */
5908         dev_priv->cdclk_pll.vco = -1;
5909 }
5910
5911 /* Adjust CDclk dividers to allow high res or save power if possible */
5912 static void valleyview_set_cdclk(struct drm_device *dev, int cdclk)
5913 {
5914         struct drm_i915_private *dev_priv = to_i915(dev);
5915         u32 val, cmd;
5916
5917         WARN_ON(dev_priv->display.get_display_clock_speed(dev)
5918                                         != dev_priv->cdclk_freq);
5919
5920         if (cdclk >= 320000) /* jump to highest voltage for 400MHz too */
5921                 cmd = 2;
5922         else if (cdclk == 266667)
5923                 cmd = 1;
5924         else
5925                 cmd = 0;
5926
5927         mutex_lock(&dev_priv->rps.hw_lock);
5928         val = vlv_punit_read(dev_priv, PUNIT_REG_DSPFREQ);
5929         val &= ~DSPFREQGUAR_MASK;
5930         val |= (cmd << DSPFREQGUAR_SHIFT);
5931         vlv_punit_write(dev_priv, PUNIT_REG_DSPFREQ, val);
5932         if (wait_for((vlv_punit_read(dev_priv, PUNIT_REG_DSPFREQ) &
5933                       DSPFREQSTAT_MASK) == (cmd << DSPFREQSTAT_SHIFT),
5934                      50)) {
5935                 DRM_ERROR("timed out waiting for CDclk change\n");
5936         }
5937         mutex_unlock(&dev_priv->rps.hw_lock);
5938
5939         mutex_lock(&dev_priv->sb_lock);
5940
5941         if (cdclk == 400000) {
5942                 u32 divider;
5943
5944                 divider = DIV_ROUND_CLOSEST(dev_priv->hpll_freq << 1, cdclk) - 1;
5945
5946                 /* adjust cdclk divider */
5947                 val = vlv_cck_read(dev_priv, CCK_DISPLAY_CLOCK_CONTROL);
5948                 val &= ~CCK_FREQUENCY_VALUES;
5949                 val |= divider;
5950                 vlv_cck_write(dev_priv, CCK_DISPLAY_CLOCK_CONTROL, val);
5951
5952                 if (wait_for((vlv_cck_read(dev_priv, CCK_DISPLAY_CLOCK_CONTROL) &
5953                               CCK_FREQUENCY_STATUS) == (divider << CCK_FREQUENCY_STATUS_SHIFT),
5954                              50))
5955                         DRM_ERROR("timed out waiting for CDclk change\n");
5956         }
5957
5958         /* adjust self-refresh exit latency value */
5959         val = vlv_bunit_read(dev_priv, BUNIT_REG_BISOC);
5960         val &= ~0x7f;
5961
5962         /*
5963          * For high bandwidth configs, we set a higher latency in the bunit
5964          * so that the core display fetch happens in time to avoid underruns.
5965          */
5966         if (cdclk == 400000)
5967                 val |= 4500 / 250; /* 4.5 usec */
5968         else
5969                 val |= 3000 / 250; /* 3.0 usec */
5970         vlv_bunit_write(dev_priv, BUNIT_REG_BISOC, val);
5971
5972         mutex_unlock(&dev_priv->sb_lock);
5973
5974         intel_update_cdclk(dev);
5975 }
5976
5977 static void cherryview_set_cdclk(struct drm_device *dev, int cdclk)
5978 {
5979         struct drm_i915_private *dev_priv = to_i915(dev);
5980         u32 val, cmd;
5981
5982         WARN_ON(dev_priv->display.get_display_clock_speed(dev)
5983                                                 != dev_priv->cdclk_freq);
5984
5985         switch (cdclk) {
5986         case 333333:
5987         case 320000:
5988         case 266667:
5989         case 200000:
5990                 break;
5991         default:
5992                 MISSING_CASE(cdclk);
5993                 return;
5994         }
5995
5996         /*
5997          * Specs are full of misinformation, but testing on actual
5998          * hardware has shown that we just need to write the desired
5999          * CCK divider into the Punit register.
6000          */
6001         cmd = DIV_ROUND_CLOSEST(dev_priv->hpll_freq << 1, cdclk) - 1;
6002
6003         mutex_lock(&dev_priv->rps.hw_lock);
6004         val = vlv_punit_read(dev_priv, PUNIT_REG_DSPFREQ);
6005         val &= ~DSPFREQGUAR_MASK_CHV;
6006         val |= (cmd << DSPFREQGUAR_SHIFT_CHV);
6007         vlv_punit_write(dev_priv, PUNIT_REG_DSPFREQ, val);
6008         if (wait_for((vlv_punit_read(dev_priv, PUNIT_REG_DSPFREQ) &
6009                       DSPFREQSTAT_MASK_CHV) == (cmd << DSPFREQSTAT_SHIFT_CHV),
6010                      50)) {
6011                 DRM_ERROR("timed out waiting for CDclk change\n");
6012         }
6013         mutex_unlock(&dev_priv->rps.hw_lock);
6014
6015         intel_update_cdclk(dev);
6016 }
6017
6018 static int valleyview_calc_cdclk(struct drm_i915_private *dev_priv,
6019                                  int max_pixclk)
6020 {
6021         int freq_320 = (dev_priv->hpll_freq <<  1) % 320000 != 0 ? 333333 : 320000;
6022         int limit = IS_CHERRYVIEW(dev_priv) ? 95 : 90;
6023
6024         /*
6025          * Really only a few cases to deal with, as only 4 CDclks are supported:
6026          *   200MHz
6027          *   267MHz
6028          *   320/333MHz (depends on HPLL freq)
6029          *   400MHz (VLV only)
6030          * So we check to see whether we're above 90% (VLV) or 95% (CHV)
6031          * of the lower bin and adjust if needed.
6032          *
6033          * We seem to get an unstable or solid color picture at 200MHz.
6034          * Not sure what's wrong. For now use 200MHz only when all pipes
6035          * are off.
6036          */
6037         if (!IS_CHERRYVIEW(dev_priv) &&
6038             max_pixclk > freq_320*limit/100)
6039                 return 400000;
6040         else if (max_pixclk > 266667*limit/100)
6041                 return freq_320;
6042         else if (max_pixclk > 0)
6043                 return 266667;
6044         else
6045                 return 200000;
6046 }
6047
6048 static int bxt_calc_cdclk(int max_pixclk)
6049 {
6050         if (max_pixclk > 576000)
6051                 return 624000;
6052         else if (max_pixclk > 384000)
6053                 return 576000;
6054         else if (max_pixclk > 288000)
6055                 return 384000;
6056         else if (max_pixclk > 144000)
6057                 return 288000;
6058         else
6059                 return 144000;
6060 }
6061
6062 /* Compute the max pixel clock for new configuration. */
6063 static int intel_mode_max_pixclk(struct drm_device *dev,
6064                                  struct drm_atomic_state *state)
6065 {
6066         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
6067         struct drm_i915_private *dev_priv = to_i915(dev);
6068         struct drm_crtc *crtc;
6069         struct drm_crtc_state *crtc_state;
6070         unsigned max_pixclk = 0, i;
6071         enum pipe pipe;
6072
6073         memcpy(intel_state->min_pixclk, dev_priv->min_pixclk,
6074                sizeof(intel_state->min_pixclk));
6075
6076         for_each_crtc_in_state(state, crtc, crtc_state, i) {
6077                 int pixclk = 0;
6078
6079                 if (crtc_state->enable)
6080                         pixclk = crtc_state->adjusted_mode.crtc_clock;
6081
6082                 intel_state->min_pixclk[i] = pixclk;
6083         }
6084
6085         for_each_pipe(dev_priv, pipe)
6086                 max_pixclk = max(intel_state->min_pixclk[pipe], max_pixclk);
6087
6088         return max_pixclk;
6089 }
6090
6091 static int valleyview_modeset_calc_cdclk(struct drm_atomic_state *state)
6092 {
6093         struct drm_device *dev = state->dev;
6094         struct drm_i915_private *dev_priv = to_i915(dev);
6095         int max_pixclk = intel_mode_max_pixclk(dev, state);
6096         struct intel_atomic_state *intel_state =
6097                 to_intel_atomic_state(state);
6098
6099         intel_state->cdclk = intel_state->dev_cdclk =
6100                 valleyview_calc_cdclk(dev_priv, max_pixclk);
6101
6102         if (!intel_state->active_crtcs)
6103                 intel_state->dev_cdclk = valleyview_calc_cdclk(dev_priv, 0);
6104
6105         return 0;
6106 }
6107
6108 static int bxt_modeset_calc_cdclk(struct drm_atomic_state *state)
6109 {
6110         int max_pixclk = ilk_max_pixel_rate(state);
6111         struct intel_atomic_state *intel_state =
6112                 to_intel_atomic_state(state);
6113
6114         intel_state->cdclk = intel_state->dev_cdclk =
6115                 bxt_calc_cdclk(max_pixclk);
6116
6117         if (!intel_state->active_crtcs)
6118                 intel_state->dev_cdclk = bxt_calc_cdclk(0);
6119
6120         return 0;
6121 }
6122
6123 static void vlv_program_pfi_credits(struct drm_i915_private *dev_priv)
6124 {
6125         unsigned int credits, default_credits;
6126
6127         if (IS_CHERRYVIEW(dev_priv))
6128                 default_credits = PFI_CREDIT(12);
6129         else
6130                 default_credits = PFI_CREDIT(8);
6131
6132         if (dev_priv->cdclk_freq >= dev_priv->czclk_freq) {
6133                 /* CHV suggested value is 31 or 63 */
6134                 if (IS_CHERRYVIEW(dev_priv))
6135                         credits = PFI_CREDIT_63;
6136                 else
6137                         credits = PFI_CREDIT(15);
6138         } else {
6139                 credits = default_credits;
6140         }
6141
6142         /*
6143          * WA - write default credits before re-programming
6144          * FIXME: should we also set the resend bit here?
6145          */
6146         I915_WRITE(GCI_CONTROL, VGA_FAST_MODE_DISABLE |
6147                    default_credits);
6148
6149         I915_WRITE(GCI_CONTROL, VGA_FAST_MODE_DISABLE |
6150                    credits | PFI_CREDIT_RESEND);
6151
6152         /*
6153          * FIXME is this guaranteed to clear
6154          * immediately or should we poll for it?
6155          */
6156         WARN_ON(I915_READ(GCI_CONTROL) & PFI_CREDIT_RESEND);
6157 }
6158
6159 static void valleyview_modeset_commit_cdclk(struct drm_atomic_state *old_state)
6160 {
6161         struct drm_device *dev = old_state->dev;
6162         struct drm_i915_private *dev_priv = to_i915(dev);
6163         struct intel_atomic_state *old_intel_state =
6164                 to_intel_atomic_state(old_state);
6165         unsigned req_cdclk = old_intel_state->dev_cdclk;
6166
6167         /*
6168          * FIXME: We can end up here with all power domains off, yet
6169          * with a CDCLK frequency other than the minimum. To account
6170          * for this take the PIPE-A power domain, which covers the HW
6171          * blocks needed for the following programming. This can be
6172          * removed once it's guaranteed that we get here either with
6173          * the minimum CDCLK set, or the required power domains
6174          * enabled.
6175          */
6176         intel_display_power_get(dev_priv, POWER_DOMAIN_PIPE_A);
6177
6178         if (IS_CHERRYVIEW(dev))
6179                 cherryview_set_cdclk(dev, req_cdclk);
6180         else
6181                 valleyview_set_cdclk(dev, req_cdclk);
6182
6183         vlv_program_pfi_credits(dev_priv);
6184
6185         intel_display_power_put(dev_priv, POWER_DOMAIN_PIPE_A);
6186 }
6187
6188 static void valleyview_crtc_enable(struct drm_crtc *crtc)
6189 {
6190         struct drm_device *dev = crtc->dev;
6191         struct drm_i915_private *dev_priv = to_i915(dev);
6192         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
6193         struct intel_encoder *encoder;
6194         struct intel_crtc_state *pipe_config =
6195                 to_intel_crtc_state(crtc->state);
6196         int pipe = intel_crtc->pipe;
6197
6198         if (WARN_ON(intel_crtc->active))
6199                 return;
6200
6201         if (intel_crtc_has_dp_encoder(intel_crtc->config))
6202                 intel_dp_set_m_n(intel_crtc, M1_N1);
6203
6204         intel_set_pipe_timings(intel_crtc);
6205         intel_set_pipe_src_size(intel_crtc);
6206
6207         if (IS_CHERRYVIEW(dev) && pipe == PIPE_B) {
6208                 struct drm_i915_private *dev_priv = to_i915(dev);
6209
6210                 I915_WRITE(CHV_BLEND(pipe), CHV_BLEND_LEGACY);
6211                 I915_WRITE(CHV_CANVAS(pipe), 0);
6212         }
6213
6214         i9xx_set_pipeconf(intel_crtc);
6215
6216         intel_crtc->active = true;
6217
6218         intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
6219
6220         for_each_encoder_on_crtc(dev, crtc, encoder)
6221                 if (encoder->pre_pll_enable)
6222                         encoder->pre_pll_enable(encoder);
6223
6224         if (IS_CHERRYVIEW(dev)) {
6225                 chv_prepare_pll(intel_crtc, intel_crtc->config);
6226                 chv_enable_pll(intel_crtc, intel_crtc->config);
6227         } else {
6228                 vlv_prepare_pll(intel_crtc, intel_crtc->config);
6229                 vlv_enable_pll(intel_crtc, intel_crtc->config);
6230         }
6231
6232         for_each_encoder_on_crtc(dev, crtc, encoder)
6233                 if (encoder->pre_enable)
6234                         encoder->pre_enable(encoder);
6235
6236         i9xx_pfit_enable(intel_crtc);
6237
6238         intel_color_load_luts(&pipe_config->base);
6239
6240         intel_update_watermarks(crtc);
6241         intel_enable_pipe(intel_crtc);
6242
6243         assert_vblank_disabled(crtc);
6244         drm_crtc_vblank_on(crtc);
6245
6246         for_each_encoder_on_crtc(dev, crtc, encoder)
6247                 encoder->enable(encoder);
6248 }
6249
6250 static void i9xx_set_pll_dividers(struct intel_crtc *crtc)
6251 {
6252         struct drm_device *dev = crtc->base.dev;
6253         struct drm_i915_private *dev_priv = to_i915(dev);
6254
6255         I915_WRITE(FP0(crtc->pipe), crtc->config->dpll_hw_state.fp0);
6256         I915_WRITE(FP1(crtc->pipe), crtc->config->dpll_hw_state.fp1);
6257 }
6258
6259 static void i9xx_crtc_enable(struct drm_crtc *crtc)
6260 {
6261         struct drm_device *dev = crtc->dev;
6262         struct drm_i915_private *dev_priv = to_i915(dev);
6263         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
6264         struct intel_encoder *encoder;
6265         struct intel_crtc_state *pipe_config =
6266                 to_intel_crtc_state(crtc->state);
6267         enum pipe pipe = intel_crtc->pipe;
6268
6269         if (WARN_ON(intel_crtc->active))
6270                 return;
6271
6272         i9xx_set_pll_dividers(intel_crtc);
6273
6274         if (intel_crtc_has_dp_encoder(intel_crtc->config))
6275                 intel_dp_set_m_n(intel_crtc, M1_N1);
6276
6277         intel_set_pipe_timings(intel_crtc);
6278         intel_set_pipe_src_size(intel_crtc);
6279
6280         i9xx_set_pipeconf(intel_crtc);
6281
6282         intel_crtc->active = true;
6283
6284         if (!IS_GEN2(dev))
6285                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
6286
6287         for_each_encoder_on_crtc(dev, crtc, encoder)
6288                 if (encoder->pre_enable)
6289                         encoder->pre_enable(encoder);
6290
6291         i9xx_enable_pll(intel_crtc);
6292
6293         i9xx_pfit_enable(intel_crtc);
6294
6295         intel_color_load_luts(&pipe_config->base);
6296
6297         intel_update_watermarks(crtc);
6298         intel_enable_pipe(intel_crtc);
6299
6300         assert_vblank_disabled(crtc);
6301         drm_crtc_vblank_on(crtc);
6302
6303         for_each_encoder_on_crtc(dev, crtc, encoder)
6304                 encoder->enable(encoder);
6305 }
6306
6307 static void i9xx_pfit_disable(struct intel_crtc *crtc)
6308 {
6309         struct drm_device *dev = crtc->base.dev;
6310         struct drm_i915_private *dev_priv = to_i915(dev);
6311
6312         if (!crtc->config->gmch_pfit.control)
6313                 return;
6314
6315         assert_pipe_disabled(dev_priv, crtc->pipe);
6316
6317         DRM_DEBUG_DRIVER("disabling pfit, current: 0x%08x\n",
6318                          I915_READ(PFIT_CONTROL));
6319         I915_WRITE(PFIT_CONTROL, 0);
6320 }
6321
6322 static void i9xx_crtc_disable(struct drm_crtc *crtc)
6323 {
6324         struct drm_device *dev = crtc->dev;
6325         struct drm_i915_private *dev_priv = to_i915(dev);
6326         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
6327         struct intel_encoder *encoder;
6328         int pipe = intel_crtc->pipe;
6329
6330         /*
6331          * On gen2 planes are double buffered but the pipe isn't, so we must
6332          * wait for planes to fully turn off before disabling the pipe.
6333          */
6334         if (IS_GEN2(dev))
6335                 intel_wait_for_vblank(dev, pipe);
6336
6337         for_each_encoder_on_crtc(dev, crtc, encoder)
6338                 encoder->disable(encoder);
6339
6340         drm_crtc_vblank_off(crtc);
6341         assert_vblank_disabled(crtc);
6342
6343         intel_disable_pipe(intel_crtc);
6344
6345         i9xx_pfit_disable(intel_crtc);
6346
6347         for_each_encoder_on_crtc(dev, crtc, encoder)
6348                 if (encoder->post_disable)
6349                         encoder->post_disable(encoder);
6350
6351         if (!intel_crtc_has_type(intel_crtc->config, INTEL_OUTPUT_DSI)) {
6352                 if (IS_CHERRYVIEW(dev))
6353                         chv_disable_pll(dev_priv, pipe);
6354                 else if (IS_VALLEYVIEW(dev))
6355                         vlv_disable_pll(dev_priv, pipe);
6356                 else
6357                         i9xx_disable_pll(intel_crtc);
6358         }
6359
6360         for_each_encoder_on_crtc(dev, crtc, encoder)
6361                 if (encoder->post_pll_disable)
6362                         encoder->post_pll_disable(encoder);
6363
6364         if (!IS_GEN2(dev))
6365                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, false);
6366 }
6367
6368 static void intel_crtc_disable_noatomic(struct drm_crtc *crtc)
6369 {
6370         struct intel_encoder *encoder;
6371         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
6372         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
6373         enum intel_display_power_domain domain;
6374         unsigned long domains;
6375
6376         if (!intel_crtc->active)
6377                 return;
6378
6379         if (to_intel_plane_state(crtc->primary->state)->visible) {
6380                 WARN_ON(intel_crtc->flip_work);
6381
6382                 intel_pre_disable_primary_noatomic(crtc);
6383
6384                 intel_crtc_disable_planes(crtc, 1 << drm_plane_index(crtc->primary));
6385                 to_intel_plane_state(crtc->primary->state)->visible = false;
6386         }
6387
6388         dev_priv->display.crtc_disable(crtc);
6389
6390         DRM_DEBUG_KMS("[CRTC:%d:%s] hw state adjusted, was enabled, now disabled\n",
6391                       crtc->base.id, crtc->name);
6392
6393         WARN_ON(drm_atomic_set_mode_for_crtc(crtc->state, NULL) < 0);
6394         crtc->state->active = false;
6395         intel_crtc->active = false;
6396         crtc->enabled = false;
6397         crtc->state->connector_mask = 0;
6398         crtc->state->encoder_mask = 0;
6399
6400         for_each_encoder_on_crtc(crtc->dev, crtc, encoder)
6401                 encoder->base.crtc = NULL;
6402
6403         intel_fbc_disable(intel_crtc);
6404         intel_update_watermarks(crtc);
6405         intel_disable_shared_dpll(intel_crtc);
6406
6407         domains = intel_crtc->enabled_power_domains;
6408         for_each_power_domain(domain, domains)
6409                 intel_display_power_put(dev_priv, domain);
6410         intel_crtc->enabled_power_domains = 0;
6411
6412         dev_priv->active_crtcs &= ~(1 << intel_crtc->pipe);
6413         dev_priv->min_pixclk[intel_crtc->pipe] = 0;
6414 }
6415
6416 /*
6417  * turn all crtc's off, but do not adjust state
6418  * This has to be paired with a call to intel_modeset_setup_hw_state.
6419  */
6420 int intel_display_suspend(struct drm_device *dev)
6421 {
6422         struct drm_i915_private *dev_priv = to_i915(dev);
6423         struct drm_atomic_state *state;
6424         int ret;
6425
6426         state = drm_atomic_helper_suspend(dev);
6427         ret = PTR_ERR_OR_ZERO(state);
6428         if (ret)
6429                 DRM_ERROR("Suspending crtc's failed with %i\n", ret);
6430         else
6431                 dev_priv->modeset_restore_state = state;
6432         return ret;
6433 }
6434
6435 void intel_encoder_destroy(struct drm_encoder *encoder)
6436 {
6437         struct intel_encoder *intel_encoder = to_intel_encoder(encoder);
6438
6439         drm_encoder_cleanup(encoder);
6440         kfree(intel_encoder);
6441 }
6442
6443 /* Cross check the actual hw state with our own modeset state tracking (and it's
6444  * internal consistency). */
6445 static void intel_connector_verify_state(struct intel_connector *connector)
6446 {
6447         struct drm_crtc *crtc = connector->base.state->crtc;
6448
6449         DRM_DEBUG_KMS("[CONNECTOR:%d:%s]\n",
6450                       connector->base.base.id,
6451                       connector->base.name);
6452
6453         if (connector->get_hw_state(connector)) {
6454                 struct intel_encoder *encoder = connector->encoder;
6455                 struct drm_connector_state *conn_state = connector->base.state;
6456
6457                 I915_STATE_WARN(!crtc,
6458                          "connector enabled without attached crtc\n");
6459
6460                 if (!crtc)
6461                         return;
6462
6463                 I915_STATE_WARN(!crtc->state->active,
6464                       "connector is active, but attached crtc isn't\n");
6465
6466                 if (!encoder || encoder->type == INTEL_OUTPUT_DP_MST)
6467                         return;
6468
6469                 I915_STATE_WARN(conn_state->best_encoder != &encoder->base,
6470                         "atomic encoder doesn't match attached encoder\n");
6471
6472                 I915_STATE_WARN(conn_state->crtc != encoder->base.crtc,
6473                         "attached encoder crtc differs from connector crtc\n");
6474         } else {
6475                 I915_STATE_WARN(crtc && crtc->state->active,
6476                         "attached crtc is active, but connector isn't\n");
6477                 I915_STATE_WARN(!crtc && connector->base.state->best_encoder,
6478                         "best encoder set without crtc!\n");
6479         }
6480 }
6481
6482 int intel_connector_init(struct intel_connector *connector)
6483 {
6484         drm_atomic_helper_connector_reset(&connector->base);
6485
6486         if (!connector->base.state)
6487                 return -ENOMEM;
6488
6489         return 0;
6490 }
6491
6492 struct intel_connector *intel_connector_alloc(void)
6493 {
6494         struct intel_connector *connector;
6495
6496         connector = kzalloc(sizeof *connector, GFP_KERNEL);
6497         if (!connector)
6498                 return NULL;
6499
6500         if (intel_connector_init(connector) < 0) {
6501                 kfree(connector);
6502                 return NULL;
6503         }
6504
6505         return connector;
6506 }
6507
6508 /* Simple connector->get_hw_state implementation for encoders that support only
6509  * one connector and no cloning and hence the encoder state determines the state
6510  * of the connector. */
6511 bool intel_connector_get_hw_state(struct intel_connector *connector)
6512 {
6513         enum pipe pipe = 0;
6514         struct intel_encoder *encoder = connector->encoder;
6515
6516         return encoder->get_hw_state(encoder, &pipe);
6517 }
6518
6519 static int pipe_required_fdi_lanes(struct intel_crtc_state *crtc_state)
6520 {
6521         if (crtc_state->base.enable && crtc_state->has_pch_encoder)
6522                 return crtc_state->fdi_lanes;
6523
6524         return 0;
6525 }
6526
6527 static int ironlake_check_fdi_lanes(struct drm_device *dev, enum pipe pipe,
6528                                      struct intel_crtc_state *pipe_config)
6529 {
6530         struct drm_atomic_state *state = pipe_config->base.state;
6531         struct intel_crtc *other_crtc;
6532         struct intel_crtc_state *other_crtc_state;
6533
6534         DRM_DEBUG_KMS("checking fdi config on pipe %c, lanes %i\n",
6535                       pipe_name(pipe), pipe_config->fdi_lanes);
6536         if (pipe_config->fdi_lanes > 4) {
6537                 DRM_DEBUG_KMS("invalid fdi lane config on pipe %c: %i lanes\n",
6538                               pipe_name(pipe), pipe_config->fdi_lanes);
6539                 return -EINVAL;
6540         }
6541
6542         if (IS_HASWELL(dev) || IS_BROADWELL(dev)) {
6543                 if (pipe_config->fdi_lanes > 2) {
6544                         DRM_DEBUG_KMS("only 2 lanes on haswell, required: %i lanes\n",
6545                                       pipe_config->fdi_lanes);
6546                         return -EINVAL;
6547                 } else {
6548                         return 0;
6549                 }
6550         }
6551
6552         if (INTEL_INFO(dev)->num_pipes == 2)
6553                 return 0;
6554
6555         /* Ivybridge 3 pipe is really complicated */
6556         switch (pipe) {
6557         case PIPE_A:
6558                 return 0;
6559         case PIPE_B:
6560                 if (pipe_config->fdi_lanes <= 2)
6561                         return 0;
6562
6563                 other_crtc = to_intel_crtc(intel_get_crtc_for_pipe(dev, PIPE_C));
6564                 other_crtc_state =
6565                         intel_atomic_get_crtc_state(state, other_crtc);
6566                 if (IS_ERR(other_crtc_state))
6567                         return PTR_ERR(other_crtc_state);
6568
6569                 if (pipe_required_fdi_lanes(other_crtc_state) > 0) {
6570                         DRM_DEBUG_KMS("invalid shared fdi lane config on pipe %c: %i lanes\n",
6571                                       pipe_name(pipe), pipe_config->fdi_lanes);
6572                         return -EINVAL;
6573                 }
6574                 return 0;
6575         case PIPE_C:
6576                 if (pipe_config->fdi_lanes > 2) {
6577                         DRM_DEBUG_KMS("only 2 lanes on pipe %c: required %i lanes\n",
6578                                       pipe_name(pipe), pipe_config->fdi_lanes);
6579                         return -EINVAL;
6580                 }
6581
6582                 other_crtc = to_intel_crtc(intel_get_crtc_for_pipe(dev, PIPE_B));
6583                 other_crtc_state =
6584                         intel_atomic_get_crtc_state(state, other_crtc);
6585                 if (IS_ERR(other_crtc_state))
6586                         return PTR_ERR(other_crtc_state);
6587
6588                 if (pipe_required_fdi_lanes(other_crtc_state) > 2) {
6589                         DRM_DEBUG_KMS("fdi link B uses too many lanes to enable link C\n");
6590                         return -EINVAL;
6591                 }
6592                 return 0;
6593         default:
6594                 BUG();
6595         }
6596 }
6597
6598 #define RETRY 1
6599 static int ironlake_fdi_compute_config(struct intel_crtc *intel_crtc,
6600                                        struct intel_crtc_state *pipe_config)
6601 {
6602         struct drm_device *dev = intel_crtc->base.dev;
6603         const struct drm_display_mode *adjusted_mode = &pipe_config->base.adjusted_mode;
6604         int lane, link_bw, fdi_dotclock, ret;
6605         bool needs_recompute = false;
6606
6607 retry:
6608         /* FDI is a binary signal running at ~2.7GHz, encoding
6609          * each output octet as 10 bits. The actual frequency
6610          * is stored as a divider into a 100MHz clock, and the
6611          * mode pixel clock is stored in units of 1KHz.
6612          * Hence the bw of each lane in terms of the mode signal
6613          * is:
6614          */
6615         link_bw = intel_fdi_link_freq(to_i915(dev), pipe_config);
6616
6617         fdi_dotclock = adjusted_mode->crtc_clock;
6618
6619         lane = ironlake_get_lanes_required(fdi_dotclock, link_bw,
6620                                            pipe_config->pipe_bpp);
6621
6622         pipe_config->fdi_lanes = lane;
6623
6624         intel_link_compute_m_n(pipe_config->pipe_bpp, lane, fdi_dotclock,
6625                                link_bw, &pipe_config->fdi_m_n);
6626
6627         ret = ironlake_check_fdi_lanes(dev, intel_crtc->pipe, pipe_config);
6628         if (ret == -EINVAL && pipe_config->pipe_bpp > 6*3) {
6629                 pipe_config->pipe_bpp -= 2*3;
6630                 DRM_DEBUG_KMS("fdi link bw constraint, reducing pipe bpp to %i\n",
6631                               pipe_config->pipe_bpp);
6632                 needs_recompute = true;
6633                 pipe_config->bw_constrained = true;
6634
6635                 goto retry;
6636         }
6637
6638         if (needs_recompute)
6639                 return RETRY;
6640
6641         return ret;
6642 }
6643
6644 static bool pipe_config_supports_ips(struct drm_i915_private *dev_priv,
6645                                      struct intel_crtc_state *pipe_config)
6646 {
6647         if (pipe_config->pipe_bpp > 24)
6648                 return false;
6649
6650         /* HSW can handle pixel rate up to cdclk? */
6651         if (IS_HASWELL(dev_priv))
6652                 return true;
6653
6654         /*
6655          * We compare against max which means we must take
6656          * the increased cdclk requirement into account when
6657          * calculating the new cdclk.
6658          *
6659          * Should measure whether using a lower cdclk w/o IPS
6660          */
6661         return ilk_pipe_pixel_rate(pipe_config) <=
6662                 dev_priv->max_cdclk_freq * 95 / 100;
6663 }
6664
6665 static void hsw_compute_ips_config(struct intel_crtc *crtc,
6666                                    struct intel_crtc_state *pipe_config)
6667 {
6668         struct drm_device *dev = crtc->base.dev;
6669         struct drm_i915_private *dev_priv = to_i915(dev);
6670
6671         pipe_config->ips_enabled = i915.enable_ips &&
6672                 hsw_crtc_supports_ips(crtc) &&
6673                 pipe_config_supports_ips(dev_priv, pipe_config);
6674 }
6675
6676 static bool intel_crtc_supports_double_wide(const struct intel_crtc *crtc)
6677 {
6678         const struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
6679
6680         /* GDG double wide on either pipe, otherwise pipe A only */
6681         return INTEL_INFO(dev_priv)->gen < 4 &&
6682                 (crtc->pipe == PIPE_A || IS_I915G(dev_priv));
6683 }
6684
6685 static int intel_crtc_compute_config(struct intel_crtc *crtc,
6686                                      struct intel_crtc_state *pipe_config)
6687 {
6688         struct drm_device *dev = crtc->base.dev;
6689         struct drm_i915_private *dev_priv = to_i915(dev);
6690         const struct drm_display_mode *adjusted_mode = &pipe_config->base.adjusted_mode;
6691         int clock_limit = dev_priv->max_dotclk_freq;
6692
6693         if (INTEL_INFO(dev)->gen < 4) {
6694                 clock_limit = dev_priv->max_cdclk_freq * 9 / 10;
6695
6696                 /*
6697                  * Enable double wide mode when the dot clock
6698                  * is > 90% of the (display) core speed.
6699                  */
6700                 if (intel_crtc_supports_double_wide(crtc) &&
6701                     adjusted_mode->crtc_clock > clock_limit) {
6702                         clock_limit = dev_priv->max_dotclk_freq;
6703                         pipe_config->double_wide = true;
6704                 }
6705         }
6706
6707         if (adjusted_mode->crtc_clock > clock_limit) {
6708                 DRM_DEBUG_KMS("requested pixel clock (%d kHz) too high (max: %d kHz, double wide: %s)\n",
6709                               adjusted_mode->crtc_clock, clock_limit,
6710                               yesno(pipe_config->double_wide));
6711                 return -EINVAL;
6712         }
6713
6714         /*
6715          * Pipe horizontal size must be even in:
6716          * - DVO ganged mode
6717          * - LVDS dual channel mode
6718          * - Double wide pipe
6719          */
6720         if ((intel_crtc_has_type(pipe_config, INTEL_OUTPUT_LVDS) &&
6721              intel_is_dual_link_lvds(dev)) || pipe_config->double_wide)
6722                 pipe_config->pipe_src_w &= ~1;
6723
6724         /* Cantiga+ cannot handle modes with a hsync front porch of 0.
6725          * WaPruneModeWithIncorrectHsyncOffset:ctg,elk,ilk,snb,ivb,vlv,hsw.
6726          */
6727         if ((INTEL_INFO(dev)->gen > 4 || IS_G4X(dev)) &&
6728                 adjusted_mode->crtc_hsync_start == adjusted_mode->crtc_hdisplay)
6729                 return -EINVAL;
6730
6731         if (HAS_IPS(dev))
6732                 hsw_compute_ips_config(crtc, pipe_config);
6733
6734         if (pipe_config->has_pch_encoder)
6735                 return ironlake_fdi_compute_config(crtc, pipe_config);
6736
6737         return 0;
6738 }
6739
6740 static int skylake_get_display_clock_speed(struct drm_device *dev)
6741 {
6742         struct drm_i915_private *dev_priv = to_i915(dev);
6743         uint32_t cdctl;
6744
6745         skl_dpll0_update(dev_priv);
6746
6747         if (dev_priv->cdclk_pll.vco == 0)
6748                 return dev_priv->cdclk_pll.ref;
6749
6750         cdctl = I915_READ(CDCLK_CTL);
6751
6752         if (dev_priv->cdclk_pll.vco == 8640000) {
6753                 switch (cdctl & CDCLK_FREQ_SEL_MASK) {
6754                 case CDCLK_FREQ_450_432:
6755                         return 432000;
6756                 case CDCLK_FREQ_337_308:
6757                         return 308571;
6758                 case CDCLK_FREQ_540:
6759                         return 540000;
6760                 case CDCLK_FREQ_675_617:
6761                         return 617143;
6762                 default:
6763                         MISSING_CASE(cdctl & CDCLK_FREQ_SEL_MASK);
6764                 }
6765         } else {
6766                 switch (cdctl & CDCLK_FREQ_SEL_MASK) {
6767                 case CDCLK_FREQ_450_432:
6768                         return 450000;
6769                 case CDCLK_FREQ_337_308:
6770                         return 337500;
6771                 case CDCLK_FREQ_540:
6772                         return 540000;
6773                 case CDCLK_FREQ_675_617:
6774                         return 675000;
6775                 default:
6776                         MISSING_CASE(cdctl & CDCLK_FREQ_SEL_MASK);
6777                 }
6778         }
6779
6780         return dev_priv->cdclk_pll.ref;
6781 }
6782
6783 static void bxt_de_pll_update(struct drm_i915_private *dev_priv)
6784 {
6785         u32 val;
6786
6787         dev_priv->cdclk_pll.ref = 19200;
6788         dev_priv->cdclk_pll.vco = 0;
6789
6790         val = I915_READ(BXT_DE_PLL_ENABLE);
6791         if ((val & BXT_DE_PLL_PLL_ENABLE) == 0)
6792                 return;
6793
6794         if (WARN_ON((val & BXT_DE_PLL_LOCK) == 0))
6795                 return;
6796
6797         val = I915_READ(BXT_DE_PLL_CTL);
6798         dev_priv->cdclk_pll.vco = (val & BXT_DE_PLL_RATIO_MASK) *
6799                 dev_priv->cdclk_pll.ref;
6800 }
6801
6802 static int broxton_get_display_clock_speed(struct drm_device *dev)
6803 {
6804         struct drm_i915_private *dev_priv = to_i915(dev);
6805         u32 divider;
6806         int div, vco;
6807
6808         bxt_de_pll_update(dev_priv);
6809
6810         vco = dev_priv->cdclk_pll.vco;
6811         if (vco == 0)
6812                 return dev_priv->cdclk_pll.ref;
6813
6814         divider = I915_READ(CDCLK_CTL) & BXT_CDCLK_CD2X_DIV_SEL_MASK;
6815
6816         switch (divider) {
6817         case BXT_CDCLK_CD2X_DIV_SEL_1:
6818                 div = 2;
6819                 break;
6820         case BXT_CDCLK_CD2X_DIV_SEL_1_5:
6821                 div = 3;
6822                 break;
6823         case BXT_CDCLK_CD2X_DIV_SEL_2:
6824                 div = 4;
6825                 break;
6826         case BXT_CDCLK_CD2X_DIV_SEL_4:
6827                 div = 8;
6828                 break;
6829         default:
6830                 MISSING_CASE(divider);
6831                 return dev_priv->cdclk_pll.ref;
6832         }
6833
6834         return DIV_ROUND_CLOSEST(vco, div);
6835 }
6836
6837 static int broadwell_get_display_clock_speed(struct drm_device *dev)
6838 {
6839         struct drm_i915_private *dev_priv = to_i915(dev);
6840         uint32_t lcpll = I915_READ(LCPLL_CTL);
6841         uint32_t freq = lcpll & LCPLL_CLK_FREQ_MASK;
6842
6843         if (lcpll & LCPLL_CD_SOURCE_FCLK)
6844                 return 800000;
6845         else if (I915_READ(FUSE_STRAP) & HSW_CDCLK_LIMIT)
6846                 return 450000;
6847         else if (freq == LCPLL_CLK_FREQ_450)
6848                 return 450000;
6849         else if (freq == LCPLL_CLK_FREQ_54O_BDW)
6850                 return 540000;
6851         else if (freq == LCPLL_CLK_FREQ_337_5_BDW)
6852                 return 337500;
6853         else
6854                 return 675000;
6855 }
6856
6857 static int haswell_get_display_clock_speed(struct drm_device *dev)
6858 {
6859         struct drm_i915_private *dev_priv = to_i915(dev);
6860         uint32_t lcpll = I915_READ(LCPLL_CTL);
6861         uint32_t freq = lcpll & LCPLL_CLK_FREQ_MASK;
6862
6863         if (lcpll & LCPLL_CD_SOURCE_FCLK)
6864                 return 800000;
6865         else if (I915_READ(FUSE_STRAP) & HSW_CDCLK_LIMIT)
6866                 return 450000;
6867         else if (freq == LCPLL_CLK_FREQ_450)
6868                 return 450000;
6869         else if (IS_HSW_ULT(dev))
6870                 return 337500;
6871         else
6872                 return 540000;
6873 }
6874
6875 static int valleyview_get_display_clock_speed(struct drm_device *dev)
6876 {
6877         return vlv_get_cck_clock_hpll(to_i915(dev), "cdclk",
6878                                       CCK_DISPLAY_CLOCK_CONTROL);
6879 }
6880
6881 static int ilk_get_display_clock_speed(struct drm_device *dev)
6882 {
6883         return 450000;
6884 }
6885
6886 static int i945_get_display_clock_speed(struct drm_device *dev)
6887 {
6888         return 400000;
6889 }
6890
6891 static int i915_get_display_clock_speed(struct drm_device *dev)
6892 {
6893         return 333333;
6894 }
6895
6896 static int i9xx_misc_get_display_clock_speed(struct drm_device *dev)
6897 {
6898         return 200000;
6899 }
6900
6901 static int pnv_get_display_clock_speed(struct drm_device *dev)
6902 {
6903         u16 gcfgc = 0;
6904
6905         pci_read_config_word(dev->pdev, GCFGC, &gcfgc);
6906
6907         switch (gcfgc & GC_DISPLAY_CLOCK_MASK) {
6908         case GC_DISPLAY_CLOCK_267_MHZ_PNV:
6909                 return 266667;
6910         case GC_DISPLAY_CLOCK_333_MHZ_PNV:
6911                 return 333333;
6912         case GC_DISPLAY_CLOCK_444_MHZ_PNV:
6913                 return 444444;
6914         case GC_DISPLAY_CLOCK_200_MHZ_PNV:
6915                 return 200000;
6916         default:
6917                 DRM_ERROR("Unknown pnv display core clock 0x%04x\n", gcfgc);
6918         case GC_DISPLAY_CLOCK_133_MHZ_PNV:
6919                 return 133333;
6920         case GC_DISPLAY_CLOCK_167_MHZ_PNV:
6921                 return 166667;
6922         }
6923 }
6924
6925 static int i915gm_get_display_clock_speed(struct drm_device *dev)
6926 {
6927         u16 gcfgc = 0;
6928
6929         pci_read_config_word(dev->pdev, GCFGC, &gcfgc);
6930
6931         if (gcfgc & GC_LOW_FREQUENCY_ENABLE)
6932                 return 133333;
6933         else {
6934                 switch (gcfgc & GC_DISPLAY_CLOCK_MASK) {
6935                 case GC_DISPLAY_CLOCK_333_MHZ:
6936                         return 333333;
6937                 default:
6938                 case GC_DISPLAY_CLOCK_190_200_MHZ:
6939                         return 190000;
6940                 }
6941         }
6942 }
6943
6944 static int i865_get_display_clock_speed(struct drm_device *dev)
6945 {
6946         return 266667;
6947 }
6948
6949 static int i85x_get_display_clock_speed(struct drm_device *dev)
6950 {
6951         u16 hpllcc = 0;
6952
6953         /*
6954          * 852GM/852GMV only supports 133 MHz and the HPLLCC
6955          * encoding is different :(
6956          * FIXME is this the right way to detect 852GM/852GMV?
6957          */
6958         if (dev->pdev->revision == 0x1)
6959                 return 133333;
6960
6961         pci_bus_read_config_word(dev->pdev->bus,
6962                                  PCI_DEVFN(0, 3), HPLLCC, &hpllcc);
6963
6964         /* Assume that the hardware is in the high speed state.  This
6965          * should be the default.
6966          */
6967         switch (hpllcc & GC_CLOCK_CONTROL_MASK) {
6968         case GC_CLOCK_133_200:
6969         case GC_CLOCK_133_200_2:
6970         case GC_CLOCK_100_200:
6971                 return 200000;
6972         case GC_CLOCK_166_250:
6973                 return 250000;
6974         case GC_CLOCK_100_133:
6975                 return 133333;
6976         case GC_CLOCK_133_266:
6977         case GC_CLOCK_133_266_2:
6978         case GC_CLOCK_166_266:
6979                 return 266667;
6980         }
6981
6982         /* Shouldn't happen */
6983         return 0;
6984 }
6985
6986 static int i830_get_display_clock_speed(struct drm_device *dev)
6987 {
6988         return 133333;
6989 }
6990
6991 static unsigned int intel_hpll_vco(struct drm_device *dev)
6992 {
6993         struct drm_i915_private *dev_priv = to_i915(dev);
6994         static const unsigned int blb_vco[8] = {
6995                 [0] = 3200000,
6996                 [1] = 4000000,
6997                 [2] = 5333333,
6998                 [3] = 4800000,
6999                 [4] = 6400000,
7000         };
7001         static const unsigned int pnv_vco[8] = {
7002                 [0] = 3200000,
7003                 [1] = 4000000,
7004                 [2] = 5333333,
7005                 [3] = 4800000,
7006                 [4] = 2666667,
7007         };
7008         static const unsigned int cl_vco[8] = {
7009                 [0] = 3200000,
7010                 [1] = 4000000,
7011                 [2] = 5333333,
7012                 [3] = 6400000,
7013                 [4] = 3333333,
7014                 [5] = 3566667,
7015                 [6] = 4266667,
7016         };
7017         static const unsigned int elk_vco[8] = {
7018                 [0] = 3200000,
7019                 [1] = 4000000,
7020                 [2] = 5333333,
7021                 [3] = 4800000,
7022         };
7023         static const unsigned int ctg_vco[8] = {
7024                 [0] = 3200000,
7025                 [1] = 4000000,
7026                 [2] = 5333333,
7027                 [3] = 6400000,
7028                 [4] = 2666667,
7029                 [5] = 4266667,
7030         };
7031         const unsigned int *vco_table;
7032         unsigned int vco;
7033         uint8_t tmp = 0;
7034
7035         /* FIXME other chipsets? */
7036         if (IS_GM45(dev))
7037                 vco_table = ctg_vco;
7038         else if (IS_G4X(dev))
7039                 vco_table = elk_vco;
7040         else if (IS_CRESTLINE(dev))
7041                 vco_table = cl_vco;
7042         else if (IS_PINEVIEW(dev))
7043                 vco_table = pnv_vco;
7044         else if (IS_G33(dev))
7045                 vco_table = blb_vco;
7046         else
7047                 return 0;
7048
7049         tmp = I915_READ(IS_MOBILE(dev) ? HPLLVCO_MOBILE : HPLLVCO);
7050
7051         vco = vco_table[tmp & 0x7];
7052         if (vco == 0)
7053                 DRM_ERROR("Bad HPLL VCO (HPLLVCO=0x%02x)\n", tmp);
7054         else
7055                 DRM_DEBUG_KMS("HPLL VCO %u kHz\n", vco);
7056
7057         return vco;
7058 }
7059
7060 static int gm45_get_display_clock_speed(struct drm_device *dev)
7061 {
7062         unsigned int cdclk_sel, vco = intel_hpll_vco(dev);
7063         uint16_t tmp = 0;
7064
7065         pci_read_config_word(dev->pdev, GCFGC, &tmp);
7066
7067         cdclk_sel = (tmp >> 12) & 0x1;
7068
7069         switch (vco) {
7070         case 2666667:
7071         case 4000000:
7072         case 5333333:
7073                 return cdclk_sel ? 333333 : 222222;
7074         case 3200000:
7075                 return cdclk_sel ? 320000 : 228571;
7076         default:
7077                 DRM_ERROR("Unable to determine CDCLK. HPLL VCO=%u, CFGC=0x%04x\n", vco, tmp);
7078                 return 222222;
7079         }
7080 }
7081
7082 static int i965gm_get_display_clock_speed(struct drm_device *dev)
7083 {
7084         static const uint8_t div_3200[] = { 16, 10,  8 };
7085         static const uint8_t div_4000[] = { 20, 12, 10 };
7086         static const uint8_t div_5333[] = { 24, 16, 14 };
7087         const uint8_t *div_table;
7088         unsigned int cdclk_sel, vco = intel_hpll_vco(dev);
7089         uint16_t tmp = 0;
7090
7091         pci_read_config_word(dev->pdev, GCFGC, &tmp);
7092
7093         cdclk_sel = ((tmp >> 8) & 0x1f) - 1;
7094
7095         if (cdclk_sel >= ARRAY_SIZE(div_3200))
7096                 goto fail;
7097
7098         switch (vco) {
7099         case 3200000:
7100                 div_table = div_3200;
7101                 break;
7102         case 4000000:
7103                 div_table = div_4000;
7104                 break;
7105         case 5333333:
7106                 div_table = div_5333;
7107                 break;
7108         default:
7109                 goto fail;
7110         }
7111
7112         return DIV_ROUND_CLOSEST(vco, div_table[cdclk_sel]);
7113
7114 fail:
7115         DRM_ERROR("Unable to determine CDCLK. HPLL VCO=%u kHz, CFGC=0x%04x\n", vco, tmp);
7116         return 200000;
7117 }
7118
7119 static int g33_get_display_clock_speed(struct drm_device *dev)
7120 {
7121         static const uint8_t div_3200[] = { 12, 10,  8,  7, 5, 16 };
7122         static const uint8_t div_4000[] = { 14, 12, 10,  8, 6, 20 };
7123         static const uint8_t div_4800[] = { 20, 14, 12, 10, 8, 24 };
7124         static const uint8_t div_5333[] = { 20, 16, 12, 12, 8, 28 };
7125         const uint8_t *div_table;
7126         unsigned int cdclk_sel, vco = intel_hpll_vco(dev);
7127         uint16_t tmp = 0;
7128
7129         pci_read_config_word(dev->pdev, GCFGC, &tmp);
7130
7131         cdclk_sel = (tmp >> 4) & 0x7;
7132
7133         if (cdclk_sel >= ARRAY_SIZE(div_3200))
7134                 goto fail;
7135
7136         switch (vco) {
7137         case 3200000:
7138                 div_table = div_3200;
7139                 break;
7140         case 4000000:
7141                 div_table = div_4000;
7142                 break;
7143         case 4800000:
7144                 div_table = div_4800;
7145                 break;
7146         case 5333333:
7147                 div_table = div_5333;
7148                 break;
7149         default:
7150                 goto fail;
7151         }
7152
7153         return DIV_ROUND_CLOSEST(vco, div_table[cdclk_sel]);
7154
7155 fail:
7156         DRM_ERROR("Unable to determine CDCLK. HPLL VCO=%u kHz, CFGC=0x%08x\n", vco, tmp);
7157         return 190476;
7158 }
7159
7160 static void
7161 intel_reduce_m_n_ratio(uint32_t *num, uint32_t *den)
7162 {
7163         while (*num > DATA_LINK_M_N_MASK ||
7164                *den > DATA_LINK_M_N_MASK) {
7165                 *num >>= 1;
7166                 *den >>= 1;
7167         }
7168 }
7169
7170 static void compute_m_n(unsigned int m, unsigned int n,
7171                         uint32_t *ret_m, uint32_t *ret_n)
7172 {
7173         *ret_n = min_t(unsigned int, roundup_pow_of_two(n), DATA_LINK_N_MAX);
7174         *ret_m = div_u64((uint64_t) m * *ret_n, n);
7175         intel_reduce_m_n_ratio(ret_m, ret_n);
7176 }
7177
7178 void
7179 intel_link_compute_m_n(int bits_per_pixel, int nlanes,
7180                        int pixel_clock, int link_clock,
7181                        struct intel_link_m_n *m_n)
7182 {
7183         m_n->tu = 64;
7184
7185         compute_m_n(bits_per_pixel * pixel_clock,
7186                     link_clock * nlanes * 8,
7187                     &m_n->gmch_m, &m_n->gmch_n);
7188
7189         compute_m_n(pixel_clock, link_clock,
7190                     &m_n->link_m, &m_n->link_n);
7191 }
7192
7193 static inline bool intel_panel_use_ssc(struct drm_i915_private *dev_priv)
7194 {
7195         if (i915.panel_use_ssc >= 0)
7196                 return i915.panel_use_ssc != 0;
7197         return dev_priv->vbt.lvds_use_ssc
7198                 && !(dev_priv->quirks & QUIRK_LVDS_SSC_DISABLE);
7199 }
7200
7201 static uint32_t pnv_dpll_compute_fp(struct dpll *dpll)
7202 {
7203         return (1 << dpll->n) << 16 | dpll->m2;
7204 }
7205
7206 static uint32_t i9xx_dpll_compute_fp(struct dpll *dpll)
7207 {
7208         return dpll->n << 16 | dpll->m1 << 8 | dpll->m2;
7209 }
7210
7211 static void i9xx_update_pll_dividers(struct intel_crtc *crtc,
7212                                      struct intel_crtc_state *crtc_state,
7213                                      struct dpll *reduced_clock)
7214 {
7215         struct drm_device *dev = crtc->base.dev;
7216         u32 fp, fp2 = 0;
7217
7218         if (IS_PINEVIEW(dev)) {
7219                 fp = pnv_dpll_compute_fp(&crtc_state->dpll);
7220                 if (reduced_clock)
7221                         fp2 = pnv_dpll_compute_fp(reduced_clock);
7222         } else {
7223                 fp = i9xx_dpll_compute_fp(&crtc_state->dpll);
7224                 if (reduced_clock)
7225                         fp2 = i9xx_dpll_compute_fp(reduced_clock);
7226         }
7227
7228         crtc_state->dpll_hw_state.fp0 = fp;
7229
7230         crtc->lowfreq_avail = false;
7231         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS) &&
7232             reduced_clock) {
7233                 crtc_state->dpll_hw_state.fp1 = fp2;
7234                 crtc->lowfreq_avail = true;
7235         } else {
7236                 crtc_state->dpll_hw_state.fp1 = fp;
7237         }
7238 }
7239
7240 static void vlv_pllb_recal_opamp(struct drm_i915_private *dev_priv, enum pipe
7241                 pipe)
7242 {
7243         u32 reg_val;
7244
7245         /*
7246          * PLLB opamp always calibrates to max value of 0x3f, force enable it
7247          * and set it to a reasonable value instead.
7248          */
7249         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW9(1));
7250         reg_val &= 0xffffff00;
7251         reg_val |= 0x00000030;
7252         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW9(1), reg_val);
7253
7254         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_REF_DW13);
7255         reg_val &= 0x8cffffff;
7256         reg_val = 0x8c000000;
7257         vlv_dpio_write(dev_priv, pipe, VLV_REF_DW13, reg_val);
7258
7259         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW9(1));
7260         reg_val &= 0xffffff00;
7261         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW9(1), reg_val);
7262
7263         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_REF_DW13);
7264         reg_val &= 0x00ffffff;
7265         reg_val |= 0xb0000000;
7266         vlv_dpio_write(dev_priv, pipe, VLV_REF_DW13, reg_val);
7267 }
7268
7269 static void intel_pch_transcoder_set_m_n(struct intel_crtc *crtc,
7270                                          struct intel_link_m_n *m_n)
7271 {
7272         struct drm_device *dev = crtc->base.dev;
7273         struct drm_i915_private *dev_priv = to_i915(dev);
7274         int pipe = crtc->pipe;
7275
7276         I915_WRITE(PCH_TRANS_DATA_M1(pipe), TU_SIZE(m_n->tu) | m_n->gmch_m);
7277         I915_WRITE(PCH_TRANS_DATA_N1(pipe), m_n->gmch_n);
7278         I915_WRITE(PCH_TRANS_LINK_M1(pipe), m_n->link_m);
7279         I915_WRITE(PCH_TRANS_LINK_N1(pipe), m_n->link_n);
7280 }
7281
7282 static void intel_cpu_transcoder_set_m_n(struct intel_crtc *crtc,
7283                                          struct intel_link_m_n *m_n,
7284                                          struct intel_link_m_n *m2_n2)
7285 {
7286         struct drm_device *dev = crtc->base.dev;
7287         struct drm_i915_private *dev_priv = to_i915(dev);
7288         int pipe = crtc->pipe;
7289         enum transcoder transcoder = crtc->config->cpu_transcoder;
7290
7291         if (INTEL_INFO(dev)->gen >= 5) {
7292                 I915_WRITE(PIPE_DATA_M1(transcoder), TU_SIZE(m_n->tu) | m_n->gmch_m);
7293                 I915_WRITE(PIPE_DATA_N1(transcoder), m_n->gmch_n);
7294                 I915_WRITE(PIPE_LINK_M1(transcoder), m_n->link_m);
7295                 I915_WRITE(PIPE_LINK_N1(transcoder), m_n->link_n);
7296                 /* M2_N2 registers to be set only for gen < 8 (M2_N2 available
7297                  * for gen < 8) and if DRRS is supported (to make sure the
7298                  * registers are not unnecessarily accessed).
7299                  */
7300                 if (m2_n2 && (IS_CHERRYVIEW(dev) || INTEL_INFO(dev)->gen < 8) &&
7301                         crtc->config->has_drrs) {
7302                         I915_WRITE(PIPE_DATA_M2(transcoder),
7303                                         TU_SIZE(m2_n2->tu) | m2_n2->gmch_m);
7304                         I915_WRITE(PIPE_DATA_N2(transcoder), m2_n2->gmch_n);
7305                         I915_WRITE(PIPE_LINK_M2(transcoder), m2_n2->link_m);
7306                         I915_WRITE(PIPE_LINK_N2(transcoder), m2_n2->link_n);
7307                 }
7308         } else {
7309                 I915_WRITE(PIPE_DATA_M_G4X(pipe), TU_SIZE(m_n->tu) | m_n->gmch_m);
7310                 I915_WRITE(PIPE_DATA_N_G4X(pipe), m_n->gmch_n);
7311                 I915_WRITE(PIPE_LINK_M_G4X(pipe), m_n->link_m);
7312                 I915_WRITE(PIPE_LINK_N_G4X(pipe), m_n->link_n);
7313         }
7314 }
7315
7316 void intel_dp_set_m_n(struct intel_crtc *crtc, enum link_m_n_set m_n)
7317 {
7318         struct intel_link_m_n *dp_m_n, *dp_m2_n2 = NULL;
7319
7320         if (m_n == M1_N1) {
7321                 dp_m_n = &crtc->config->dp_m_n;
7322                 dp_m2_n2 = &crtc->config->dp_m2_n2;
7323         } else if (m_n == M2_N2) {
7324
7325                 /*
7326                  * M2_N2 registers are not supported. Hence m2_n2 divider value
7327                  * needs to be programmed into M1_N1.
7328                  */
7329                 dp_m_n = &crtc->config->dp_m2_n2;
7330         } else {
7331                 DRM_ERROR("Unsupported divider value\n");
7332                 return;
7333         }
7334
7335         if (crtc->config->has_pch_encoder)
7336                 intel_pch_transcoder_set_m_n(crtc, &crtc->config->dp_m_n);
7337         else
7338                 intel_cpu_transcoder_set_m_n(crtc, dp_m_n, dp_m2_n2);
7339 }
7340
7341 static void vlv_compute_dpll(struct intel_crtc *crtc,
7342                              struct intel_crtc_state *pipe_config)
7343 {
7344         pipe_config->dpll_hw_state.dpll = DPLL_INTEGRATED_REF_CLK_VLV |
7345                 DPLL_REF_CLK_ENABLE_VLV | DPLL_VGA_MODE_DIS;
7346         if (crtc->pipe != PIPE_A)
7347                 pipe_config->dpll_hw_state.dpll |= DPLL_INTEGRATED_CRI_CLK_VLV;
7348
7349         /* DPLL not used with DSI, but still need the rest set up */
7350         if (!intel_crtc_has_type(pipe_config, INTEL_OUTPUT_DSI))
7351                 pipe_config->dpll_hw_state.dpll |= DPLL_VCO_ENABLE |
7352                         DPLL_EXT_BUFFER_ENABLE_VLV;
7353
7354         pipe_config->dpll_hw_state.dpll_md =
7355                 (pipe_config->pixel_multiplier - 1) << DPLL_MD_UDI_MULTIPLIER_SHIFT;
7356 }
7357
7358 static void chv_compute_dpll(struct intel_crtc *crtc,
7359                              struct intel_crtc_state *pipe_config)
7360 {
7361         pipe_config->dpll_hw_state.dpll = DPLL_SSC_REF_CLK_CHV |
7362                 DPLL_REF_CLK_ENABLE_VLV | DPLL_VGA_MODE_DIS;
7363         if (crtc->pipe != PIPE_A)
7364                 pipe_config->dpll_hw_state.dpll |= DPLL_INTEGRATED_CRI_CLK_VLV;
7365
7366         /* DPLL not used with DSI, but still need the rest set up */
7367         if (!intel_crtc_has_type(pipe_config, INTEL_OUTPUT_DSI))
7368                 pipe_config->dpll_hw_state.dpll |= DPLL_VCO_ENABLE;
7369
7370         pipe_config->dpll_hw_state.dpll_md =
7371                 (pipe_config->pixel_multiplier - 1) << DPLL_MD_UDI_MULTIPLIER_SHIFT;
7372 }
7373
7374 static void vlv_prepare_pll(struct intel_crtc *crtc,
7375                             const struct intel_crtc_state *pipe_config)
7376 {
7377         struct drm_device *dev = crtc->base.dev;
7378         struct drm_i915_private *dev_priv = to_i915(dev);
7379         enum pipe pipe = crtc->pipe;
7380         u32 mdiv;
7381         u32 bestn, bestm1, bestm2, bestp1, bestp2;
7382         u32 coreclk, reg_val;
7383
7384         /* Enable Refclk */
7385         I915_WRITE(DPLL(pipe),
7386                    pipe_config->dpll_hw_state.dpll &
7387                    ~(DPLL_VCO_ENABLE | DPLL_EXT_BUFFER_ENABLE_VLV));
7388
7389         /* No need to actually set up the DPLL with DSI */
7390         if ((pipe_config->dpll_hw_state.dpll & DPLL_VCO_ENABLE) == 0)
7391                 return;
7392
7393         mutex_lock(&dev_priv->sb_lock);
7394
7395         bestn = pipe_config->dpll.n;
7396         bestm1 = pipe_config->dpll.m1;
7397         bestm2 = pipe_config->dpll.m2;
7398         bestp1 = pipe_config->dpll.p1;
7399         bestp2 = pipe_config->dpll.p2;
7400
7401         /* See eDP HDMI DPIO driver vbios notes doc */
7402
7403         /* PLL B needs special handling */
7404         if (pipe == PIPE_B)
7405                 vlv_pllb_recal_opamp(dev_priv, pipe);
7406
7407         /* Set up Tx target for periodic Rcomp update */
7408         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW9_BCAST, 0x0100000f);
7409
7410         /* Disable target IRef on PLL */
7411         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW8(pipe));
7412         reg_val &= 0x00ffffff;
7413         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW8(pipe), reg_val);
7414
7415         /* Disable fast lock */
7416         vlv_dpio_write(dev_priv, pipe, VLV_CMN_DW0, 0x610);
7417
7418         /* Set idtafcrecal before PLL is enabled */
7419         mdiv = ((bestm1 << DPIO_M1DIV_SHIFT) | (bestm2 & DPIO_M2DIV_MASK));
7420         mdiv |= ((bestp1 << DPIO_P1_SHIFT) | (bestp2 << DPIO_P2_SHIFT));
7421         mdiv |= ((bestn << DPIO_N_SHIFT));
7422         mdiv |= (1 << DPIO_K_SHIFT);
7423
7424         /*
7425          * Post divider depends on pixel clock rate, DAC vs digital (and LVDS,
7426          * but we don't support that).
7427          * Note: don't use the DAC post divider as it seems unstable.
7428          */
7429         mdiv |= (DPIO_POST_DIV_HDMIDP << DPIO_POST_DIV_SHIFT);
7430         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW3(pipe), mdiv);
7431
7432         mdiv |= DPIO_ENABLE_CALIBRATION;
7433         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW3(pipe), mdiv);
7434
7435         /* Set HBR and RBR LPF coefficients */
7436         if (pipe_config->port_clock == 162000 ||
7437             intel_crtc_has_type(crtc->config, INTEL_OUTPUT_ANALOG) ||
7438             intel_crtc_has_type(crtc->config, INTEL_OUTPUT_HDMI))
7439                 vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW10(pipe),
7440                                  0x009f0003);
7441         else
7442                 vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW10(pipe),
7443                                  0x00d0000f);
7444
7445         if (intel_crtc_has_dp_encoder(pipe_config)) {
7446                 /* Use SSC source */
7447                 if (pipe == PIPE_A)
7448                         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW5(pipe),
7449                                          0x0df40000);
7450                 else
7451                         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW5(pipe),
7452                                          0x0df70000);
7453         } else { /* HDMI or VGA */
7454                 /* Use bend source */
7455                 if (pipe == PIPE_A)
7456                         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW5(pipe),
7457                                          0x0df70000);
7458                 else
7459                         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW5(pipe),
7460                                          0x0df40000);
7461         }
7462
7463         coreclk = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW7(pipe));
7464         coreclk = (coreclk & 0x0000ff00) | 0x01c00000;
7465         if (intel_crtc_has_dp_encoder(crtc->config))
7466                 coreclk |= 0x01000000;
7467         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW7(pipe), coreclk);
7468
7469         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW11(pipe), 0x87871000);
7470         mutex_unlock(&dev_priv->sb_lock);
7471 }
7472
7473 static void chv_prepare_pll(struct intel_crtc *crtc,
7474                             const struct intel_crtc_state *pipe_config)
7475 {
7476         struct drm_device *dev = crtc->base.dev;
7477         struct drm_i915_private *dev_priv = to_i915(dev);
7478         enum pipe pipe = crtc->pipe;
7479         enum dpio_channel port = vlv_pipe_to_channel(pipe);
7480         u32 loopfilter, tribuf_calcntr;
7481         u32 bestn, bestm1, bestm2, bestp1, bestp2, bestm2_frac;
7482         u32 dpio_val;
7483         int vco;
7484
7485         /* Enable Refclk and SSC */
7486         I915_WRITE(DPLL(pipe),
7487                    pipe_config->dpll_hw_state.dpll & ~DPLL_VCO_ENABLE);
7488
7489         /* No need to actually set up the DPLL with DSI */
7490         if ((pipe_config->dpll_hw_state.dpll & DPLL_VCO_ENABLE) == 0)
7491                 return;
7492
7493         bestn = pipe_config->dpll.n;
7494         bestm2_frac = pipe_config->dpll.m2 & 0x3fffff;
7495         bestm1 = pipe_config->dpll.m1;
7496         bestm2 = pipe_config->dpll.m2 >> 22;
7497         bestp1 = pipe_config->dpll.p1;
7498         bestp2 = pipe_config->dpll.p2;
7499         vco = pipe_config->dpll.vco;
7500         dpio_val = 0;
7501         loopfilter = 0;
7502
7503         mutex_lock(&dev_priv->sb_lock);
7504
7505         /* p1 and p2 divider */
7506         vlv_dpio_write(dev_priv, pipe, CHV_CMN_DW13(port),
7507                         5 << DPIO_CHV_S1_DIV_SHIFT |
7508                         bestp1 << DPIO_CHV_P1_DIV_SHIFT |
7509                         bestp2 << DPIO_CHV_P2_DIV_SHIFT |
7510                         1 << DPIO_CHV_K_DIV_SHIFT);
7511
7512         /* Feedback post-divider - m2 */
7513         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW0(port), bestm2);
7514
7515         /* Feedback refclk divider - n and m1 */
7516         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW1(port),
7517                         DPIO_CHV_M1_DIV_BY_2 |
7518                         1 << DPIO_CHV_N_DIV_SHIFT);
7519
7520         /* M2 fraction division */
7521         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW2(port), bestm2_frac);
7522
7523         /* M2 fraction division enable */
7524         dpio_val = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW3(port));
7525         dpio_val &= ~(DPIO_CHV_FEEDFWD_GAIN_MASK | DPIO_CHV_FRAC_DIV_EN);
7526         dpio_val |= (2 << DPIO_CHV_FEEDFWD_GAIN_SHIFT);
7527         if (bestm2_frac)
7528                 dpio_val |= DPIO_CHV_FRAC_DIV_EN;
7529         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW3(port), dpio_val);
7530
7531         /* Program digital lock detect threshold */
7532         dpio_val = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW9(port));
7533         dpio_val &= ~(DPIO_CHV_INT_LOCK_THRESHOLD_MASK |
7534                                         DPIO_CHV_INT_LOCK_THRESHOLD_SEL_COARSE);
7535         dpio_val |= (0x5 << DPIO_CHV_INT_LOCK_THRESHOLD_SHIFT);
7536         if (!bestm2_frac)
7537                 dpio_val |= DPIO_CHV_INT_LOCK_THRESHOLD_SEL_COARSE;
7538         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW9(port), dpio_val);
7539
7540         /* Loop filter */
7541         if (vco == 5400000) {
7542                 loopfilter |= (0x3 << DPIO_CHV_PROP_COEFF_SHIFT);
7543                 loopfilter |= (0x8 << DPIO_CHV_INT_COEFF_SHIFT);
7544                 loopfilter |= (0x1 << DPIO_CHV_GAIN_CTRL_SHIFT);
7545                 tribuf_calcntr = 0x9;
7546         } else if (vco <= 6200000) {
7547                 loopfilter |= (0x5 << DPIO_CHV_PROP_COEFF_SHIFT);
7548                 loopfilter |= (0xB << DPIO_CHV_INT_COEFF_SHIFT);
7549                 loopfilter |= (0x3 << DPIO_CHV_GAIN_CTRL_SHIFT);
7550                 tribuf_calcntr = 0x9;
7551         } else if (vco <= 6480000) {
7552                 loopfilter |= (0x4 << DPIO_CHV_PROP_COEFF_SHIFT);
7553                 loopfilter |= (0x9 << DPIO_CHV_INT_COEFF_SHIFT);
7554                 loopfilter |= (0x3 << DPIO_CHV_GAIN_CTRL_SHIFT);
7555                 tribuf_calcntr = 0x8;
7556         } else {
7557                 /* Not supported. Apply the same limits as in the max case */
7558                 loopfilter |= (0x4 << DPIO_CHV_PROP_COEFF_SHIFT);
7559                 loopfilter |= (0x9 << DPIO_CHV_INT_COEFF_SHIFT);
7560                 loopfilter |= (0x3 << DPIO_CHV_GAIN_CTRL_SHIFT);
7561                 tribuf_calcntr = 0;
7562         }
7563         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW6(port), loopfilter);
7564
7565         dpio_val = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW8(port));
7566         dpio_val &= ~DPIO_CHV_TDC_TARGET_CNT_MASK;
7567         dpio_val |= (tribuf_calcntr << DPIO_CHV_TDC_TARGET_CNT_SHIFT);
7568         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW8(port), dpio_val);
7569
7570         /* AFC Recal */
7571         vlv_dpio_write(dev_priv, pipe, CHV_CMN_DW14(port),
7572                         vlv_dpio_read(dev_priv, pipe, CHV_CMN_DW14(port)) |
7573                         DPIO_AFC_RECAL);
7574
7575         mutex_unlock(&dev_priv->sb_lock);
7576 }
7577
7578 /**
7579  * vlv_force_pll_on - forcibly enable just the PLL
7580  * @dev_priv: i915 private structure
7581  * @pipe: pipe PLL to enable
7582  * @dpll: PLL configuration
7583  *
7584  * Enable the PLL for @pipe using the supplied @dpll config. To be used
7585  * in cases where we need the PLL enabled even when @pipe is not going to
7586  * be enabled.
7587  */
7588 int vlv_force_pll_on(struct drm_device *dev, enum pipe pipe,
7589                      const struct dpll *dpll)
7590 {
7591         struct intel_crtc *crtc =
7592                 to_intel_crtc(intel_get_crtc_for_pipe(dev, pipe));
7593         struct intel_crtc_state *pipe_config;
7594
7595         pipe_config = kzalloc(sizeof(*pipe_config), GFP_KERNEL);
7596         if (!pipe_config)
7597                 return -ENOMEM;
7598
7599         pipe_config->base.crtc = &crtc->base;
7600         pipe_config->pixel_multiplier = 1;
7601         pipe_config->dpll = *dpll;
7602
7603         if (IS_CHERRYVIEW(dev)) {
7604                 chv_compute_dpll(crtc, pipe_config);
7605                 chv_prepare_pll(crtc, pipe_config);
7606                 chv_enable_pll(crtc, pipe_config);
7607         } else {
7608                 vlv_compute_dpll(crtc, pipe_config);
7609                 vlv_prepare_pll(crtc, pipe_config);
7610                 vlv_enable_pll(crtc, pipe_config);
7611         }
7612
7613         kfree(pipe_config);
7614
7615         return 0;
7616 }
7617
7618 /**
7619  * vlv_force_pll_off - forcibly disable just the PLL
7620  * @dev_priv: i915 private structure
7621  * @pipe: pipe PLL to disable
7622  *
7623  * Disable the PLL for @pipe. To be used in cases where we need
7624  * the PLL enabled even when @pipe is not going to be enabled.
7625  */
7626 void vlv_force_pll_off(struct drm_device *dev, enum pipe pipe)
7627 {
7628         if (IS_CHERRYVIEW(dev))
7629                 chv_disable_pll(to_i915(dev), pipe);
7630         else
7631                 vlv_disable_pll(to_i915(dev), pipe);
7632 }
7633
7634 static void i9xx_compute_dpll(struct intel_crtc *crtc,
7635                               struct intel_crtc_state *crtc_state,
7636                               struct dpll *reduced_clock)
7637 {
7638         struct drm_device *dev = crtc->base.dev;
7639         struct drm_i915_private *dev_priv = to_i915(dev);
7640         u32 dpll;
7641         struct dpll *clock = &crtc_state->dpll;
7642
7643         i9xx_update_pll_dividers(crtc, crtc_state, reduced_clock);
7644
7645         dpll = DPLL_VGA_MODE_DIS;
7646
7647         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS))
7648                 dpll |= DPLLB_MODE_LVDS;
7649         else
7650                 dpll |= DPLLB_MODE_DAC_SERIAL;
7651
7652         if (IS_I945G(dev) || IS_I945GM(dev) || IS_G33(dev)) {
7653                 dpll |= (crtc_state->pixel_multiplier - 1)
7654                         << SDVO_MULTIPLIER_SHIFT_HIRES;
7655         }
7656
7657         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_SDVO) ||
7658             intel_crtc_has_type(crtc_state, INTEL_OUTPUT_HDMI))
7659                 dpll |= DPLL_SDVO_HIGH_SPEED;
7660
7661         if (intel_crtc_has_dp_encoder(crtc_state))
7662                 dpll |= DPLL_SDVO_HIGH_SPEED;
7663
7664         /* compute bitmask from p1 value */
7665         if (IS_PINEVIEW(dev))
7666                 dpll |= (1 << (clock->p1 - 1)) << DPLL_FPA01_P1_POST_DIV_SHIFT_PINEVIEW;
7667         else {
7668                 dpll |= (1 << (clock->p1 - 1)) << DPLL_FPA01_P1_POST_DIV_SHIFT;
7669                 if (IS_G4X(dev) && reduced_clock)
7670                         dpll |= (1 << (reduced_clock->p1 - 1)) << DPLL_FPA1_P1_POST_DIV_SHIFT;
7671         }
7672         switch (clock->p2) {
7673         case 5:
7674                 dpll |= DPLL_DAC_SERIAL_P2_CLOCK_DIV_5;
7675                 break;
7676         case 7:
7677                 dpll |= DPLLB_LVDS_P2_CLOCK_DIV_7;
7678                 break;
7679         case 10:
7680                 dpll |= DPLL_DAC_SERIAL_P2_CLOCK_DIV_10;
7681                 break;
7682         case 14:
7683                 dpll |= DPLLB_LVDS_P2_CLOCK_DIV_14;
7684                 break;
7685         }
7686         if (INTEL_INFO(dev)->gen >= 4)
7687                 dpll |= (6 << PLL_LOAD_PULSE_PHASE_SHIFT);
7688
7689         if (crtc_state->sdvo_tv_clock)
7690                 dpll |= PLL_REF_INPUT_TVCLKINBC;
7691         else if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS) &&
7692                  intel_panel_use_ssc(dev_priv))
7693                 dpll |= PLLB_REF_INPUT_SPREADSPECTRUMIN;
7694         else
7695                 dpll |= PLL_REF_INPUT_DREFCLK;
7696
7697         dpll |= DPLL_VCO_ENABLE;
7698         crtc_state->dpll_hw_state.dpll = dpll;
7699
7700         if (INTEL_INFO(dev)->gen >= 4) {
7701                 u32 dpll_md = (crtc_state->pixel_multiplier - 1)
7702                         << DPLL_MD_UDI_MULTIPLIER_SHIFT;
7703                 crtc_state->dpll_hw_state.dpll_md = dpll_md;
7704         }
7705 }
7706
7707 static void i8xx_compute_dpll(struct intel_crtc *crtc,
7708                               struct intel_crtc_state *crtc_state,
7709                               struct dpll *reduced_clock)
7710 {
7711         struct drm_device *dev = crtc->base.dev;
7712         struct drm_i915_private *dev_priv = to_i915(dev);
7713         u32 dpll;
7714         struct dpll *clock = &crtc_state->dpll;
7715
7716         i9xx_update_pll_dividers(crtc, crtc_state, reduced_clock);
7717
7718         dpll = DPLL_VGA_MODE_DIS;
7719
7720         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS)) {
7721                 dpll |= (1 << (clock->p1 - 1)) << DPLL_FPA01_P1_POST_DIV_SHIFT;
7722         } else {
7723                 if (clock->p1 == 2)
7724                         dpll |= PLL_P1_DIVIDE_BY_TWO;
7725                 else
7726                         dpll |= (clock->p1 - 2) << DPLL_FPA01_P1_POST_DIV_SHIFT;
7727                 if (clock->p2 == 4)
7728                         dpll |= PLL_P2_DIVIDE_BY_4;
7729         }
7730
7731         if (!IS_I830(dev) && intel_crtc_has_type(crtc_state, INTEL_OUTPUT_DVO))
7732                 dpll |= DPLL_DVO_2X_MODE;
7733
7734         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS) &&
7735             intel_panel_use_ssc(dev_priv))
7736                 dpll |= PLLB_REF_INPUT_SPREADSPECTRUMIN;
7737         else
7738                 dpll |= PLL_REF_INPUT_DREFCLK;
7739
7740         dpll |= DPLL_VCO_ENABLE;
7741         crtc_state->dpll_hw_state.dpll = dpll;
7742 }
7743
7744 static void intel_set_pipe_timings(struct intel_crtc *intel_crtc)
7745 {
7746         struct drm_device *dev = intel_crtc->base.dev;
7747         struct drm_i915_private *dev_priv = to_i915(dev);
7748         enum pipe pipe = intel_crtc->pipe;
7749         enum transcoder cpu_transcoder = intel_crtc->config->cpu_transcoder;
7750         const struct drm_display_mode *adjusted_mode = &intel_crtc->config->base.adjusted_mode;
7751         uint32_t crtc_vtotal, crtc_vblank_end;
7752         int vsyncshift = 0;
7753
7754         /* We need to be careful not to changed the adjusted mode, for otherwise
7755          * the hw state checker will get angry at the mismatch. */
7756         crtc_vtotal = adjusted_mode->crtc_vtotal;
7757         crtc_vblank_end = adjusted_mode->crtc_vblank_end;
7758
7759         if (adjusted_mode->flags & DRM_MODE_FLAG_INTERLACE) {
7760                 /* the chip adds 2 halflines automatically */
7761                 crtc_vtotal -= 1;
7762                 crtc_vblank_end -= 1;
7763
7764                 if (intel_crtc_has_type(intel_crtc->config, INTEL_OUTPUT_SDVO))
7765                         vsyncshift = (adjusted_mode->crtc_htotal - 1) / 2;
7766                 else
7767                         vsyncshift = adjusted_mode->crtc_hsync_start -
7768                                 adjusted_mode->crtc_htotal / 2;
7769                 if (vsyncshift < 0)
7770                         vsyncshift += adjusted_mode->crtc_htotal;
7771         }
7772
7773         if (INTEL_INFO(dev)->gen > 3)
7774                 I915_WRITE(VSYNCSHIFT(cpu_transcoder), vsyncshift);
7775
7776         I915_WRITE(HTOTAL(cpu_transcoder),
7777                    (adjusted_mode->crtc_hdisplay - 1) |
7778                    ((adjusted_mode->crtc_htotal - 1) << 16));
7779         I915_WRITE(HBLANK(cpu_transcoder),
7780                    (adjusted_mode->crtc_hblank_start - 1) |
7781                    ((adjusted_mode->crtc_hblank_end - 1) << 16));
7782         I915_WRITE(HSYNC(cpu_transcoder),
7783                    (adjusted_mode->crtc_hsync_start - 1) |
7784                    ((adjusted_mode->crtc_hsync_end - 1) << 16));
7785
7786         I915_WRITE(VTOTAL(cpu_transcoder),
7787                    (adjusted_mode->crtc_vdisplay - 1) |
7788                    ((crtc_vtotal - 1) << 16));
7789         I915_WRITE(VBLANK(cpu_transcoder),
7790                    (adjusted_mode->crtc_vblank_start - 1) |
7791                    ((crtc_vblank_end - 1) << 16));
7792         I915_WRITE(VSYNC(cpu_transcoder),
7793                    (adjusted_mode->crtc_vsync_start - 1) |
7794                    ((adjusted_mode->crtc_vsync_end - 1) << 16));
7795
7796         /* Workaround: when the EDP input selection is B, the VTOTAL_B must be
7797          * programmed with the VTOTAL_EDP value. Same for VTOTAL_C. This is
7798          * documented on the DDI_FUNC_CTL register description, EDP Input Select
7799          * bits. */
7800         if (IS_HASWELL(dev) && cpu_transcoder == TRANSCODER_EDP &&
7801             (pipe == PIPE_B || pipe == PIPE_C))
7802                 I915_WRITE(VTOTAL(pipe), I915_READ(VTOTAL(cpu_transcoder)));
7803
7804 }
7805
7806 static void intel_set_pipe_src_size(struct intel_crtc *intel_crtc)
7807 {
7808         struct drm_device *dev = intel_crtc->base.dev;
7809         struct drm_i915_private *dev_priv = to_i915(dev);
7810         enum pipe pipe = intel_crtc->pipe;
7811
7812         /* pipesrc controls the size that is scaled from, which should
7813          * always be the user's requested size.
7814          */
7815         I915_WRITE(PIPESRC(pipe),
7816                    ((intel_crtc->config->pipe_src_w - 1) << 16) |
7817                    (intel_crtc->config->pipe_src_h - 1));
7818 }
7819
7820 static void intel_get_pipe_timings(struct intel_crtc *crtc,
7821                                    struct intel_crtc_state *pipe_config)
7822 {
7823         struct drm_device *dev = crtc->base.dev;
7824         struct drm_i915_private *dev_priv = to_i915(dev);
7825         enum transcoder cpu_transcoder = pipe_config->cpu_transcoder;
7826         uint32_t tmp;
7827
7828         tmp = I915_READ(HTOTAL(cpu_transcoder));
7829         pipe_config->base.adjusted_mode.crtc_hdisplay = (tmp & 0xffff) + 1;
7830         pipe_config->base.adjusted_mode.crtc_htotal = ((tmp >> 16) & 0xffff) + 1;
7831         tmp = I915_READ(HBLANK(cpu_transcoder));
7832         pipe_config->base.adjusted_mode.crtc_hblank_start = (tmp & 0xffff) + 1;
7833         pipe_config->base.adjusted_mode.crtc_hblank_end = ((tmp >> 16) & 0xffff) + 1;
7834         tmp = I915_READ(HSYNC(cpu_transcoder));
7835         pipe_config->base.adjusted_mode.crtc_hsync_start = (tmp & 0xffff) + 1;
7836         pipe_config->base.adjusted_mode.crtc_hsync_end = ((tmp >> 16) & 0xffff) + 1;
7837
7838         tmp = I915_READ(VTOTAL(cpu_transcoder));
7839         pipe_config->base.adjusted_mode.crtc_vdisplay = (tmp & 0xffff) + 1;
7840         pipe_config->base.adjusted_mode.crtc_vtotal = ((tmp >> 16) & 0xffff) + 1;
7841         tmp = I915_READ(VBLANK(cpu_transcoder));
7842         pipe_config->base.adjusted_mode.crtc_vblank_start = (tmp & 0xffff) + 1;
7843         pipe_config->base.adjusted_mode.crtc_vblank_end = ((tmp >> 16) & 0xffff) + 1;
7844         tmp = I915_READ(VSYNC(cpu_transcoder));
7845         pipe_config->base.adjusted_mode.crtc_vsync_start = (tmp & 0xffff) + 1;
7846         pipe_config->base.adjusted_mode.crtc_vsync_end = ((tmp >> 16) & 0xffff) + 1;
7847
7848         if (I915_READ(PIPECONF(cpu_transcoder)) & PIPECONF_INTERLACE_MASK) {
7849                 pipe_config->base.adjusted_mode.flags |= DRM_MODE_FLAG_INTERLACE;
7850                 pipe_config->base.adjusted_mode.crtc_vtotal += 1;
7851                 pipe_config->base.adjusted_mode.crtc_vblank_end += 1;
7852         }
7853 }
7854
7855 static void intel_get_pipe_src_size(struct intel_crtc *crtc,
7856                                     struct intel_crtc_state *pipe_config)
7857 {
7858         struct drm_device *dev = crtc->base.dev;
7859         struct drm_i915_private *dev_priv = to_i915(dev);
7860         u32 tmp;
7861
7862         tmp = I915_READ(PIPESRC(crtc->pipe));
7863         pipe_config->pipe_src_h = (tmp & 0xffff) + 1;
7864         pipe_config->pipe_src_w = ((tmp >> 16) & 0xffff) + 1;
7865
7866         pipe_config->base.mode.vdisplay = pipe_config->pipe_src_h;
7867         pipe_config->base.mode.hdisplay = pipe_config->pipe_src_w;
7868 }
7869
7870 void intel_mode_from_pipe_config(struct drm_display_mode *mode,
7871                                  struct intel_crtc_state *pipe_config)
7872 {
7873         mode->hdisplay = pipe_config->base.adjusted_mode.crtc_hdisplay;
7874         mode->htotal = pipe_config->base.adjusted_mode.crtc_htotal;
7875         mode->hsync_start = pipe_config->base.adjusted_mode.crtc_hsync_start;
7876         mode->hsync_end = pipe_config->base.adjusted_mode.crtc_hsync_end;
7877
7878         mode->vdisplay = pipe_config->base.adjusted_mode.crtc_vdisplay;
7879         mode->vtotal = pipe_config->base.adjusted_mode.crtc_vtotal;
7880         mode->vsync_start = pipe_config->base.adjusted_mode.crtc_vsync_start;
7881         mode->vsync_end = pipe_config->base.adjusted_mode.crtc_vsync_end;
7882
7883         mode->flags = pipe_config->base.adjusted_mode.flags;
7884         mode->type = DRM_MODE_TYPE_DRIVER;
7885
7886         mode->clock = pipe_config->base.adjusted_mode.crtc_clock;
7887         mode->flags |= pipe_config->base.adjusted_mode.flags;
7888
7889         mode->hsync = drm_mode_hsync(mode);
7890         mode->vrefresh = drm_mode_vrefresh(mode);
7891         drm_mode_set_name(mode);
7892 }
7893
7894 static void i9xx_set_pipeconf(struct intel_crtc *intel_crtc)
7895 {
7896         struct drm_device *dev = intel_crtc->base.dev;
7897         struct drm_i915_private *dev_priv = to_i915(dev);
7898         uint32_t pipeconf;
7899
7900         pipeconf = 0;
7901
7902         if ((intel_crtc->pipe == PIPE_A && dev_priv->quirks & QUIRK_PIPEA_FORCE) ||
7903             (intel_crtc->pipe == PIPE_B && dev_priv->quirks & QUIRK_PIPEB_FORCE))
7904                 pipeconf |= I915_READ(PIPECONF(intel_crtc->pipe)) & PIPECONF_ENABLE;
7905
7906         if (intel_crtc->config->double_wide)
7907                 pipeconf |= PIPECONF_DOUBLE_WIDE;
7908
7909         /* only g4x and later have fancy bpc/dither controls */
7910         if (IS_G4X(dev) || IS_VALLEYVIEW(dev) || IS_CHERRYVIEW(dev)) {
7911                 /* Bspec claims that we can't use dithering for 30bpp pipes. */
7912                 if (intel_crtc->config->dither && intel_crtc->config->pipe_bpp != 30)
7913                         pipeconf |= PIPECONF_DITHER_EN |
7914                                     PIPECONF_DITHER_TYPE_SP;
7915
7916                 switch (intel_crtc->config->pipe_bpp) {
7917                 case 18:
7918                         pipeconf |= PIPECONF_6BPC;
7919                         break;
7920                 case 24:
7921                         pipeconf |= PIPECONF_8BPC;
7922                         break;
7923                 case 30:
7924                         pipeconf |= PIPECONF_10BPC;
7925                         break;
7926                 default:
7927                         /* Case prevented by intel_choose_pipe_bpp_dither. */
7928                         BUG();
7929                 }
7930         }
7931
7932         if (HAS_PIPE_CXSR(dev)) {
7933                 if (intel_crtc->lowfreq_avail) {
7934                         DRM_DEBUG_KMS("enabling CxSR downclocking\n");
7935                         pipeconf |= PIPECONF_CXSR_DOWNCLOCK;
7936                 } else {
7937                         DRM_DEBUG_KMS("disabling CxSR downclocking\n");
7938                 }
7939         }
7940
7941         if (intel_crtc->config->base.adjusted_mode.flags & DRM_MODE_FLAG_INTERLACE) {
7942                 if (INTEL_INFO(dev)->gen < 4 ||
7943                     intel_crtc_has_type(intel_crtc->config, INTEL_OUTPUT_SDVO))
7944                         pipeconf |= PIPECONF_INTERLACE_W_FIELD_INDICATION;
7945                 else
7946                         pipeconf |= PIPECONF_INTERLACE_W_SYNC_SHIFT;
7947         } else
7948                 pipeconf |= PIPECONF_PROGRESSIVE;
7949
7950         if ((IS_VALLEYVIEW(dev) || IS_CHERRYVIEW(dev)) &&
7951              intel_crtc->config->limited_color_range)
7952                 pipeconf |= PIPECONF_COLOR_RANGE_SELECT;
7953
7954         I915_WRITE(PIPECONF(intel_crtc->pipe), pipeconf);
7955         POSTING_READ(PIPECONF(intel_crtc->pipe));
7956 }
7957
7958 static int i8xx_crtc_compute_clock(struct intel_crtc *crtc,
7959                                    struct intel_crtc_state *crtc_state)
7960 {
7961         struct drm_device *dev = crtc->base.dev;
7962         struct drm_i915_private *dev_priv = to_i915(dev);
7963         const struct intel_limit *limit;
7964         int refclk = 48000;
7965
7966         memset(&crtc_state->dpll_hw_state, 0,
7967                sizeof(crtc_state->dpll_hw_state));
7968
7969         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS)) {
7970                 if (intel_panel_use_ssc(dev_priv)) {
7971                         refclk = dev_priv->vbt.lvds_ssc_freq;
7972                         DRM_DEBUG_KMS("using SSC reference clock of %d kHz\n", refclk);
7973                 }
7974
7975                 limit = &intel_limits_i8xx_lvds;
7976         } else if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_DVO)) {
7977                 limit = &intel_limits_i8xx_dvo;
7978         } else {
7979                 limit = &intel_limits_i8xx_dac;
7980         }
7981
7982         if (!crtc_state->clock_set &&
7983             !i9xx_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
7984                                  refclk, NULL, &crtc_state->dpll)) {
7985                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
7986                 return -EINVAL;
7987         }
7988
7989         i8xx_compute_dpll(crtc, crtc_state, NULL);
7990
7991         return 0;
7992 }
7993
7994 static int g4x_crtc_compute_clock(struct intel_crtc *crtc,
7995                                   struct intel_crtc_state *crtc_state)
7996 {
7997         struct drm_device *dev = crtc->base.dev;
7998         struct drm_i915_private *dev_priv = to_i915(dev);
7999         const struct intel_limit *limit;
8000         int refclk = 96000;
8001
8002         memset(&crtc_state->dpll_hw_state, 0,
8003                sizeof(crtc_state->dpll_hw_state));
8004
8005         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS)) {
8006                 if (intel_panel_use_ssc(dev_priv)) {
8007                         refclk = dev_priv->vbt.lvds_ssc_freq;
8008                         DRM_DEBUG_KMS("using SSC reference clock of %d kHz\n", refclk);
8009                 }
8010
8011                 if (intel_is_dual_link_lvds(dev))
8012                         limit = &intel_limits_g4x_dual_channel_lvds;
8013                 else
8014                         limit = &intel_limits_g4x_single_channel_lvds;
8015         } else if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_HDMI) ||
8016                    intel_crtc_has_type(crtc_state, INTEL_OUTPUT_ANALOG)) {
8017                 limit = &intel_limits_g4x_hdmi;
8018         } else if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_SDVO)) {
8019                 limit = &intel_limits_g4x_sdvo;
8020         } else {
8021                 /* The option is for other outputs */
8022                 limit = &intel_limits_i9xx_sdvo;
8023         }
8024
8025         if (!crtc_state->clock_set &&
8026             !g4x_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
8027                                 refclk, NULL, &crtc_state->dpll)) {
8028                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
8029                 return -EINVAL;
8030         }
8031
8032         i9xx_compute_dpll(crtc, crtc_state, NULL);
8033
8034         return 0;
8035 }
8036
8037 static int pnv_crtc_compute_clock(struct intel_crtc *crtc,
8038                                   struct intel_crtc_state *crtc_state)
8039 {
8040         struct drm_device *dev = crtc->base.dev;
8041         struct drm_i915_private *dev_priv = to_i915(dev);
8042         const struct intel_limit *limit;
8043         int refclk = 96000;
8044
8045         memset(&crtc_state->dpll_hw_state, 0,
8046                sizeof(crtc_state->dpll_hw_state));
8047
8048         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS)) {
8049                 if (intel_panel_use_ssc(dev_priv)) {
8050                         refclk = dev_priv->vbt.lvds_ssc_freq;
8051                         DRM_DEBUG_KMS("using SSC reference clock of %d kHz\n", refclk);
8052                 }
8053
8054                 limit = &intel_limits_pineview_lvds;
8055         } else {
8056                 limit = &intel_limits_pineview_sdvo;
8057         }
8058
8059         if (!crtc_state->clock_set &&
8060             !pnv_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
8061                                 refclk, NULL, &crtc_state->dpll)) {
8062                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
8063                 return -EINVAL;
8064         }
8065
8066         i9xx_compute_dpll(crtc, crtc_state, NULL);
8067
8068         return 0;
8069 }
8070
8071 static int i9xx_crtc_compute_clock(struct intel_crtc *crtc,
8072                                    struct intel_crtc_state *crtc_state)
8073 {
8074         struct drm_device *dev = crtc->base.dev;
8075         struct drm_i915_private *dev_priv = to_i915(dev);
8076         const struct intel_limit *limit;
8077         int refclk = 96000;
8078
8079         memset(&crtc_state->dpll_hw_state, 0,
8080                sizeof(crtc_state->dpll_hw_state));
8081
8082         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS)) {
8083                 if (intel_panel_use_ssc(dev_priv)) {
8084                         refclk = dev_priv->vbt.lvds_ssc_freq;
8085                         DRM_DEBUG_KMS("using SSC reference clock of %d kHz\n", refclk);
8086                 }
8087
8088                 limit = &intel_limits_i9xx_lvds;
8089         } else {
8090                 limit = &intel_limits_i9xx_sdvo;
8091         }
8092
8093         if (!crtc_state->clock_set &&
8094             !i9xx_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
8095                                  refclk, NULL, &crtc_state->dpll)) {
8096                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
8097                 return -EINVAL;
8098         }
8099
8100         i9xx_compute_dpll(crtc, crtc_state, NULL);
8101
8102         return 0;
8103 }
8104
8105 static int chv_crtc_compute_clock(struct intel_crtc *crtc,
8106                                   struct intel_crtc_state *crtc_state)
8107 {
8108         int refclk = 100000;
8109         const struct intel_limit *limit = &intel_limits_chv;
8110
8111         memset(&crtc_state->dpll_hw_state, 0,
8112                sizeof(crtc_state->dpll_hw_state));
8113
8114         if (!crtc_state->clock_set &&
8115             !chv_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
8116                                 refclk, NULL, &crtc_state->dpll)) {
8117                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
8118                 return -EINVAL;
8119         }
8120
8121         chv_compute_dpll(crtc, crtc_state);
8122
8123         return 0;
8124 }
8125
8126 static int vlv_crtc_compute_clock(struct intel_crtc *crtc,
8127                                   struct intel_crtc_state *crtc_state)
8128 {
8129         int refclk = 100000;
8130         const struct intel_limit *limit = &intel_limits_vlv;
8131
8132         memset(&crtc_state->dpll_hw_state, 0,
8133                sizeof(crtc_state->dpll_hw_state));
8134
8135         if (!crtc_state->clock_set &&
8136             !vlv_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
8137                                 refclk, NULL, &crtc_state->dpll)) {
8138                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
8139                 return -EINVAL;
8140         }
8141
8142         vlv_compute_dpll(crtc, crtc_state);
8143
8144         return 0;
8145 }
8146
8147 static void i9xx_get_pfit_config(struct intel_crtc *crtc,
8148                                  struct intel_crtc_state *pipe_config)
8149 {
8150         struct drm_device *dev = crtc->base.dev;
8151         struct drm_i915_private *dev_priv = to_i915(dev);
8152         uint32_t tmp;
8153
8154         if (INTEL_INFO(dev)->gen <= 3 && (IS_I830(dev) || !IS_MOBILE(dev)))
8155                 return;
8156
8157         tmp = I915_READ(PFIT_CONTROL);
8158         if (!(tmp & PFIT_ENABLE))
8159                 return;
8160
8161         /* Check whether the pfit is attached to our pipe. */
8162         if (INTEL_INFO(dev)->gen < 4) {
8163                 if (crtc->pipe != PIPE_B)
8164                         return;
8165         } else {
8166                 if ((tmp & PFIT_PIPE_MASK) != (crtc->pipe << PFIT_PIPE_SHIFT))
8167                         return;
8168         }
8169
8170         pipe_config->gmch_pfit.control = tmp;
8171         pipe_config->gmch_pfit.pgm_ratios = I915_READ(PFIT_PGM_RATIOS);
8172 }
8173
8174 static void vlv_crtc_clock_get(struct intel_crtc *crtc,
8175                                struct intel_crtc_state *pipe_config)
8176 {
8177         struct drm_device *dev = crtc->base.dev;
8178         struct drm_i915_private *dev_priv = to_i915(dev);
8179         int pipe = pipe_config->cpu_transcoder;
8180         struct dpll clock;
8181         u32 mdiv;
8182         int refclk = 100000;
8183
8184         /* In case of DSI, DPLL will not be used */
8185         if ((pipe_config->dpll_hw_state.dpll & DPLL_VCO_ENABLE) == 0)
8186                 return;
8187
8188         mutex_lock(&dev_priv->sb_lock);
8189         mdiv = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW3(pipe));
8190         mutex_unlock(&dev_priv->sb_lock);
8191
8192         clock.m1 = (mdiv >> DPIO_M1DIV_SHIFT) & 7;
8193         clock.m2 = mdiv & DPIO_M2DIV_MASK;
8194         clock.n = (mdiv >> DPIO_N_SHIFT) & 0xf;
8195         clock.p1 = (mdiv >> DPIO_P1_SHIFT) & 7;
8196         clock.p2 = (mdiv >> DPIO_P2_SHIFT) & 0x1f;
8197
8198         pipe_config->port_clock = vlv_calc_dpll_params(refclk, &clock);
8199 }
8200
8201 static void
8202 i9xx_get_initial_plane_config(struct intel_crtc *crtc,
8203                               struct intel_initial_plane_config *plane_config)
8204 {
8205         struct drm_device *dev = crtc->base.dev;
8206         struct drm_i915_private *dev_priv = to_i915(dev);
8207         u32 val, base, offset;
8208         int pipe = crtc->pipe, plane = crtc->plane;
8209         int fourcc, pixel_format;
8210         unsigned int aligned_height;
8211         struct drm_framebuffer *fb;
8212         struct intel_framebuffer *intel_fb;
8213
8214         val = I915_READ(DSPCNTR(plane));
8215         if (!(val & DISPLAY_PLANE_ENABLE))
8216                 return;
8217
8218         intel_fb = kzalloc(sizeof(*intel_fb), GFP_KERNEL);
8219         if (!intel_fb) {
8220                 DRM_DEBUG_KMS("failed to alloc fb\n");
8221                 return;
8222         }
8223
8224         fb = &intel_fb->base;
8225
8226         if (INTEL_INFO(dev)->gen >= 4) {
8227                 if (val & DISPPLANE_TILED) {
8228                         plane_config->tiling = I915_TILING_X;
8229                         fb->modifier[0] = I915_FORMAT_MOD_X_TILED;
8230                 }
8231         }
8232
8233         pixel_format = val & DISPPLANE_PIXFORMAT_MASK;
8234         fourcc = i9xx_format_to_fourcc(pixel_format);
8235         fb->pixel_format = fourcc;
8236         fb->bits_per_pixel = drm_format_plane_cpp(fourcc, 0) * 8;
8237
8238         if (INTEL_INFO(dev)->gen >= 4) {
8239                 if (plane_config->tiling)
8240                         offset = I915_READ(DSPTILEOFF(plane));
8241                 else
8242                         offset = I915_READ(DSPLINOFF(plane));
8243                 base = I915_READ(DSPSURF(plane)) & 0xfffff000;
8244         } else {
8245                 base = I915_READ(DSPADDR(plane));
8246         }
8247         plane_config->base = base;
8248
8249         val = I915_READ(PIPESRC(pipe));
8250         fb->width = ((val >> 16) & 0xfff) + 1;
8251         fb->height = ((val >> 0) & 0xfff) + 1;
8252
8253         val = I915_READ(DSPSTRIDE(pipe));
8254         fb->pitches[0] = val & 0xffffffc0;
8255
8256         aligned_height = intel_fb_align_height(dev, fb->height,
8257                                                fb->pixel_format,
8258                                                fb->modifier[0]);
8259
8260         plane_config->size = fb->pitches[0] * aligned_height;
8261
8262         DRM_DEBUG_KMS("pipe/plane %c/%d with fb: size=%dx%d@%d, offset=%x, pitch %d, size 0x%x\n",
8263                       pipe_name(pipe), plane, fb->width, fb->height,
8264                       fb->bits_per_pixel, base, fb->pitches[0],
8265                       plane_config->size);
8266
8267         plane_config->fb = intel_fb;
8268 }
8269
8270 static void chv_crtc_clock_get(struct intel_crtc *crtc,
8271                                struct intel_crtc_state *pipe_config)
8272 {
8273         struct drm_device *dev = crtc->base.dev;
8274         struct drm_i915_private *dev_priv = to_i915(dev);
8275         int pipe = pipe_config->cpu_transcoder;
8276         enum dpio_channel port = vlv_pipe_to_channel(pipe);
8277         struct dpll clock;
8278         u32 cmn_dw13, pll_dw0, pll_dw1, pll_dw2, pll_dw3;
8279         int refclk = 100000;
8280
8281         /* In case of DSI, DPLL will not be used */
8282         if ((pipe_config->dpll_hw_state.dpll & DPLL_VCO_ENABLE) == 0)
8283                 return;
8284
8285         mutex_lock(&dev_priv->sb_lock);
8286         cmn_dw13 = vlv_dpio_read(dev_priv, pipe, CHV_CMN_DW13(port));
8287         pll_dw0 = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW0(port));
8288         pll_dw1 = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW1(port));
8289         pll_dw2 = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW2(port));
8290         pll_dw3 = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW3(port));
8291         mutex_unlock(&dev_priv->sb_lock);
8292
8293         clock.m1 = (pll_dw1 & 0x7) == DPIO_CHV_M1_DIV_BY_2 ? 2 : 0;
8294         clock.m2 = (pll_dw0 & 0xff) << 22;
8295         if (pll_dw3 & DPIO_CHV_FRAC_DIV_EN)
8296                 clock.m2 |= pll_dw2 & 0x3fffff;
8297         clock.n = (pll_dw1 >> DPIO_CHV_N_DIV_SHIFT) & 0xf;
8298         clock.p1 = (cmn_dw13 >> DPIO_CHV_P1_DIV_SHIFT) & 0x7;
8299         clock.p2 = (cmn_dw13 >> DPIO_CHV_P2_DIV_SHIFT) & 0x1f;
8300
8301         pipe_config->port_clock = chv_calc_dpll_params(refclk, &clock);
8302 }
8303
8304 static bool i9xx_get_pipe_config(struct intel_crtc *crtc,
8305                                  struct intel_crtc_state *pipe_config)
8306 {
8307         struct drm_device *dev = crtc->base.dev;
8308         struct drm_i915_private *dev_priv = to_i915(dev);
8309         enum intel_display_power_domain power_domain;
8310         uint32_t tmp;
8311         bool ret;
8312
8313         power_domain = POWER_DOMAIN_PIPE(crtc->pipe);
8314         if (!intel_display_power_get_if_enabled(dev_priv, power_domain))
8315                 return false;
8316
8317         pipe_config->cpu_transcoder = (enum transcoder) crtc->pipe;
8318         pipe_config->shared_dpll = NULL;
8319
8320         ret = false;
8321
8322         tmp = I915_READ(PIPECONF(crtc->pipe));
8323         if (!(tmp & PIPECONF_ENABLE))
8324                 goto out;
8325
8326         if (IS_G4X(dev) || IS_VALLEYVIEW(dev) || IS_CHERRYVIEW(dev)) {
8327                 switch (tmp & PIPECONF_BPC_MASK) {
8328                 case PIPECONF_6BPC:
8329                         pipe_config->pipe_bpp = 18;
8330                         break;
8331                 case PIPECONF_8BPC:
8332                         pipe_config->pipe_bpp = 24;
8333                         break;
8334                 case PIPECONF_10BPC:
8335                         pipe_config->pipe_bpp = 30;
8336                         break;
8337                 default:
8338                         break;
8339                 }
8340         }
8341
8342         if ((IS_VALLEYVIEW(dev) || IS_CHERRYVIEW(dev)) &&
8343             (tmp & PIPECONF_COLOR_RANGE_SELECT))
8344                 pipe_config->limited_color_range = true;
8345
8346         if (INTEL_INFO(dev)->gen < 4)
8347                 pipe_config->double_wide = tmp & PIPECONF_DOUBLE_WIDE;
8348
8349         intel_get_pipe_timings(crtc, pipe_config);
8350         intel_get_pipe_src_size(crtc, pipe_config);
8351
8352         i9xx_get_pfit_config(crtc, pipe_config);
8353
8354         if (INTEL_INFO(dev)->gen >= 4) {
8355                 /* No way to read it out on pipes B and C */
8356                 if (IS_CHERRYVIEW(dev) && crtc->pipe != PIPE_A)
8357                         tmp = dev_priv->chv_dpll_md[crtc->pipe];
8358                 else
8359                         tmp = I915_READ(DPLL_MD(crtc->pipe));
8360                 pipe_config->pixel_multiplier =
8361                         ((tmp & DPLL_MD_UDI_MULTIPLIER_MASK)
8362                          >> DPLL_MD_UDI_MULTIPLIER_SHIFT) + 1;
8363                 pipe_config->dpll_hw_state.dpll_md = tmp;
8364         } else if (IS_I945G(dev) || IS_I945GM(dev) || IS_G33(dev)) {
8365                 tmp = I915_READ(DPLL(crtc->pipe));
8366                 pipe_config->pixel_multiplier =
8367                         ((tmp & SDVO_MULTIPLIER_MASK)
8368                          >> SDVO_MULTIPLIER_SHIFT_HIRES) + 1;
8369         } else {
8370                 /* Note that on i915G/GM the pixel multiplier is in the sdvo
8371                  * port and will be fixed up in the encoder->get_config
8372                  * function. */
8373                 pipe_config->pixel_multiplier = 1;
8374         }
8375         pipe_config->dpll_hw_state.dpll = I915_READ(DPLL(crtc->pipe));
8376         if (!IS_VALLEYVIEW(dev) && !IS_CHERRYVIEW(dev)) {
8377                 /*
8378                  * DPLL_DVO_2X_MODE must be enabled for both DPLLs
8379                  * on 830. Filter it out here so that we don't
8380                  * report errors due to that.
8381                  */
8382                 if (IS_I830(dev))
8383                         pipe_config->dpll_hw_state.dpll &= ~DPLL_DVO_2X_MODE;
8384
8385                 pipe_config->dpll_hw_state.fp0 = I915_READ(FP0(crtc->pipe));
8386                 pipe_config->dpll_hw_state.fp1 = I915_READ(FP1(crtc->pipe));
8387         } else {
8388                 /* Mask out read-only status bits. */
8389                 pipe_config->dpll_hw_state.dpll &= ~(DPLL_LOCK_VLV |
8390                                                      DPLL_PORTC_READY_MASK |
8391                                                      DPLL_PORTB_READY_MASK);
8392         }
8393
8394         if (IS_CHERRYVIEW(dev))
8395                 chv_crtc_clock_get(crtc, pipe_config);
8396         else if (IS_VALLEYVIEW(dev))
8397                 vlv_crtc_clock_get(crtc, pipe_config);
8398         else
8399                 i9xx_crtc_clock_get(crtc, pipe_config);
8400
8401         /*
8402          * Normally the dotclock is filled in by the encoder .get_config()
8403          * but in case the pipe is enabled w/o any ports we need a sane
8404          * default.
8405          */
8406         pipe_config->base.adjusted_mode.crtc_clock =
8407                 pipe_config->port_clock / pipe_config->pixel_multiplier;
8408
8409         ret = true;
8410
8411 out:
8412         intel_display_power_put(dev_priv, power_domain);
8413
8414         return ret;
8415 }
8416
8417 static void ironlake_init_pch_refclk(struct drm_device *dev)
8418 {
8419         struct drm_i915_private *dev_priv = to_i915(dev);
8420         struct intel_encoder *encoder;
8421         int i;
8422         u32 val, final;
8423         bool has_lvds = false;
8424         bool has_cpu_edp = false;
8425         bool has_panel = false;
8426         bool has_ck505 = false;
8427         bool can_ssc = false;
8428         bool using_ssc_source = false;
8429
8430         /* We need to take the global config into account */
8431         for_each_intel_encoder(dev, encoder) {
8432                 switch (encoder->type) {
8433                 case INTEL_OUTPUT_LVDS:
8434                         has_panel = true;
8435                         has_lvds = true;
8436                         break;
8437                 case INTEL_OUTPUT_EDP:
8438                         has_panel = true;
8439                         if (enc_to_dig_port(&encoder->base)->port == PORT_A)
8440                                 has_cpu_edp = true;
8441                         break;
8442                 default:
8443                         break;
8444                 }
8445         }
8446
8447         if (HAS_PCH_IBX(dev)) {
8448                 has_ck505 = dev_priv->vbt.display_clock_mode;
8449                 can_ssc = has_ck505;
8450         } else {
8451                 has_ck505 = false;
8452                 can_ssc = true;
8453         }
8454
8455         /* Check if any DPLLs are using the SSC source */
8456         for (i = 0; i < dev_priv->num_shared_dpll; i++) {
8457                 u32 temp = I915_READ(PCH_DPLL(i));
8458
8459                 if (!(temp & DPLL_VCO_ENABLE))
8460                         continue;
8461
8462                 if ((temp & PLL_REF_INPUT_MASK) ==
8463                     PLLB_REF_INPUT_SPREADSPECTRUMIN) {
8464                         using_ssc_source = true;
8465                         break;
8466                 }
8467         }
8468
8469         DRM_DEBUG_KMS("has_panel %d has_lvds %d has_ck505 %d using_ssc_source %d\n",
8470                       has_panel, has_lvds, has_ck505, using_ssc_source);
8471
8472         /* Ironlake: try to setup display ref clock before DPLL
8473          * enabling. This is only under driver's control after
8474          * PCH B stepping, previous chipset stepping should be
8475          * ignoring this setting.
8476          */
8477         val = I915_READ(PCH_DREF_CONTROL);
8478
8479         /* As we must carefully and slowly disable/enable each source in turn,
8480          * compute the final state we want first and check if we need to
8481          * make any changes at all.
8482          */
8483         final = val;
8484         final &= ~DREF_NONSPREAD_SOURCE_MASK;
8485         if (has_ck505)
8486                 final |= DREF_NONSPREAD_CK505_ENABLE;
8487         else
8488                 final |= DREF_NONSPREAD_SOURCE_ENABLE;
8489
8490         final &= ~DREF_SSC_SOURCE_MASK;
8491         final &= ~DREF_CPU_SOURCE_OUTPUT_MASK;
8492         final &= ~DREF_SSC1_ENABLE;
8493
8494         if (has_panel) {
8495                 final |= DREF_SSC_SOURCE_ENABLE;
8496
8497                 if (intel_panel_use_ssc(dev_priv) && can_ssc)
8498                         final |= DREF_SSC1_ENABLE;
8499
8500                 if (has_cpu_edp) {
8501                         if (intel_panel_use_ssc(dev_priv) && can_ssc)
8502                                 final |= DREF_CPU_SOURCE_OUTPUT_DOWNSPREAD;
8503                         else
8504                                 final |= DREF_CPU_SOURCE_OUTPUT_NONSPREAD;
8505                 } else
8506                         final |= DREF_CPU_SOURCE_OUTPUT_DISABLE;
8507         } else if (using_ssc_source) {
8508                 final |= DREF_SSC_SOURCE_ENABLE;
8509                 final |= DREF_SSC1_ENABLE;
8510         }
8511
8512         if (final == val)
8513                 return;
8514
8515         /* Always enable nonspread source */
8516         val &= ~DREF_NONSPREAD_SOURCE_MASK;
8517
8518         if (has_ck505)
8519                 val |= DREF_NONSPREAD_CK505_ENABLE;
8520         else
8521                 val |= DREF_NONSPREAD_SOURCE_ENABLE;
8522
8523         if (has_panel) {
8524                 val &= ~DREF_SSC_SOURCE_MASK;
8525                 val |= DREF_SSC_SOURCE_ENABLE;
8526
8527                 /* SSC must be turned on before enabling the CPU output  */
8528                 if (intel_panel_use_ssc(dev_priv) && can_ssc) {
8529                         DRM_DEBUG_KMS("Using SSC on panel\n");
8530                         val |= DREF_SSC1_ENABLE;
8531                 } else
8532                         val &= ~DREF_SSC1_ENABLE;
8533
8534                 /* Get SSC going before enabling the outputs */
8535                 I915_WRITE(PCH_DREF_CONTROL, val);
8536                 POSTING_READ(PCH_DREF_CONTROL);
8537                 udelay(200);
8538
8539                 val &= ~DREF_CPU_SOURCE_OUTPUT_MASK;
8540
8541                 /* Enable CPU source on CPU attached eDP */
8542                 if (has_cpu_edp) {
8543                         if (intel_panel_use_ssc(dev_priv) && can_ssc) {
8544                                 DRM_DEBUG_KMS("Using SSC on eDP\n");
8545                                 val |= DREF_CPU_SOURCE_OUTPUT_DOWNSPREAD;
8546                         } else
8547                                 val |= DREF_CPU_SOURCE_OUTPUT_NONSPREAD;
8548                 } else
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         } else {
8555                 DRM_DEBUG_KMS("Disabling CPU source output\n");
8556
8557                 val &= ~DREF_CPU_SOURCE_OUTPUT_MASK;
8558
8559                 /* Turn off CPU output */
8560                 val |= DREF_CPU_SOURCE_OUTPUT_DISABLE;
8561
8562                 I915_WRITE(PCH_DREF_CONTROL, val);
8563                 POSTING_READ(PCH_DREF_CONTROL);
8564                 udelay(200);
8565
8566                 if (!using_ssc_source) {
8567                         DRM_DEBUG_KMS("Disabling SSC source\n");
8568
8569                         /* Turn off the SSC source */
8570                         val &= ~DREF_SSC_SOURCE_MASK;
8571                         val |= DREF_SSC_SOURCE_DISABLE;
8572
8573                         /* Turn off SSC1 */
8574                         val &= ~DREF_SSC1_ENABLE;
8575
8576                         I915_WRITE(PCH_DREF_CONTROL, val);
8577                         POSTING_READ(PCH_DREF_CONTROL);
8578                         udelay(200);
8579                 }
8580         }
8581
8582         BUG_ON(val != final);
8583 }
8584
8585 static void lpt_reset_fdi_mphy(struct drm_i915_private *dev_priv)
8586 {
8587         uint32_t tmp;
8588
8589         tmp = I915_READ(SOUTH_CHICKEN2);
8590         tmp |= FDI_MPHY_IOSFSB_RESET_CTL;
8591         I915_WRITE(SOUTH_CHICKEN2, tmp);
8592
8593         if (wait_for_us(I915_READ(SOUTH_CHICKEN2) &
8594                         FDI_MPHY_IOSFSB_RESET_STATUS, 100))
8595                 DRM_ERROR("FDI mPHY reset assert timeout\n");
8596
8597         tmp = I915_READ(SOUTH_CHICKEN2);
8598         tmp &= ~FDI_MPHY_IOSFSB_RESET_CTL;
8599         I915_WRITE(SOUTH_CHICKEN2, tmp);
8600
8601         if (wait_for_us((I915_READ(SOUTH_CHICKEN2) &
8602                          FDI_MPHY_IOSFSB_RESET_STATUS) == 0, 100))
8603                 DRM_ERROR("FDI mPHY reset de-assert timeout\n");
8604 }
8605
8606 /* WaMPhyProgramming:hsw */
8607 static void lpt_program_fdi_mphy(struct drm_i915_private *dev_priv)
8608 {
8609         uint32_t tmp;
8610
8611         tmp = intel_sbi_read(dev_priv, 0x8008, SBI_MPHY);
8612         tmp &= ~(0xFF << 24);
8613         tmp |= (0x12 << 24);
8614         intel_sbi_write(dev_priv, 0x8008, tmp, SBI_MPHY);
8615
8616         tmp = intel_sbi_read(dev_priv, 0x2008, SBI_MPHY);
8617         tmp |= (1 << 11);
8618         intel_sbi_write(dev_priv, 0x2008, tmp, SBI_MPHY);
8619
8620         tmp = intel_sbi_read(dev_priv, 0x2108, SBI_MPHY);
8621         tmp |= (1 << 11);
8622         intel_sbi_write(dev_priv, 0x2108, tmp, SBI_MPHY);
8623
8624         tmp = intel_sbi_read(dev_priv, 0x206C, SBI_MPHY);
8625         tmp |= (1 << 24) | (1 << 21) | (1 << 18);
8626         intel_sbi_write(dev_priv, 0x206C, tmp, SBI_MPHY);
8627
8628         tmp = intel_sbi_read(dev_priv, 0x216C, SBI_MPHY);
8629         tmp |= (1 << 24) | (1 << 21) | (1 << 18);
8630         intel_sbi_write(dev_priv, 0x216C, tmp, SBI_MPHY);
8631
8632         tmp = intel_sbi_read(dev_priv, 0x2080, SBI_MPHY);
8633         tmp &= ~(7 << 13);
8634         tmp |= (5 << 13);
8635         intel_sbi_write(dev_priv, 0x2080, tmp, SBI_MPHY);
8636
8637         tmp = intel_sbi_read(dev_priv, 0x2180, SBI_MPHY);
8638         tmp &= ~(7 << 13);
8639         tmp |= (5 << 13);
8640         intel_sbi_write(dev_priv, 0x2180, tmp, SBI_MPHY);
8641
8642         tmp = intel_sbi_read(dev_priv, 0x208C, SBI_MPHY);
8643         tmp &= ~0xFF;
8644         tmp |= 0x1C;
8645         intel_sbi_write(dev_priv, 0x208C, tmp, SBI_MPHY);
8646
8647         tmp = intel_sbi_read(dev_priv, 0x218C, SBI_MPHY);
8648         tmp &= ~0xFF;
8649         tmp |= 0x1C;
8650         intel_sbi_write(dev_priv, 0x218C, tmp, SBI_MPHY);
8651
8652         tmp = intel_sbi_read(dev_priv, 0x2098, SBI_MPHY);
8653         tmp &= ~(0xFF << 16);
8654         tmp |= (0x1C << 16);
8655         intel_sbi_write(dev_priv, 0x2098, tmp, SBI_MPHY);
8656
8657         tmp = intel_sbi_read(dev_priv, 0x2198, SBI_MPHY);
8658         tmp &= ~(0xFF << 16);
8659         tmp |= (0x1C << 16);
8660         intel_sbi_write(dev_priv, 0x2198, tmp, SBI_MPHY);
8661
8662         tmp = intel_sbi_read(dev_priv, 0x20C4, SBI_MPHY);
8663         tmp |= (1 << 27);
8664         intel_sbi_write(dev_priv, 0x20C4, tmp, SBI_MPHY);
8665
8666         tmp = intel_sbi_read(dev_priv, 0x21C4, SBI_MPHY);
8667         tmp |= (1 << 27);
8668         intel_sbi_write(dev_priv, 0x21C4, tmp, SBI_MPHY);
8669
8670         tmp = intel_sbi_read(dev_priv, 0x20EC, SBI_MPHY);
8671         tmp &= ~(0xF << 28);
8672         tmp |= (4 << 28);
8673         intel_sbi_write(dev_priv, 0x20EC, tmp, SBI_MPHY);
8674
8675         tmp = intel_sbi_read(dev_priv, 0x21EC, SBI_MPHY);
8676         tmp &= ~(0xF << 28);
8677         tmp |= (4 << 28);
8678         intel_sbi_write(dev_priv, 0x21EC, tmp, SBI_MPHY);
8679 }
8680
8681 /* Implements 3 different sequences from BSpec chapter "Display iCLK
8682  * Programming" based on the parameters passed:
8683  * - Sequence to enable CLKOUT_DP
8684  * - Sequence to enable CLKOUT_DP without spread
8685  * - Sequence to enable CLKOUT_DP for FDI usage and configure PCH FDI I/O
8686  */
8687 static void lpt_enable_clkout_dp(struct drm_device *dev, bool with_spread,
8688                                  bool with_fdi)
8689 {
8690         struct drm_i915_private *dev_priv = to_i915(dev);
8691         uint32_t reg, tmp;
8692
8693         if (WARN(with_fdi && !with_spread, "FDI requires downspread\n"))
8694                 with_spread = true;
8695         if (WARN(HAS_PCH_LPT_LP(dev) && with_fdi, "LP PCH doesn't have FDI\n"))
8696                 with_fdi = false;
8697
8698         mutex_lock(&dev_priv->sb_lock);
8699
8700         tmp = intel_sbi_read(dev_priv, SBI_SSCCTL, SBI_ICLK);
8701         tmp &= ~SBI_SSCCTL_DISABLE;
8702         tmp |= SBI_SSCCTL_PATHALT;
8703         intel_sbi_write(dev_priv, SBI_SSCCTL, tmp, SBI_ICLK);
8704
8705         udelay(24);
8706
8707         if (with_spread) {
8708                 tmp = intel_sbi_read(dev_priv, SBI_SSCCTL, SBI_ICLK);
8709                 tmp &= ~SBI_SSCCTL_PATHALT;
8710                 intel_sbi_write(dev_priv, SBI_SSCCTL, tmp, SBI_ICLK);
8711
8712                 if (with_fdi) {
8713                         lpt_reset_fdi_mphy(dev_priv);
8714                         lpt_program_fdi_mphy(dev_priv);
8715                 }
8716         }
8717
8718         reg = HAS_PCH_LPT_LP(dev) ? SBI_GEN0 : SBI_DBUFF0;
8719         tmp = intel_sbi_read(dev_priv, reg, SBI_ICLK);
8720         tmp |= SBI_GEN0_CFG_BUFFENABLE_DISABLE;
8721         intel_sbi_write(dev_priv, reg, tmp, SBI_ICLK);
8722
8723         mutex_unlock(&dev_priv->sb_lock);
8724 }
8725
8726 /* Sequence to disable CLKOUT_DP */
8727 static void lpt_disable_clkout_dp(struct drm_device *dev)
8728 {
8729         struct drm_i915_private *dev_priv = to_i915(dev);
8730         uint32_t reg, tmp;
8731
8732         mutex_lock(&dev_priv->sb_lock);
8733
8734         reg = HAS_PCH_LPT_LP(dev) ? SBI_GEN0 : SBI_DBUFF0;
8735         tmp = intel_sbi_read(dev_priv, reg, SBI_ICLK);
8736         tmp &= ~SBI_GEN0_CFG_BUFFENABLE_DISABLE;
8737         intel_sbi_write(dev_priv, reg, tmp, SBI_ICLK);
8738
8739         tmp = intel_sbi_read(dev_priv, SBI_SSCCTL, SBI_ICLK);
8740         if (!(tmp & SBI_SSCCTL_DISABLE)) {
8741                 if (!(tmp & SBI_SSCCTL_PATHALT)) {
8742                         tmp |= SBI_SSCCTL_PATHALT;
8743                         intel_sbi_write(dev_priv, SBI_SSCCTL, tmp, SBI_ICLK);
8744                         udelay(32);
8745                 }
8746                 tmp |= SBI_SSCCTL_DISABLE;
8747                 intel_sbi_write(dev_priv, SBI_SSCCTL, tmp, SBI_ICLK);
8748         }
8749
8750         mutex_unlock(&dev_priv->sb_lock);
8751 }
8752
8753 #define BEND_IDX(steps) ((50 + (steps)) / 5)
8754
8755 static const uint16_t sscdivintphase[] = {
8756         [BEND_IDX( 50)] = 0x3B23,
8757         [BEND_IDX( 45)] = 0x3B23,
8758         [BEND_IDX( 40)] = 0x3C23,
8759         [BEND_IDX( 35)] = 0x3C23,
8760         [BEND_IDX( 30)] = 0x3D23,
8761         [BEND_IDX( 25)] = 0x3D23,
8762         [BEND_IDX( 20)] = 0x3E23,
8763         [BEND_IDX( 15)] = 0x3E23,
8764         [BEND_IDX( 10)] = 0x3F23,
8765         [BEND_IDX(  5)] = 0x3F23,
8766         [BEND_IDX(  0)] = 0x0025,
8767         [BEND_IDX( -5)] = 0x0025,
8768         [BEND_IDX(-10)] = 0x0125,
8769         [BEND_IDX(-15)] = 0x0125,
8770         [BEND_IDX(-20)] = 0x0225,
8771         [BEND_IDX(-25)] = 0x0225,
8772         [BEND_IDX(-30)] = 0x0325,
8773         [BEND_IDX(-35)] = 0x0325,
8774         [BEND_IDX(-40)] = 0x0425,
8775         [BEND_IDX(-45)] = 0x0425,
8776         [BEND_IDX(-50)] = 0x0525,
8777 };
8778
8779 /*
8780  * Bend CLKOUT_DP
8781  * steps -50 to 50 inclusive, in steps of 5
8782  * < 0 slow down the clock, > 0 speed up the clock, 0 == no bend (135MHz)
8783  * change in clock period = -(steps / 10) * 5.787 ps
8784  */
8785 static void lpt_bend_clkout_dp(struct drm_i915_private *dev_priv, int steps)
8786 {
8787         uint32_t tmp;
8788         int idx = BEND_IDX(steps);
8789
8790         if (WARN_ON(steps % 5 != 0))
8791                 return;
8792
8793         if (WARN_ON(idx >= ARRAY_SIZE(sscdivintphase)))
8794                 return;
8795
8796         mutex_lock(&dev_priv->sb_lock);
8797
8798         if (steps % 10 != 0)
8799                 tmp = 0xAAAAAAAB;
8800         else
8801                 tmp = 0x00000000;
8802         intel_sbi_write(dev_priv, SBI_SSCDITHPHASE, tmp, SBI_ICLK);
8803
8804         tmp = intel_sbi_read(dev_priv, SBI_SSCDIVINTPHASE, SBI_ICLK);
8805         tmp &= 0xffff0000;
8806         tmp |= sscdivintphase[idx];
8807         intel_sbi_write(dev_priv, SBI_SSCDIVINTPHASE, tmp, SBI_ICLK);
8808
8809         mutex_unlock(&dev_priv->sb_lock);
8810 }
8811
8812 #undef BEND_IDX
8813
8814 static void lpt_init_pch_refclk(struct drm_device *dev)
8815 {
8816         struct intel_encoder *encoder;
8817         bool has_vga = false;
8818
8819         for_each_intel_encoder(dev, encoder) {
8820                 switch (encoder->type) {
8821                 case INTEL_OUTPUT_ANALOG:
8822                         has_vga = true;
8823                         break;
8824                 default:
8825                         break;
8826                 }
8827         }
8828
8829         if (has_vga) {
8830                 lpt_bend_clkout_dp(to_i915(dev), 0);
8831                 lpt_enable_clkout_dp(dev, true, true);
8832         } else {
8833                 lpt_disable_clkout_dp(dev);
8834         }
8835 }
8836
8837 /*
8838  * Initialize reference clocks when the driver loads
8839  */
8840 void intel_init_pch_refclk(struct drm_device *dev)
8841 {
8842         if (HAS_PCH_IBX(dev) || HAS_PCH_CPT(dev))
8843                 ironlake_init_pch_refclk(dev);
8844         else if (HAS_PCH_LPT(dev))
8845                 lpt_init_pch_refclk(dev);
8846 }
8847
8848 static void ironlake_set_pipeconf(struct drm_crtc *crtc)
8849 {
8850         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
8851         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
8852         int pipe = intel_crtc->pipe;
8853         uint32_t val;
8854
8855         val = 0;
8856
8857         switch (intel_crtc->config->pipe_bpp) {
8858         case 18:
8859                 val |= PIPECONF_6BPC;
8860                 break;
8861         case 24:
8862                 val |= PIPECONF_8BPC;
8863                 break;
8864         case 30:
8865                 val |= PIPECONF_10BPC;
8866                 break;
8867         case 36:
8868                 val |= PIPECONF_12BPC;
8869                 break;
8870         default:
8871                 /* Case prevented by intel_choose_pipe_bpp_dither. */
8872                 BUG();
8873         }
8874
8875         if (intel_crtc->config->dither)
8876                 val |= (PIPECONF_DITHER_EN | PIPECONF_DITHER_TYPE_SP);
8877
8878         if (intel_crtc->config->base.adjusted_mode.flags & DRM_MODE_FLAG_INTERLACE)
8879                 val |= PIPECONF_INTERLACED_ILK;
8880         else
8881                 val |= PIPECONF_PROGRESSIVE;
8882
8883         if (intel_crtc->config->limited_color_range)
8884                 val |= PIPECONF_COLOR_RANGE_SELECT;
8885
8886         I915_WRITE(PIPECONF(pipe), val);
8887         POSTING_READ(PIPECONF(pipe));
8888 }
8889
8890 static void haswell_set_pipeconf(struct drm_crtc *crtc)
8891 {
8892         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
8893         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
8894         enum transcoder cpu_transcoder = intel_crtc->config->cpu_transcoder;
8895         u32 val = 0;
8896
8897         if (IS_HASWELL(dev_priv) && intel_crtc->config->dither)
8898                 val |= (PIPECONF_DITHER_EN | PIPECONF_DITHER_TYPE_SP);
8899
8900         if (intel_crtc->config->base.adjusted_mode.flags & DRM_MODE_FLAG_INTERLACE)
8901                 val |= PIPECONF_INTERLACED_ILK;
8902         else
8903                 val |= PIPECONF_PROGRESSIVE;
8904
8905         I915_WRITE(PIPECONF(cpu_transcoder), val);
8906         POSTING_READ(PIPECONF(cpu_transcoder));
8907 }
8908
8909 static void haswell_set_pipemisc(struct drm_crtc *crtc)
8910 {
8911         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
8912         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
8913
8914         if (IS_BROADWELL(dev_priv) || INTEL_INFO(dev_priv)->gen >= 9) {
8915                 u32 val = 0;
8916
8917                 switch (intel_crtc->config->pipe_bpp) {
8918                 case 18:
8919                         val |= PIPEMISC_DITHER_6_BPC;
8920                         break;
8921                 case 24:
8922                         val |= PIPEMISC_DITHER_8_BPC;
8923                         break;
8924                 case 30:
8925                         val |= PIPEMISC_DITHER_10_BPC;
8926                         break;
8927                 case 36:
8928                         val |= PIPEMISC_DITHER_12_BPC;
8929                         break;
8930                 default:
8931                         /* Case prevented by pipe_config_set_bpp. */
8932                         BUG();
8933                 }
8934
8935                 if (intel_crtc->config->dither)
8936                         val |= PIPEMISC_DITHER_ENABLE | PIPEMISC_DITHER_TYPE_SP;
8937
8938                 I915_WRITE(PIPEMISC(intel_crtc->pipe), val);
8939         }
8940 }
8941
8942 int ironlake_get_lanes_required(int target_clock, int link_bw, int bpp)
8943 {
8944         /*
8945          * Account for spread spectrum to avoid
8946          * oversubscribing the link. Max center spread
8947          * is 2.5%; use 5% for safety's sake.
8948          */
8949         u32 bps = target_clock * bpp * 21 / 20;
8950         return DIV_ROUND_UP(bps, link_bw * 8);
8951 }
8952
8953 static bool ironlake_needs_fb_cb_tune(struct dpll *dpll, int factor)
8954 {
8955         return i9xx_dpll_compute_m(dpll) < factor * dpll->n;
8956 }
8957
8958 static void ironlake_compute_dpll(struct intel_crtc *intel_crtc,
8959                                   struct intel_crtc_state *crtc_state,
8960                                   struct dpll *reduced_clock)
8961 {
8962         struct drm_crtc *crtc = &intel_crtc->base;
8963         struct drm_device *dev = crtc->dev;
8964         struct drm_i915_private *dev_priv = to_i915(dev);
8965         u32 dpll, fp, fp2;
8966         int factor;
8967
8968         /* Enable autotuning of the PLL clock (if permissible) */
8969         factor = 21;
8970         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS)) {
8971                 if ((intel_panel_use_ssc(dev_priv) &&
8972                      dev_priv->vbt.lvds_ssc_freq == 100000) ||
8973                     (HAS_PCH_IBX(dev) && intel_is_dual_link_lvds(dev)))
8974                         factor = 25;
8975         } else if (crtc_state->sdvo_tv_clock)
8976                 factor = 20;
8977
8978         fp = i9xx_dpll_compute_fp(&crtc_state->dpll);
8979
8980         if (ironlake_needs_fb_cb_tune(&crtc_state->dpll, factor))
8981                 fp |= FP_CB_TUNE;
8982
8983         if (reduced_clock) {
8984                 fp2 = i9xx_dpll_compute_fp(reduced_clock);
8985
8986                 if (reduced_clock->m < factor * reduced_clock->n)
8987                         fp2 |= FP_CB_TUNE;
8988         } else {
8989                 fp2 = fp;
8990         }
8991
8992         dpll = 0;
8993
8994         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS))
8995                 dpll |= DPLLB_MODE_LVDS;
8996         else
8997                 dpll |= DPLLB_MODE_DAC_SERIAL;
8998
8999         dpll |= (crtc_state->pixel_multiplier - 1)
9000                 << PLL_REF_SDVO_HDMI_MULTIPLIER_SHIFT;
9001
9002         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_SDVO) ||
9003             intel_crtc_has_type(crtc_state, INTEL_OUTPUT_HDMI))
9004                 dpll |= DPLL_SDVO_HIGH_SPEED;
9005
9006         if (intel_crtc_has_dp_encoder(crtc_state))
9007                 dpll |= DPLL_SDVO_HIGH_SPEED;
9008
9009         /* compute bitmask from p1 value */
9010         dpll |= (1 << (crtc_state->dpll.p1 - 1)) << DPLL_FPA01_P1_POST_DIV_SHIFT;
9011         /* also FPA1 */
9012         dpll |= (1 << (crtc_state->dpll.p1 - 1)) << DPLL_FPA1_P1_POST_DIV_SHIFT;
9013
9014         switch (crtc_state->dpll.p2) {
9015         case 5:
9016                 dpll |= DPLL_DAC_SERIAL_P2_CLOCK_DIV_5;
9017                 break;
9018         case 7:
9019                 dpll |= DPLLB_LVDS_P2_CLOCK_DIV_7;
9020                 break;
9021         case 10:
9022                 dpll |= DPLL_DAC_SERIAL_P2_CLOCK_DIV_10;
9023                 break;
9024         case 14:
9025                 dpll |= DPLLB_LVDS_P2_CLOCK_DIV_14;
9026                 break;
9027         }
9028
9029         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS) &&
9030             intel_panel_use_ssc(dev_priv))
9031                 dpll |= PLLB_REF_INPUT_SPREADSPECTRUMIN;
9032         else
9033                 dpll |= PLL_REF_INPUT_DREFCLK;
9034
9035         dpll |= DPLL_VCO_ENABLE;
9036
9037         crtc_state->dpll_hw_state.dpll = dpll;
9038         crtc_state->dpll_hw_state.fp0 = fp;
9039         crtc_state->dpll_hw_state.fp1 = fp2;
9040 }
9041
9042 static int ironlake_crtc_compute_clock(struct intel_crtc *crtc,
9043                                        struct intel_crtc_state *crtc_state)
9044 {
9045         struct drm_device *dev = crtc->base.dev;
9046         struct drm_i915_private *dev_priv = to_i915(dev);
9047         struct dpll reduced_clock;
9048         bool has_reduced_clock = false;
9049         struct intel_shared_dpll *pll;
9050         const struct intel_limit *limit;
9051         int refclk = 120000;
9052
9053         memset(&crtc_state->dpll_hw_state, 0,
9054                sizeof(crtc_state->dpll_hw_state));
9055
9056         crtc->lowfreq_avail = false;
9057
9058         /* CPU eDP is the only output that doesn't need a PCH PLL of its own. */
9059         if (!crtc_state->has_pch_encoder)
9060                 return 0;
9061
9062         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS)) {
9063                 if (intel_panel_use_ssc(dev_priv)) {
9064                         DRM_DEBUG_KMS("using SSC reference clock of %d kHz\n",
9065                                       dev_priv->vbt.lvds_ssc_freq);
9066                         refclk = dev_priv->vbt.lvds_ssc_freq;
9067                 }
9068
9069                 if (intel_is_dual_link_lvds(dev)) {
9070                         if (refclk == 100000)
9071                                 limit = &intel_limits_ironlake_dual_lvds_100m;
9072                         else
9073                                 limit = &intel_limits_ironlake_dual_lvds;
9074                 } else {
9075                         if (refclk == 100000)
9076                                 limit = &intel_limits_ironlake_single_lvds_100m;
9077                         else
9078                                 limit = &intel_limits_ironlake_single_lvds;
9079                 }
9080         } else {
9081                 limit = &intel_limits_ironlake_dac;
9082         }
9083
9084         if (!crtc_state->clock_set &&
9085             !g4x_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
9086                                 refclk, NULL, &crtc_state->dpll)) {
9087                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
9088                 return -EINVAL;
9089         }
9090
9091         ironlake_compute_dpll(crtc, crtc_state,
9092                               has_reduced_clock ? &reduced_clock : NULL);
9093
9094         pll = intel_get_shared_dpll(crtc, crtc_state, NULL);
9095         if (pll == NULL) {
9096                 DRM_DEBUG_DRIVER("failed to find PLL for pipe %c\n",
9097                                  pipe_name(crtc->pipe));
9098                 return -EINVAL;
9099         }
9100
9101         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS) &&
9102             has_reduced_clock)
9103                 crtc->lowfreq_avail = true;
9104
9105         return 0;
9106 }
9107
9108 static void intel_pch_transcoder_get_m_n(struct intel_crtc *crtc,
9109                                          struct intel_link_m_n *m_n)
9110 {
9111         struct drm_device *dev = crtc->base.dev;
9112         struct drm_i915_private *dev_priv = to_i915(dev);
9113         enum pipe pipe = crtc->pipe;
9114
9115         m_n->link_m = I915_READ(PCH_TRANS_LINK_M1(pipe));
9116         m_n->link_n = I915_READ(PCH_TRANS_LINK_N1(pipe));
9117         m_n->gmch_m = I915_READ(PCH_TRANS_DATA_M1(pipe))
9118                 & ~TU_SIZE_MASK;
9119         m_n->gmch_n = I915_READ(PCH_TRANS_DATA_N1(pipe));
9120         m_n->tu = ((I915_READ(PCH_TRANS_DATA_M1(pipe))
9121                     & TU_SIZE_MASK) >> TU_SIZE_SHIFT) + 1;
9122 }
9123
9124 static void intel_cpu_transcoder_get_m_n(struct intel_crtc *crtc,
9125                                          enum transcoder transcoder,
9126                                          struct intel_link_m_n *m_n,
9127                                          struct intel_link_m_n *m2_n2)
9128 {
9129         struct drm_device *dev = crtc->base.dev;
9130         struct drm_i915_private *dev_priv = to_i915(dev);
9131         enum pipe pipe = crtc->pipe;
9132
9133         if (INTEL_INFO(dev)->gen >= 5) {
9134                 m_n->link_m = I915_READ(PIPE_LINK_M1(transcoder));
9135                 m_n->link_n = I915_READ(PIPE_LINK_N1(transcoder));
9136                 m_n->gmch_m = I915_READ(PIPE_DATA_M1(transcoder))
9137                         & ~TU_SIZE_MASK;
9138                 m_n->gmch_n = I915_READ(PIPE_DATA_N1(transcoder));
9139                 m_n->tu = ((I915_READ(PIPE_DATA_M1(transcoder))
9140                             & TU_SIZE_MASK) >> TU_SIZE_SHIFT) + 1;
9141                 /* Read M2_N2 registers only for gen < 8 (M2_N2 available for
9142                  * gen < 8) and if DRRS is supported (to make sure the
9143                  * registers are not unnecessarily read).
9144                  */
9145                 if (m2_n2 && INTEL_INFO(dev)->gen < 8 &&
9146                         crtc->config->has_drrs) {
9147                         m2_n2->link_m = I915_READ(PIPE_LINK_M2(transcoder));
9148                         m2_n2->link_n = I915_READ(PIPE_LINK_N2(transcoder));
9149                         m2_n2->gmch_m = I915_READ(PIPE_DATA_M2(transcoder))
9150                                         & ~TU_SIZE_MASK;
9151                         m2_n2->gmch_n = I915_READ(PIPE_DATA_N2(transcoder));
9152                         m2_n2->tu = ((I915_READ(PIPE_DATA_M2(transcoder))
9153                                         & TU_SIZE_MASK) >> TU_SIZE_SHIFT) + 1;
9154                 }
9155         } else {
9156                 m_n->link_m = I915_READ(PIPE_LINK_M_G4X(pipe));
9157                 m_n->link_n = I915_READ(PIPE_LINK_N_G4X(pipe));
9158                 m_n->gmch_m = I915_READ(PIPE_DATA_M_G4X(pipe))
9159                         & ~TU_SIZE_MASK;
9160                 m_n->gmch_n = I915_READ(PIPE_DATA_N_G4X(pipe));
9161                 m_n->tu = ((I915_READ(PIPE_DATA_M_G4X(pipe))
9162                             & TU_SIZE_MASK) >> TU_SIZE_SHIFT) + 1;
9163         }
9164 }
9165
9166 void intel_dp_get_m_n(struct intel_crtc *crtc,
9167                       struct intel_crtc_state *pipe_config)
9168 {
9169         if (pipe_config->has_pch_encoder)
9170                 intel_pch_transcoder_get_m_n(crtc, &pipe_config->dp_m_n);
9171         else
9172                 intel_cpu_transcoder_get_m_n(crtc, pipe_config->cpu_transcoder,
9173                                              &pipe_config->dp_m_n,
9174                                              &pipe_config->dp_m2_n2);
9175 }
9176
9177 static void ironlake_get_fdi_m_n_config(struct intel_crtc *crtc,
9178                                         struct intel_crtc_state *pipe_config)
9179 {
9180         intel_cpu_transcoder_get_m_n(crtc, pipe_config->cpu_transcoder,
9181                                      &pipe_config->fdi_m_n, NULL);
9182 }
9183
9184 static void skylake_get_pfit_config(struct intel_crtc *crtc,
9185                                     struct intel_crtc_state *pipe_config)
9186 {
9187         struct drm_device *dev = crtc->base.dev;
9188         struct drm_i915_private *dev_priv = to_i915(dev);
9189         struct intel_crtc_scaler_state *scaler_state = &pipe_config->scaler_state;
9190         uint32_t ps_ctrl = 0;
9191         int id = -1;
9192         int i;
9193
9194         /* find scaler attached to this pipe */
9195         for (i = 0; i < crtc->num_scalers; i++) {
9196                 ps_ctrl = I915_READ(SKL_PS_CTRL(crtc->pipe, i));
9197                 if (ps_ctrl & PS_SCALER_EN && !(ps_ctrl & PS_PLANE_SEL_MASK)) {
9198                         id = i;
9199                         pipe_config->pch_pfit.enabled = true;
9200                         pipe_config->pch_pfit.pos = I915_READ(SKL_PS_WIN_POS(crtc->pipe, i));
9201                         pipe_config->pch_pfit.size = I915_READ(SKL_PS_WIN_SZ(crtc->pipe, i));
9202                         break;
9203                 }
9204         }
9205
9206         scaler_state->scaler_id = id;
9207         if (id >= 0) {
9208                 scaler_state->scaler_users |= (1 << SKL_CRTC_INDEX);
9209         } else {
9210                 scaler_state->scaler_users &= ~(1 << SKL_CRTC_INDEX);
9211         }
9212 }
9213
9214 static void
9215 skylake_get_initial_plane_config(struct intel_crtc *crtc,
9216                                  struct intel_initial_plane_config *plane_config)
9217 {
9218         struct drm_device *dev = crtc->base.dev;
9219         struct drm_i915_private *dev_priv = to_i915(dev);
9220         u32 val, base, offset, stride_mult, tiling;
9221         int pipe = crtc->pipe;
9222         int fourcc, pixel_format;
9223         unsigned int aligned_height;
9224         struct drm_framebuffer *fb;
9225         struct intel_framebuffer *intel_fb;
9226
9227         intel_fb = kzalloc(sizeof(*intel_fb), GFP_KERNEL);
9228         if (!intel_fb) {
9229                 DRM_DEBUG_KMS("failed to alloc fb\n");
9230                 return;
9231         }
9232
9233         fb = &intel_fb->base;
9234
9235         val = I915_READ(PLANE_CTL(pipe, 0));
9236         if (!(val & PLANE_CTL_ENABLE))
9237                 goto error;
9238
9239         pixel_format = val & PLANE_CTL_FORMAT_MASK;
9240         fourcc = skl_format_to_fourcc(pixel_format,
9241                                       val & PLANE_CTL_ORDER_RGBX,
9242                                       val & PLANE_CTL_ALPHA_MASK);
9243         fb->pixel_format = fourcc;
9244         fb->bits_per_pixel = drm_format_plane_cpp(fourcc, 0) * 8;
9245
9246         tiling = val & PLANE_CTL_TILED_MASK;
9247         switch (tiling) {
9248         case PLANE_CTL_TILED_LINEAR:
9249                 fb->modifier[0] = DRM_FORMAT_MOD_NONE;
9250                 break;
9251         case PLANE_CTL_TILED_X:
9252                 plane_config->tiling = I915_TILING_X;
9253                 fb->modifier[0] = I915_FORMAT_MOD_X_TILED;
9254                 break;
9255         case PLANE_CTL_TILED_Y:
9256                 fb->modifier[0] = I915_FORMAT_MOD_Y_TILED;
9257                 break;
9258         case PLANE_CTL_TILED_YF:
9259                 fb->modifier[0] = I915_FORMAT_MOD_Yf_TILED;
9260                 break;
9261         default:
9262                 MISSING_CASE(tiling);
9263                 goto error;
9264         }
9265
9266         base = I915_READ(PLANE_SURF(pipe, 0)) & 0xfffff000;
9267         plane_config->base = base;
9268
9269         offset = I915_READ(PLANE_OFFSET(pipe, 0));
9270
9271         val = I915_READ(PLANE_SIZE(pipe, 0));
9272         fb->height = ((val >> 16) & 0xfff) + 1;
9273         fb->width = ((val >> 0) & 0x1fff) + 1;
9274
9275         val = I915_READ(PLANE_STRIDE(pipe, 0));
9276         stride_mult = intel_fb_stride_alignment(dev_priv, fb->modifier[0],
9277                                                 fb->pixel_format);
9278         fb->pitches[0] = (val & 0x3ff) * stride_mult;
9279
9280         aligned_height = intel_fb_align_height(dev, fb->height,
9281                                                fb->pixel_format,
9282                                                fb->modifier[0]);
9283
9284         plane_config->size = fb->pitches[0] * aligned_height;
9285
9286         DRM_DEBUG_KMS("pipe %c with fb: size=%dx%d@%d, offset=%x, pitch %d, size 0x%x\n",
9287                       pipe_name(pipe), fb->width, fb->height,
9288                       fb->bits_per_pixel, base, fb->pitches[0],
9289                       plane_config->size);
9290
9291         plane_config->fb = intel_fb;
9292         return;
9293
9294 error:
9295         kfree(fb);
9296 }
9297
9298 static void ironlake_get_pfit_config(struct intel_crtc *crtc,
9299                                      struct intel_crtc_state *pipe_config)
9300 {
9301         struct drm_device *dev = crtc->base.dev;
9302         struct drm_i915_private *dev_priv = to_i915(dev);
9303         uint32_t tmp;
9304
9305         tmp = I915_READ(PF_CTL(crtc->pipe));
9306
9307         if (tmp & PF_ENABLE) {
9308                 pipe_config->pch_pfit.enabled = true;
9309                 pipe_config->pch_pfit.pos = I915_READ(PF_WIN_POS(crtc->pipe));
9310                 pipe_config->pch_pfit.size = I915_READ(PF_WIN_SZ(crtc->pipe));
9311
9312                 /* We currently do not free assignements of panel fitters on
9313                  * ivb/hsw (since we don't use the higher upscaling modes which
9314                  * differentiates them) so just WARN about this case for now. */
9315                 if (IS_GEN7(dev)) {
9316                         WARN_ON((tmp & PF_PIPE_SEL_MASK_IVB) !=
9317                                 PF_PIPE_SEL_IVB(crtc->pipe));
9318                 }
9319         }
9320 }
9321
9322 static void
9323 ironlake_get_initial_plane_config(struct intel_crtc *crtc,
9324                                   struct intel_initial_plane_config *plane_config)
9325 {
9326         struct drm_device *dev = crtc->base.dev;
9327         struct drm_i915_private *dev_priv = to_i915(dev);
9328         u32 val, base, offset;
9329         int pipe = crtc->pipe;
9330         int fourcc, pixel_format;
9331         unsigned int aligned_height;
9332         struct drm_framebuffer *fb;
9333         struct intel_framebuffer *intel_fb;
9334
9335         val = I915_READ(DSPCNTR(pipe));
9336         if (!(val & DISPLAY_PLANE_ENABLE))
9337                 return;
9338
9339         intel_fb = kzalloc(sizeof(*intel_fb), GFP_KERNEL);
9340         if (!intel_fb) {
9341                 DRM_DEBUG_KMS("failed to alloc fb\n");
9342                 return;
9343         }
9344
9345         fb = &intel_fb->base;
9346
9347         if (INTEL_INFO(dev)->gen >= 4) {
9348                 if (val & DISPPLANE_TILED) {
9349                         plane_config->tiling = I915_TILING_X;
9350                         fb->modifier[0] = I915_FORMAT_MOD_X_TILED;
9351                 }
9352         }
9353
9354         pixel_format = val & DISPPLANE_PIXFORMAT_MASK;
9355         fourcc = i9xx_format_to_fourcc(pixel_format);
9356         fb->pixel_format = fourcc;
9357         fb->bits_per_pixel = drm_format_plane_cpp(fourcc, 0) * 8;
9358
9359         base = I915_READ(DSPSURF(pipe)) & 0xfffff000;
9360         if (IS_HASWELL(dev) || IS_BROADWELL(dev)) {
9361                 offset = I915_READ(DSPOFFSET(pipe));
9362         } else {
9363                 if (plane_config->tiling)
9364                         offset = I915_READ(DSPTILEOFF(pipe));
9365                 else
9366                         offset = I915_READ(DSPLINOFF(pipe));
9367         }
9368         plane_config->base = base;
9369
9370         val = I915_READ(PIPESRC(pipe));
9371         fb->width = ((val >> 16) & 0xfff) + 1;
9372         fb->height = ((val >> 0) & 0xfff) + 1;
9373
9374         val = I915_READ(DSPSTRIDE(pipe));
9375         fb->pitches[0] = val & 0xffffffc0;
9376
9377         aligned_height = intel_fb_align_height(dev, fb->height,
9378                                                fb->pixel_format,
9379                                                fb->modifier[0]);
9380
9381         plane_config->size = fb->pitches[0] * aligned_height;
9382
9383         DRM_DEBUG_KMS("pipe %c with fb: size=%dx%d@%d, offset=%x, pitch %d, size 0x%x\n",
9384                       pipe_name(pipe), fb->width, fb->height,
9385                       fb->bits_per_pixel, base, fb->pitches[0],
9386                       plane_config->size);
9387
9388         plane_config->fb = intel_fb;
9389 }
9390
9391 static bool ironlake_get_pipe_config(struct intel_crtc *crtc,
9392                                      struct intel_crtc_state *pipe_config)
9393 {
9394         struct drm_device *dev = crtc->base.dev;
9395         struct drm_i915_private *dev_priv = to_i915(dev);
9396         enum intel_display_power_domain power_domain;
9397         uint32_t tmp;
9398         bool ret;
9399
9400         power_domain = POWER_DOMAIN_PIPE(crtc->pipe);
9401         if (!intel_display_power_get_if_enabled(dev_priv, power_domain))
9402                 return false;
9403
9404         pipe_config->cpu_transcoder = (enum transcoder) crtc->pipe;
9405         pipe_config->shared_dpll = NULL;
9406
9407         ret = false;
9408         tmp = I915_READ(PIPECONF(crtc->pipe));
9409         if (!(tmp & PIPECONF_ENABLE))
9410                 goto out;
9411
9412         switch (tmp & PIPECONF_BPC_MASK) {
9413         case PIPECONF_6BPC:
9414                 pipe_config->pipe_bpp = 18;
9415                 break;
9416         case PIPECONF_8BPC:
9417                 pipe_config->pipe_bpp = 24;
9418                 break;
9419         case PIPECONF_10BPC:
9420                 pipe_config->pipe_bpp = 30;
9421                 break;
9422         case PIPECONF_12BPC:
9423                 pipe_config->pipe_bpp = 36;
9424                 break;
9425         default:
9426                 break;
9427         }
9428
9429         if (tmp & PIPECONF_COLOR_RANGE_SELECT)
9430                 pipe_config->limited_color_range = true;
9431
9432         if (I915_READ(PCH_TRANSCONF(crtc->pipe)) & TRANS_ENABLE) {
9433                 struct intel_shared_dpll *pll;
9434                 enum intel_dpll_id pll_id;
9435
9436                 pipe_config->has_pch_encoder = true;
9437
9438                 tmp = I915_READ(FDI_RX_CTL(crtc->pipe));
9439                 pipe_config->fdi_lanes = ((FDI_DP_PORT_WIDTH_MASK & tmp) >>
9440                                           FDI_DP_PORT_WIDTH_SHIFT) + 1;
9441
9442                 ironlake_get_fdi_m_n_config(crtc, pipe_config);
9443
9444                 if (HAS_PCH_IBX(dev_priv)) {
9445                         /*
9446                          * The pipe->pch transcoder and pch transcoder->pll
9447                          * mapping is fixed.
9448                          */
9449                         pll_id = (enum intel_dpll_id) crtc->pipe;
9450                 } else {
9451                         tmp = I915_READ(PCH_DPLL_SEL);
9452                         if (tmp & TRANS_DPLLB_SEL(crtc->pipe))
9453                                 pll_id = DPLL_ID_PCH_PLL_B;
9454                         else
9455                                 pll_id= DPLL_ID_PCH_PLL_A;
9456                 }
9457
9458                 pipe_config->shared_dpll =
9459                         intel_get_shared_dpll_by_id(dev_priv, pll_id);
9460                 pll = pipe_config->shared_dpll;
9461
9462                 WARN_ON(!pll->funcs.get_hw_state(dev_priv, pll,
9463                                                  &pipe_config->dpll_hw_state));
9464
9465                 tmp = pipe_config->dpll_hw_state.dpll;
9466                 pipe_config->pixel_multiplier =
9467                         ((tmp & PLL_REF_SDVO_HDMI_MULTIPLIER_MASK)
9468                          >> PLL_REF_SDVO_HDMI_MULTIPLIER_SHIFT) + 1;
9469
9470                 ironlake_pch_clock_get(crtc, pipe_config);
9471         } else {
9472                 pipe_config->pixel_multiplier = 1;
9473         }
9474
9475         intel_get_pipe_timings(crtc, pipe_config);
9476         intel_get_pipe_src_size(crtc, pipe_config);
9477
9478         ironlake_get_pfit_config(crtc, pipe_config);
9479
9480         ret = true;
9481
9482 out:
9483         intel_display_power_put(dev_priv, power_domain);
9484
9485         return ret;
9486 }
9487
9488 static void assert_can_disable_lcpll(struct drm_i915_private *dev_priv)
9489 {
9490         struct drm_device *dev = &dev_priv->drm;
9491         struct intel_crtc *crtc;
9492
9493         for_each_intel_crtc(dev, crtc)
9494                 I915_STATE_WARN(crtc->active, "CRTC for pipe %c enabled\n",
9495                      pipe_name(crtc->pipe));
9496
9497         I915_STATE_WARN(I915_READ(HSW_PWR_WELL_DRIVER), "Power well on\n");
9498         I915_STATE_WARN(I915_READ(SPLL_CTL) & SPLL_PLL_ENABLE, "SPLL enabled\n");
9499         I915_STATE_WARN(I915_READ(WRPLL_CTL(0)) & WRPLL_PLL_ENABLE, "WRPLL1 enabled\n");
9500         I915_STATE_WARN(I915_READ(WRPLL_CTL(1)) & WRPLL_PLL_ENABLE, "WRPLL2 enabled\n");
9501         I915_STATE_WARN(I915_READ(PCH_PP_STATUS) & PP_ON, "Panel power on\n");
9502         I915_STATE_WARN(I915_READ(BLC_PWM_CPU_CTL2) & BLM_PWM_ENABLE,
9503              "CPU PWM1 enabled\n");
9504         if (IS_HASWELL(dev))
9505                 I915_STATE_WARN(I915_READ(HSW_BLC_PWM2_CTL) & BLM_PWM_ENABLE,
9506                      "CPU PWM2 enabled\n");
9507         I915_STATE_WARN(I915_READ(BLC_PWM_PCH_CTL1) & BLM_PCH_PWM_ENABLE,
9508              "PCH PWM1 enabled\n");
9509         I915_STATE_WARN(I915_READ(UTIL_PIN_CTL) & UTIL_PIN_ENABLE,
9510              "Utility pin enabled\n");
9511         I915_STATE_WARN(I915_READ(PCH_GTC_CTL) & PCH_GTC_ENABLE, "PCH GTC enabled\n");
9512
9513         /*
9514          * In theory we can still leave IRQs enabled, as long as only the HPD
9515          * interrupts remain enabled. We used to check for that, but since it's
9516          * gen-specific and since we only disable LCPLL after we fully disable
9517          * the interrupts, the check below should be enough.
9518          */
9519         I915_STATE_WARN(intel_irqs_enabled(dev_priv), "IRQs enabled\n");
9520 }
9521
9522 static uint32_t hsw_read_dcomp(struct drm_i915_private *dev_priv)
9523 {
9524         struct drm_device *dev = &dev_priv->drm;
9525
9526         if (IS_HASWELL(dev))
9527                 return I915_READ(D_COMP_HSW);
9528         else
9529                 return I915_READ(D_COMP_BDW);
9530 }
9531
9532 static void hsw_write_dcomp(struct drm_i915_private *dev_priv, uint32_t val)
9533 {
9534         struct drm_device *dev = &dev_priv->drm;
9535
9536         if (IS_HASWELL(dev)) {
9537                 mutex_lock(&dev_priv->rps.hw_lock);
9538                 if (sandybridge_pcode_write(dev_priv, GEN6_PCODE_WRITE_D_COMP,
9539                                             val))
9540                         DRM_ERROR("Failed to write to D_COMP\n");
9541                 mutex_unlock(&dev_priv->rps.hw_lock);
9542         } else {
9543                 I915_WRITE(D_COMP_BDW, val);
9544                 POSTING_READ(D_COMP_BDW);
9545         }
9546 }
9547
9548 /*
9549  * This function implements pieces of two sequences from BSpec:
9550  * - Sequence for display software to disable LCPLL
9551  * - Sequence for display software to allow package C8+
9552  * The steps implemented here are just the steps that actually touch the LCPLL
9553  * register. Callers should take care of disabling all the display engine
9554  * functions, doing the mode unset, fixing interrupts, etc.
9555  */
9556 static void hsw_disable_lcpll(struct drm_i915_private *dev_priv,
9557                               bool switch_to_fclk, bool allow_power_down)
9558 {
9559         uint32_t val;
9560
9561         assert_can_disable_lcpll(dev_priv);
9562
9563         val = I915_READ(LCPLL_CTL);
9564
9565         if (switch_to_fclk) {
9566                 val |= LCPLL_CD_SOURCE_FCLK;
9567                 I915_WRITE(LCPLL_CTL, val);
9568
9569                 if (wait_for_us(I915_READ(LCPLL_CTL) &
9570                                 LCPLL_CD_SOURCE_FCLK_DONE, 1))
9571                         DRM_ERROR("Switching to FCLK failed\n");
9572
9573                 val = I915_READ(LCPLL_CTL);
9574         }
9575
9576         val |= LCPLL_PLL_DISABLE;
9577         I915_WRITE(LCPLL_CTL, val);
9578         POSTING_READ(LCPLL_CTL);
9579
9580         if (intel_wait_for_register(dev_priv, LCPLL_CTL, LCPLL_PLL_LOCK, 0, 1))
9581                 DRM_ERROR("LCPLL still locked\n");
9582
9583         val = hsw_read_dcomp(dev_priv);
9584         val |= D_COMP_COMP_DISABLE;
9585         hsw_write_dcomp(dev_priv, val);
9586         ndelay(100);
9587
9588         if (wait_for((hsw_read_dcomp(dev_priv) & D_COMP_RCOMP_IN_PROGRESS) == 0,
9589                      1))
9590                 DRM_ERROR("D_COMP RCOMP still in progress\n");
9591
9592         if (allow_power_down) {
9593                 val = I915_READ(LCPLL_CTL);
9594                 val |= LCPLL_POWER_DOWN_ALLOW;
9595                 I915_WRITE(LCPLL_CTL, val);
9596                 POSTING_READ(LCPLL_CTL);
9597         }
9598 }
9599
9600 /*
9601  * Fully restores LCPLL, disallowing power down and switching back to LCPLL
9602  * source.
9603  */
9604 static void hsw_restore_lcpll(struct drm_i915_private *dev_priv)
9605 {
9606         uint32_t val;
9607
9608         val = I915_READ(LCPLL_CTL);
9609
9610         if ((val & (LCPLL_PLL_LOCK | LCPLL_PLL_DISABLE | LCPLL_CD_SOURCE_FCLK |
9611                     LCPLL_POWER_DOWN_ALLOW)) == LCPLL_PLL_LOCK)
9612                 return;
9613
9614         /*
9615          * Make sure we're not on PC8 state before disabling PC8, otherwise
9616          * we'll hang the machine. To prevent PC8 state, just enable force_wake.
9617          */
9618         intel_uncore_forcewake_get(dev_priv, FORCEWAKE_ALL);
9619
9620         if (val & LCPLL_POWER_DOWN_ALLOW) {
9621                 val &= ~LCPLL_POWER_DOWN_ALLOW;
9622                 I915_WRITE(LCPLL_CTL, val);
9623                 POSTING_READ(LCPLL_CTL);
9624         }
9625
9626         val = hsw_read_dcomp(dev_priv);
9627         val |= D_COMP_COMP_FORCE;
9628         val &= ~D_COMP_COMP_DISABLE;
9629         hsw_write_dcomp(dev_priv, val);
9630
9631         val = I915_READ(LCPLL_CTL);
9632         val &= ~LCPLL_PLL_DISABLE;
9633         I915_WRITE(LCPLL_CTL, val);
9634
9635         if (intel_wait_for_register(dev_priv,
9636                                     LCPLL_CTL, LCPLL_PLL_LOCK, LCPLL_PLL_LOCK,
9637                                     5))
9638                 DRM_ERROR("LCPLL not locked yet\n");
9639
9640         if (val & LCPLL_CD_SOURCE_FCLK) {
9641                 val = I915_READ(LCPLL_CTL);
9642                 val &= ~LCPLL_CD_SOURCE_FCLK;
9643                 I915_WRITE(LCPLL_CTL, val);
9644
9645                 if (wait_for_us((I915_READ(LCPLL_CTL) &
9646                                  LCPLL_CD_SOURCE_FCLK_DONE) == 0, 1))
9647                         DRM_ERROR("Switching back to LCPLL failed\n");
9648         }
9649
9650         intel_uncore_forcewake_put(dev_priv, FORCEWAKE_ALL);
9651         intel_update_cdclk(&dev_priv->drm);
9652 }
9653
9654 /*
9655  * Package states C8 and deeper are really deep PC states that can only be
9656  * reached when all the devices on the system allow it, so even if the graphics
9657  * device allows PC8+, it doesn't mean the system will actually get to these
9658  * states. Our driver only allows PC8+ when going into runtime PM.
9659  *
9660  * The requirements for PC8+ are that all the outputs are disabled, the power
9661  * well is disabled and most interrupts are disabled, and these are also
9662  * requirements for runtime PM. When these conditions are met, we manually do
9663  * the other conditions: disable the interrupts, clocks and switch LCPLL refclk
9664  * to Fclk. If we're in PC8+ and we get an non-hotplug interrupt, we can hard
9665  * hang the machine.
9666  *
9667  * When we really reach PC8 or deeper states (not just when we allow it) we lose
9668  * the state of some registers, so when we come back from PC8+ we need to
9669  * restore this state. We don't get into PC8+ if we're not in RC6, so we don't
9670  * need to take care of the registers kept by RC6. Notice that this happens even
9671  * if we don't put the device in PCI D3 state (which is what currently happens
9672  * because of the runtime PM support).
9673  *
9674  * For more, read "Display Sequences for Package C8" on the hardware
9675  * documentation.
9676  */
9677 void hsw_enable_pc8(struct drm_i915_private *dev_priv)
9678 {
9679         struct drm_device *dev = &dev_priv->drm;
9680         uint32_t val;
9681
9682         DRM_DEBUG_KMS("Enabling package C8+\n");
9683
9684         if (HAS_PCH_LPT_LP(dev)) {
9685                 val = I915_READ(SOUTH_DSPCLK_GATE_D);
9686                 val &= ~PCH_LP_PARTITION_LEVEL_DISABLE;
9687                 I915_WRITE(SOUTH_DSPCLK_GATE_D, val);
9688         }
9689
9690         lpt_disable_clkout_dp(dev);
9691         hsw_disable_lcpll(dev_priv, true, true);
9692 }
9693
9694 void hsw_disable_pc8(struct drm_i915_private *dev_priv)
9695 {
9696         struct drm_device *dev = &dev_priv->drm;
9697         uint32_t val;
9698
9699         DRM_DEBUG_KMS("Disabling package C8+\n");
9700
9701         hsw_restore_lcpll(dev_priv);
9702         lpt_init_pch_refclk(dev);
9703
9704         if (HAS_PCH_LPT_LP(dev)) {
9705                 val = I915_READ(SOUTH_DSPCLK_GATE_D);
9706                 val |= PCH_LP_PARTITION_LEVEL_DISABLE;
9707                 I915_WRITE(SOUTH_DSPCLK_GATE_D, val);
9708         }
9709 }
9710
9711 static void bxt_modeset_commit_cdclk(struct drm_atomic_state *old_state)
9712 {
9713         struct drm_device *dev = old_state->dev;
9714         struct intel_atomic_state *old_intel_state =
9715                 to_intel_atomic_state(old_state);
9716         unsigned int req_cdclk = old_intel_state->dev_cdclk;
9717
9718         bxt_set_cdclk(to_i915(dev), req_cdclk);
9719 }
9720
9721 /* compute the max rate for new configuration */
9722 static int ilk_max_pixel_rate(struct drm_atomic_state *state)
9723 {
9724         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
9725         struct drm_i915_private *dev_priv = to_i915(state->dev);
9726         struct drm_crtc *crtc;
9727         struct drm_crtc_state *cstate;
9728         struct intel_crtc_state *crtc_state;
9729         unsigned max_pixel_rate = 0, i;
9730         enum pipe pipe;
9731
9732         memcpy(intel_state->min_pixclk, dev_priv->min_pixclk,
9733                sizeof(intel_state->min_pixclk));
9734
9735         for_each_crtc_in_state(state, crtc, cstate, i) {
9736                 int pixel_rate;
9737
9738                 crtc_state = to_intel_crtc_state(cstate);
9739                 if (!crtc_state->base.enable) {
9740                         intel_state->min_pixclk[i] = 0;
9741                         continue;
9742                 }
9743
9744                 pixel_rate = ilk_pipe_pixel_rate(crtc_state);
9745
9746                 /* pixel rate mustn't exceed 95% of cdclk with IPS on BDW */
9747                 if (IS_BROADWELL(dev_priv) && crtc_state->ips_enabled)
9748                         pixel_rate = DIV_ROUND_UP(pixel_rate * 100, 95);
9749
9750                 intel_state->min_pixclk[i] = pixel_rate;
9751         }
9752
9753         for_each_pipe(dev_priv, pipe)
9754                 max_pixel_rate = max(intel_state->min_pixclk[pipe], max_pixel_rate);
9755
9756         return max_pixel_rate;
9757 }
9758
9759 static void broadwell_set_cdclk(struct drm_device *dev, int cdclk)
9760 {
9761         struct drm_i915_private *dev_priv = to_i915(dev);
9762         uint32_t val, data;
9763         int ret;
9764
9765         if (WARN((I915_READ(LCPLL_CTL) &
9766                   (LCPLL_PLL_DISABLE | LCPLL_PLL_LOCK |
9767                    LCPLL_CD_CLOCK_DISABLE | LCPLL_ROOT_CD_CLOCK_DISABLE |
9768                    LCPLL_CD2X_CLOCK_DISABLE | LCPLL_POWER_DOWN_ALLOW |
9769                    LCPLL_CD_SOURCE_FCLK)) != LCPLL_PLL_LOCK,
9770                  "trying to change cdclk frequency with cdclk not enabled\n"))
9771                 return;
9772
9773         mutex_lock(&dev_priv->rps.hw_lock);
9774         ret = sandybridge_pcode_write(dev_priv,
9775                                       BDW_PCODE_DISPLAY_FREQ_CHANGE_REQ, 0x0);
9776         mutex_unlock(&dev_priv->rps.hw_lock);
9777         if (ret) {
9778                 DRM_ERROR("failed to inform pcode about cdclk change\n");
9779                 return;
9780         }
9781
9782         val = I915_READ(LCPLL_CTL);
9783         val |= LCPLL_CD_SOURCE_FCLK;
9784         I915_WRITE(LCPLL_CTL, val);
9785
9786         if (wait_for_us(I915_READ(LCPLL_CTL) &
9787                         LCPLL_CD_SOURCE_FCLK_DONE, 1))
9788                 DRM_ERROR("Switching to FCLK failed\n");
9789
9790         val = I915_READ(LCPLL_CTL);
9791         val &= ~LCPLL_CLK_FREQ_MASK;
9792
9793         switch (cdclk) {
9794         case 450000:
9795                 val |= LCPLL_CLK_FREQ_450;
9796                 data = 0;
9797                 break;
9798         case 540000:
9799                 val |= LCPLL_CLK_FREQ_54O_BDW;
9800                 data = 1;
9801                 break;
9802         case 337500:
9803                 val |= LCPLL_CLK_FREQ_337_5_BDW;
9804                 data = 2;
9805                 break;
9806         case 675000:
9807                 val |= LCPLL_CLK_FREQ_675_BDW;
9808                 data = 3;
9809                 break;
9810         default:
9811                 WARN(1, "invalid cdclk frequency\n");
9812                 return;
9813         }
9814
9815         I915_WRITE(LCPLL_CTL, val);
9816
9817         val = I915_READ(LCPLL_CTL);
9818         val &= ~LCPLL_CD_SOURCE_FCLK;
9819         I915_WRITE(LCPLL_CTL, val);
9820
9821         if (wait_for_us((I915_READ(LCPLL_CTL) &
9822                         LCPLL_CD_SOURCE_FCLK_DONE) == 0, 1))
9823                 DRM_ERROR("Switching back to LCPLL failed\n");
9824
9825         mutex_lock(&dev_priv->rps.hw_lock);
9826         sandybridge_pcode_write(dev_priv, HSW_PCODE_DE_WRITE_FREQ_REQ, data);
9827         mutex_unlock(&dev_priv->rps.hw_lock);
9828
9829         I915_WRITE(CDCLK_FREQ, DIV_ROUND_CLOSEST(cdclk, 1000) - 1);
9830
9831         intel_update_cdclk(dev);
9832
9833         WARN(cdclk != dev_priv->cdclk_freq,
9834              "cdclk requested %d kHz but got %d kHz\n",
9835              cdclk, dev_priv->cdclk_freq);
9836 }
9837
9838 static int broadwell_calc_cdclk(int max_pixclk)
9839 {
9840         if (max_pixclk > 540000)
9841                 return 675000;
9842         else if (max_pixclk > 450000)
9843                 return 540000;
9844         else if (max_pixclk > 337500)
9845                 return 450000;
9846         else
9847                 return 337500;
9848 }
9849
9850 static int broadwell_modeset_calc_cdclk(struct drm_atomic_state *state)
9851 {
9852         struct drm_i915_private *dev_priv = to_i915(state->dev);
9853         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
9854         int max_pixclk = ilk_max_pixel_rate(state);
9855         int cdclk;
9856
9857         /*
9858          * FIXME should also account for plane ratio
9859          * once 64bpp pixel formats are supported.
9860          */
9861         cdclk = broadwell_calc_cdclk(max_pixclk);
9862
9863         if (cdclk > dev_priv->max_cdclk_freq) {
9864                 DRM_DEBUG_KMS("requested cdclk (%d kHz) exceeds max (%d kHz)\n",
9865                               cdclk, dev_priv->max_cdclk_freq);
9866                 return -EINVAL;
9867         }
9868
9869         intel_state->cdclk = intel_state->dev_cdclk = cdclk;
9870         if (!intel_state->active_crtcs)
9871                 intel_state->dev_cdclk = broadwell_calc_cdclk(0);
9872
9873         return 0;
9874 }
9875
9876 static void broadwell_modeset_commit_cdclk(struct drm_atomic_state *old_state)
9877 {
9878         struct drm_device *dev = old_state->dev;
9879         struct intel_atomic_state *old_intel_state =
9880                 to_intel_atomic_state(old_state);
9881         unsigned req_cdclk = old_intel_state->dev_cdclk;
9882
9883         broadwell_set_cdclk(dev, req_cdclk);
9884 }
9885
9886 static int skl_modeset_calc_cdclk(struct drm_atomic_state *state)
9887 {
9888         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
9889         struct drm_i915_private *dev_priv = to_i915(state->dev);
9890         const int max_pixclk = ilk_max_pixel_rate(state);
9891         int vco = intel_state->cdclk_pll_vco;
9892         int cdclk;
9893
9894         /*
9895          * FIXME should also account for plane ratio
9896          * once 64bpp pixel formats are supported.
9897          */
9898         cdclk = skl_calc_cdclk(max_pixclk, vco);
9899
9900         /*
9901          * FIXME move the cdclk caclulation to
9902          * compute_config() so we can fail gracegully.
9903          */
9904         if (cdclk > dev_priv->max_cdclk_freq) {
9905                 DRM_ERROR("requested cdclk (%d kHz) exceeds max (%d kHz)\n",
9906                           cdclk, dev_priv->max_cdclk_freq);
9907                 cdclk = dev_priv->max_cdclk_freq;
9908         }
9909
9910         intel_state->cdclk = intel_state->dev_cdclk = cdclk;
9911         if (!intel_state->active_crtcs)
9912                 intel_state->dev_cdclk = skl_calc_cdclk(0, vco);
9913
9914         return 0;
9915 }
9916
9917 static void skl_modeset_commit_cdclk(struct drm_atomic_state *old_state)
9918 {
9919         struct drm_i915_private *dev_priv = to_i915(old_state->dev);
9920         struct intel_atomic_state *intel_state = to_intel_atomic_state(old_state);
9921         unsigned int req_cdclk = intel_state->dev_cdclk;
9922         unsigned int req_vco = intel_state->cdclk_pll_vco;
9923
9924         skl_set_cdclk(dev_priv, req_cdclk, req_vco);
9925 }
9926
9927 static int haswell_crtc_compute_clock(struct intel_crtc *crtc,
9928                                       struct intel_crtc_state *crtc_state)
9929 {
9930         if (!intel_crtc_has_type(crtc_state, INTEL_OUTPUT_DSI)) {
9931                 if (!intel_ddi_pll_select(crtc, crtc_state))
9932                         return -EINVAL;
9933         }
9934
9935         crtc->lowfreq_avail = false;
9936
9937         return 0;
9938 }
9939
9940 static void bxt_get_ddi_pll(struct drm_i915_private *dev_priv,
9941                                 enum port port,
9942                                 struct intel_crtc_state *pipe_config)
9943 {
9944         enum intel_dpll_id id;
9945
9946         switch (port) {
9947         case PORT_A:
9948                 pipe_config->ddi_pll_sel = SKL_DPLL0;
9949                 id = DPLL_ID_SKL_DPLL0;
9950                 break;
9951         case PORT_B:
9952                 pipe_config->ddi_pll_sel = SKL_DPLL1;
9953                 id = DPLL_ID_SKL_DPLL1;
9954                 break;
9955         case PORT_C:
9956                 pipe_config->ddi_pll_sel = SKL_DPLL2;
9957                 id = DPLL_ID_SKL_DPLL2;
9958                 break;
9959         default:
9960                 DRM_ERROR("Incorrect port type\n");
9961                 return;
9962         }
9963
9964         pipe_config->shared_dpll = intel_get_shared_dpll_by_id(dev_priv, id);
9965 }
9966
9967 static void skylake_get_ddi_pll(struct drm_i915_private *dev_priv,
9968                                 enum port port,
9969                                 struct intel_crtc_state *pipe_config)
9970 {
9971         enum intel_dpll_id id;
9972         u32 temp;
9973
9974         temp = I915_READ(DPLL_CTRL2) & DPLL_CTRL2_DDI_CLK_SEL_MASK(port);
9975         pipe_config->ddi_pll_sel = temp >> (port * 3 + 1);
9976
9977         switch (pipe_config->ddi_pll_sel) {
9978         case SKL_DPLL0:
9979                 id = DPLL_ID_SKL_DPLL0;
9980                 break;
9981         case SKL_DPLL1:
9982                 id = DPLL_ID_SKL_DPLL1;
9983                 break;
9984         case SKL_DPLL2:
9985                 id = DPLL_ID_SKL_DPLL2;
9986                 break;
9987         case SKL_DPLL3:
9988                 id = DPLL_ID_SKL_DPLL3;
9989                 break;
9990         default:
9991                 MISSING_CASE(pipe_config->ddi_pll_sel);
9992                 return;
9993         }
9994
9995         pipe_config->shared_dpll = intel_get_shared_dpll_by_id(dev_priv, id);
9996 }
9997
9998 static void haswell_get_ddi_pll(struct drm_i915_private *dev_priv,
9999                                 enum port port,
10000                                 struct intel_crtc_state *pipe_config)
10001 {
10002         enum intel_dpll_id id;
10003
10004         pipe_config->ddi_pll_sel = I915_READ(PORT_CLK_SEL(port));
10005
10006         switch (pipe_config->ddi_pll_sel) {
10007         case PORT_CLK_SEL_WRPLL1:
10008                 id = DPLL_ID_WRPLL1;
10009                 break;
10010         case PORT_CLK_SEL_WRPLL2:
10011                 id = DPLL_ID_WRPLL2;
10012                 break;
10013         case PORT_CLK_SEL_SPLL:
10014                 id = DPLL_ID_SPLL;
10015                 break;
10016         case PORT_CLK_SEL_LCPLL_810:
10017                 id = DPLL_ID_LCPLL_810;
10018                 break;
10019         case PORT_CLK_SEL_LCPLL_1350:
10020                 id = DPLL_ID_LCPLL_1350;
10021                 break;
10022         case PORT_CLK_SEL_LCPLL_2700:
10023                 id = DPLL_ID_LCPLL_2700;
10024                 break;
10025         default:
10026                 MISSING_CASE(pipe_config->ddi_pll_sel);
10027                 /* fall through */
10028         case PORT_CLK_SEL_NONE:
10029                 return;
10030         }
10031
10032         pipe_config->shared_dpll = intel_get_shared_dpll_by_id(dev_priv, id);
10033 }
10034
10035 static bool hsw_get_transcoder_state(struct intel_crtc *crtc,
10036                                      struct intel_crtc_state *pipe_config,
10037                                      unsigned long *power_domain_mask)
10038 {
10039         struct drm_device *dev = crtc->base.dev;
10040         struct drm_i915_private *dev_priv = to_i915(dev);
10041         enum intel_display_power_domain power_domain;
10042         u32 tmp;
10043
10044         /*
10045          * The pipe->transcoder mapping is fixed with the exception of the eDP
10046          * transcoder handled below.
10047          */
10048         pipe_config->cpu_transcoder = (enum transcoder) crtc->pipe;
10049
10050         /*
10051          * XXX: Do intel_display_power_get_if_enabled before reading this (for
10052          * consistency and less surprising code; it's in always on power).
10053          */
10054         tmp = I915_READ(TRANS_DDI_FUNC_CTL(TRANSCODER_EDP));
10055         if (tmp & TRANS_DDI_FUNC_ENABLE) {
10056                 enum pipe trans_edp_pipe;
10057                 switch (tmp & TRANS_DDI_EDP_INPUT_MASK) {
10058                 default:
10059                         WARN(1, "unknown pipe linked to edp transcoder\n");
10060                 case TRANS_DDI_EDP_INPUT_A_ONOFF:
10061                 case TRANS_DDI_EDP_INPUT_A_ON:
10062                         trans_edp_pipe = PIPE_A;
10063                         break;
10064                 case TRANS_DDI_EDP_INPUT_B_ONOFF:
10065                         trans_edp_pipe = PIPE_B;
10066                         break;
10067                 case TRANS_DDI_EDP_INPUT_C_ONOFF:
10068                         trans_edp_pipe = PIPE_C;
10069                         break;
10070                 }
10071
10072                 if (trans_edp_pipe == crtc->pipe)
10073                         pipe_config->cpu_transcoder = TRANSCODER_EDP;
10074         }
10075
10076         power_domain = POWER_DOMAIN_TRANSCODER(pipe_config->cpu_transcoder);
10077         if (!intel_display_power_get_if_enabled(dev_priv, power_domain))
10078                 return false;
10079         *power_domain_mask |= BIT(power_domain);
10080
10081         tmp = I915_READ(PIPECONF(pipe_config->cpu_transcoder));
10082
10083         return tmp & PIPECONF_ENABLE;
10084 }
10085
10086 static bool bxt_get_dsi_transcoder_state(struct intel_crtc *crtc,
10087                                          struct intel_crtc_state *pipe_config,
10088                                          unsigned long *power_domain_mask)
10089 {
10090         struct drm_device *dev = crtc->base.dev;
10091         struct drm_i915_private *dev_priv = to_i915(dev);
10092         enum intel_display_power_domain power_domain;
10093         enum port port;
10094         enum transcoder cpu_transcoder;
10095         u32 tmp;
10096
10097         for_each_port_masked(port, BIT(PORT_A) | BIT(PORT_C)) {
10098                 if (port == PORT_A)
10099                         cpu_transcoder = TRANSCODER_DSI_A;
10100                 else
10101                         cpu_transcoder = TRANSCODER_DSI_C;
10102
10103                 power_domain = POWER_DOMAIN_TRANSCODER(cpu_transcoder);
10104                 if (!intel_display_power_get_if_enabled(dev_priv, power_domain))
10105                         continue;
10106                 *power_domain_mask |= BIT(power_domain);
10107
10108                 /*
10109                  * The PLL needs to be enabled with a valid divider
10110                  * configuration, otherwise accessing DSI registers will hang
10111                  * the machine. See BSpec North Display Engine
10112                  * registers/MIPI[BXT]. We can break out here early, since we
10113                  * need the same DSI PLL to be enabled for both DSI ports.
10114                  */
10115                 if (!intel_dsi_pll_is_enabled(dev_priv))
10116                         break;
10117
10118                 /* XXX: this works for video mode only */
10119                 tmp = I915_READ(BXT_MIPI_PORT_CTRL(port));
10120                 if (!(tmp & DPI_ENABLE))
10121                         continue;
10122
10123                 tmp = I915_READ(MIPI_CTRL(port));
10124                 if ((tmp & BXT_PIPE_SELECT_MASK) != BXT_PIPE_SELECT(crtc->pipe))
10125                         continue;
10126
10127                 pipe_config->cpu_transcoder = cpu_transcoder;
10128                 break;
10129         }
10130
10131         return transcoder_is_dsi(pipe_config->cpu_transcoder);
10132 }
10133
10134 static void haswell_get_ddi_port_state(struct intel_crtc *crtc,
10135                                        struct intel_crtc_state *pipe_config)
10136 {
10137         struct drm_device *dev = crtc->base.dev;
10138         struct drm_i915_private *dev_priv = to_i915(dev);
10139         struct intel_shared_dpll *pll;
10140         enum port port;
10141         uint32_t tmp;
10142
10143         tmp = I915_READ(TRANS_DDI_FUNC_CTL(pipe_config->cpu_transcoder));
10144
10145         port = (tmp & TRANS_DDI_PORT_MASK) >> TRANS_DDI_PORT_SHIFT;
10146
10147         if (IS_SKYLAKE(dev) || IS_KABYLAKE(dev))
10148                 skylake_get_ddi_pll(dev_priv, port, pipe_config);
10149         else if (IS_BROXTON(dev))
10150                 bxt_get_ddi_pll(dev_priv, port, pipe_config);
10151         else
10152                 haswell_get_ddi_pll(dev_priv, port, pipe_config);
10153
10154         pll = pipe_config->shared_dpll;
10155         if (pll) {
10156                 WARN_ON(!pll->funcs.get_hw_state(dev_priv, pll,
10157                                                  &pipe_config->dpll_hw_state));
10158         }
10159
10160         /*
10161          * Haswell has only FDI/PCH transcoder A. It is which is connected to
10162          * DDI E. So just check whether this pipe is wired to DDI E and whether
10163          * the PCH transcoder is on.
10164          */
10165         if (INTEL_INFO(dev)->gen < 9 &&
10166             (port == PORT_E) && I915_READ(LPT_TRANSCONF) & TRANS_ENABLE) {
10167                 pipe_config->has_pch_encoder = true;
10168
10169                 tmp = I915_READ(FDI_RX_CTL(PIPE_A));
10170                 pipe_config->fdi_lanes = ((FDI_DP_PORT_WIDTH_MASK & tmp) >>
10171                                           FDI_DP_PORT_WIDTH_SHIFT) + 1;
10172
10173                 ironlake_get_fdi_m_n_config(crtc, pipe_config);
10174         }
10175 }
10176
10177 static bool haswell_get_pipe_config(struct intel_crtc *crtc,
10178                                     struct intel_crtc_state *pipe_config)
10179 {
10180         struct drm_device *dev = crtc->base.dev;
10181         struct drm_i915_private *dev_priv = to_i915(dev);
10182         enum intel_display_power_domain power_domain;
10183         unsigned long power_domain_mask;
10184         bool active;
10185
10186         power_domain = POWER_DOMAIN_PIPE(crtc->pipe);
10187         if (!intel_display_power_get_if_enabled(dev_priv, power_domain))
10188                 return false;
10189         power_domain_mask = BIT(power_domain);
10190
10191         pipe_config->shared_dpll = NULL;
10192
10193         active = hsw_get_transcoder_state(crtc, pipe_config, &power_domain_mask);
10194
10195         if (IS_BROXTON(dev_priv) &&
10196             bxt_get_dsi_transcoder_state(crtc, pipe_config, &power_domain_mask)) {
10197                 WARN_ON(active);
10198                 active = true;
10199         }
10200
10201         if (!active)
10202                 goto out;
10203
10204         if (!transcoder_is_dsi(pipe_config->cpu_transcoder)) {
10205                 haswell_get_ddi_port_state(crtc, pipe_config);
10206                 intel_get_pipe_timings(crtc, pipe_config);
10207         }
10208
10209         intel_get_pipe_src_size(crtc, pipe_config);
10210
10211         pipe_config->gamma_mode =
10212                 I915_READ(GAMMA_MODE(crtc->pipe)) & GAMMA_MODE_MODE_MASK;
10213
10214         if (INTEL_INFO(dev)->gen >= 9) {
10215                 skl_init_scalers(dev, crtc, pipe_config);
10216         }
10217
10218         if (INTEL_INFO(dev)->gen >= 9) {
10219                 pipe_config->scaler_state.scaler_id = -1;
10220                 pipe_config->scaler_state.scaler_users &= ~(1 << SKL_CRTC_INDEX);
10221         }
10222
10223         power_domain = POWER_DOMAIN_PIPE_PANEL_FITTER(crtc->pipe);
10224         if (intel_display_power_get_if_enabled(dev_priv, power_domain)) {
10225                 power_domain_mask |= BIT(power_domain);
10226                 if (INTEL_INFO(dev)->gen >= 9)
10227                         skylake_get_pfit_config(crtc, pipe_config);
10228                 else
10229                         ironlake_get_pfit_config(crtc, pipe_config);
10230         }
10231
10232         if (IS_HASWELL(dev))
10233                 pipe_config->ips_enabled = hsw_crtc_supports_ips(crtc) &&
10234                         (I915_READ(IPS_CTL) & IPS_ENABLE);
10235
10236         if (pipe_config->cpu_transcoder != TRANSCODER_EDP &&
10237             !transcoder_is_dsi(pipe_config->cpu_transcoder)) {
10238                 pipe_config->pixel_multiplier =
10239                         I915_READ(PIPE_MULT(pipe_config->cpu_transcoder)) + 1;
10240         } else {
10241                 pipe_config->pixel_multiplier = 1;
10242         }
10243
10244 out:
10245         for_each_power_domain(power_domain, power_domain_mask)
10246                 intel_display_power_put(dev_priv, power_domain);
10247
10248         return active;
10249 }
10250
10251 static void i845_update_cursor(struct drm_crtc *crtc, u32 base,
10252                                const struct intel_plane_state *plane_state)
10253 {
10254         struct drm_device *dev = crtc->dev;
10255         struct drm_i915_private *dev_priv = to_i915(dev);
10256         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
10257         uint32_t cntl = 0, size = 0;
10258
10259         if (plane_state && plane_state->visible) {
10260                 unsigned int width = plane_state->base.crtc_w;
10261                 unsigned int height = plane_state->base.crtc_h;
10262                 unsigned int stride = roundup_pow_of_two(width) * 4;
10263
10264                 switch (stride) {
10265                 default:
10266                         WARN_ONCE(1, "Invalid cursor width/stride, width=%u, stride=%u\n",
10267                                   width, stride);
10268                         stride = 256;
10269                         /* fallthrough */
10270                 case 256:
10271                 case 512:
10272                 case 1024:
10273                 case 2048:
10274                         break;
10275                 }
10276
10277                 cntl |= CURSOR_ENABLE |
10278                         CURSOR_GAMMA_ENABLE |
10279                         CURSOR_FORMAT_ARGB |
10280                         CURSOR_STRIDE(stride);
10281
10282                 size = (height << 12) | width;
10283         }
10284
10285         if (intel_crtc->cursor_cntl != 0 &&
10286             (intel_crtc->cursor_base != base ||
10287              intel_crtc->cursor_size != size ||
10288              intel_crtc->cursor_cntl != cntl)) {
10289                 /* On these chipsets we can only modify the base/size/stride
10290                  * whilst the cursor is disabled.
10291                  */
10292                 I915_WRITE(CURCNTR(PIPE_A), 0);
10293                 POSTING_READ(CURCNTR(PIPE_A));
10294                 intel_crtc->cursor_cntl = 0;
10295         }
10296
10297         if (intel_crtc->cursor_base != base) {
10298                 I915_WRITE(CURBASE(PIPE_A), base);
10299                 intel_crtc->cursor_base = base;
10300         }
10301
10302         if (intel_crtc->cursor_size != size) {
10303                 I915_WRITE(CURSIZE, size);
10304                 intel_crtc->cursor_size = size;
10305         }
10306
10307         if (intel_crtc->cursor_cntl != cntl) {
10308                 I915_WRITE(CURCNTR(PIPE_A), cntl);
10309                 POSTING_READ(CURCNTR(PIPE_A));
10310                 intel_crtc->cursor_cntl = cntl;
10311         }
10312 }
10313
10314 static void i9xx_update_cursor(struct drm_crtc *crtc, u32 base,
10315                                const struct intel_plane_state *plane_state)
10316 {
10317         struct drm_device *dev = crtc->dev;
10318         struct drm_i915_private *dev_priv = to_i915(dev);
10319         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
10320         int pipe = intel_crtc->pipe;
10321         uint32_t cntl = 0;
10322
10323         if (plane_state && plane_state->visible) {
10324                 cntl = MCURSOR_GAMMA_ENABLE;
10325                 switch (plane_state->base.crtc_w) {
10326                         case 64:
10327                                 cntl |= CURSOR_MODE_64_ARGB_AX;
10328                                 break;
10329                         case 128:
10330                                 cntl |= CURSOR_MODE_128_ARGB_AX;
10331                                 break;
10332                         case 256:
10333                                 cntl |= CURSOR_MODE_256_ARGB_AX;
10334                                 break;
10335                         default:
10336                                 MISSING_CASE(plane_state->base.crtc_w);
10337                                 return;
10338                 }
10339                 cntl |= pipe << 28; /* Connect to correct pipe */
10340
10341                 if (HAS_DDI(dev))
10342                         cntl |= CURSOR_PIPE_CSC_ENABLE;
10343
10344                 if (plane_state->base.rotation == BIT(DRM_ROTATE_180))
10345                         cntl |= CURSOR_ROTATE_180;
10346         }
10347
10348         if (intel_crtc->cursor_cntl != cntl) {
10349                 I915_WRITE(CURCNTR(pipe), cntl);
10350                 POSTING_READ(CURCNTR(pipe));
10351                 intel_crtc->cursor_cntl = cntl;
10352         }
10353
10354         /* and commit changes on next vblank */
10355         I915_WRITE(CURBASE(pipe), base);
10356         POSTING_READ(CURBASE(pipe));
10357
10358         intel_crtc->cursor_base = base;
10359 }
10360
10361 /* If no-part of the cursor is visible on the framebuffer, then the GPU may hang... */
10362 static void intel_crtc_update_cursor(struct drm_crtc *crtc,
10363                                      const struct intel_plane_state *plane_state)
10364 {
10365         struct drm_device *dev = crtc->dev;
10366         struct drm_i915_private *dev_priv = to_i915(dev);
10367         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
10368         int pipe = intel_crtc->pipe;
10369         u32 base = intel_crtc->cursor_addr;
10370         u32 pos = 0;
10371
10372         if (plane_state) {
10373                 int x = plane_state->base.crtc_x;
10374                 int y = plane_state->base.crtc_y;
10375
10376                 if (x < 0) {
10377                         pos |= CURSOR_POS_SIGN << CURSOR_X_SHIFT;
10378                         x = -x;
10379                 }
10380                 pos |= x << CURSOR_X_SHIFT;
10381
10382                 if (y < 0) {
10383                         pos |= CURSOR_POS_SIGN << CURSOR_Y_SHIFT;
10384                         y = -y;
10385                 }
10386                 pos |= y << CURSOR_Y_SHIFT;
10387
10388                 /* ILK+ do this automagically */
10389                 if (HAS_GMCH_DISPLAY(dev) &&
10390                     plane_state->base.rotation == BIT(DRM_ROTATE_180)) {
10391                         base += (plane_state->base.crtc_h *
10392                                  plane_state->base.crtc_w - 1) * 4;
10393                 }
10394         }
10395
10396         I915_WRITE(CURPOS(pipe), pos);
10397
10398         if (IS_845G(dev) || IS_I865G(dev))
10399                 i845_update_cursor(crtc, base, plane_state);
10400         else
10401                 i9xx_update_cursor(crtc, base, plane_state);
10402 }
10403
10404 static bool cursor_size_ok(struct drm_device *dev,
10405                            uint32_t width, uint32_t height)
10406 {
10407         if (width == 0 || height == 0)
10408                 return false;
10409
10410         /*
10411          * 845g/865g are special in that they are only limited by
10412          * the width of their cursors, the height is arbitrary up to
10413          * the precision of the register. Everything else requires
10414          * square cursors, limited to a few power-of-two sizes.
10415          */
10416         if (IS_845G(dev) || IS_I865G(dev)) {
10417                 if ((width & 63) != 0)
10418                         return false;
10419
10420                 if (width > (IS_845G(dev) ? 64 : 512))
10421                         return false;
10422
10423                 if (height > 1023)
10424                         return false;
10425         } else {
10426                 switch (width | height) {
10427                 case 256:
10428                 case 128:
10429                         if (IS_GEN2(dev))
10430                                 return false;
10431                 case 64:
10432                         break;
10433                 default:
10434                         return false;
10435                 }
10436         }
10437
10438         return true;
10439 }
10440
10441 /* VESA 640x480x72Hz mode to set on the pipe */
10442 static struct drm_display_mode load_detect_mode = {
10443         DRM_MODE("640x480", DRM_MODE_TYPE_DEFAULT, 31500, 640, 664,
10444                  704, 832, 0, 480, 489, 491, 520, 0, DRM_MODE_FLAG_NHSYNC | DRM_MODE_FLAG_NVSYNC),
10445 };
10446
10447 struct drm_framebuffer *
10448 __intel_framebuffer_create(struct drm_device *dev,
10449                            struct drm_mode_fb_cmd2 *mode_cmd,
10450                            struct drm_i915_gem_object *obj)
10451 {
10452         struct intel_framebuffer *intel_fb;
10453         int ret;
10454
10455         intel_fb = kzalloc(sizeof(*intel_fb), GFP_KERNEL);
10456         if (!intel_fb)
10457                 return ERR_PTR(-ENOMEM);
10458
10459         ret = intel_framebuffer_init(dev, intel_fb, mode_cmd, obj);
10460         if (ret)
10461                 goto err;
10462
10463         return &intel_fb->base;
10464
10465 err:
10466         kfree(intel_fb);
10467         return ERR_PTR(ret);
10468 }
10469
10470 static struct drm_framebuffer *
10471 intel_framebuffer_create(struct drm_device *dev,
10472                          struct drm_mode_fb_cmd2 *mode_cmd,
10473                          struct drm_i915_gem_object *obj)
10474 {
10475         struct drm_framebuffer *fb;
10476         int ret;
10477
10478         ret = i915_mutex_lock_interruptible(dev);
10479         if (ret)
10480                 return ERR_PTR(ret);
10481         fb = __intel_framebuffer_create(dev, mode_cmd, obj);
10482         mutex_unlock(&dev->struct_mutex);
10483
10484         return fb;
10485 }
10486
10487 static u32
10488 intel_framebuffer_pitch_for_width(int width, int bpp)
10489 {
10490         u32 pitch = DIV_ROUND_UP(width * bpp, 8);
10491         return ALIGN(pitch, 64);
10492 }
10493
10494 static u32
10495 intel_framebuffer_size_for_mode(struct drm_display_mode *mode, int bpp)
10496 {
10497         u32 pitch = intel_framebuffer_pitch_for_width(mode->hdisplay, bpp);
10498         return PAGE_ALIGN(pitch * mode->vdisplay);
10499 }
10500
10501 static struct drm_framebuffer *
10502 intel_framebuffer_create_for_mode(struct drm_device *dev,
10503                                   struct drm_display_mode *mode,
10504                                   int depth, int bpp)
10505 {
10506         struct drm_framebuffer *fb;
10507         struct drm_i915_gem_object *obj;
10508         struct drm_mode_fb_cmd2 mode_cmd = { 0 };
10509
10510         obj = i915_gem_object_create(dev,
10511                                     intel_framebuffer_size_for_mode(mode, bpp));
10512         if (IS_ERR(obj))
10513                 return ERR_CAST(obj);
10514
10515         mode_cmd.width = mode->hdisplay;
10516         mode_cmd.height = mode->vdisplay;
10517         mode_cmd.pitches[0] = intel_framebuffer_pitch_for_width(mode_cmd.width,
10518                                                                 bpp);
10519         mode_cmd.pixel_format = drm_mode_legacy_fb_format(bpp, depth);
10520
10521         fb = intel_framebuffer_create(dev, &mode_cmd, obj);
10522         if (IS_ERR(fb))
10523                 i915_gem_object_put_unlocked(obj);
10524
10525         return fb;
10526 }
10527
10528 static struct drm_framebuffer *
10529 mode_fits_in_fbdev(struct drm_device *dev,
10530                    struct drm_display_mode *mode)
10531 {
10532 #ifdef CONFIG_DRM_FBDEV_EMULATION
10533         struct drm_i915_private *dev_priv = to_i915(dev);
10534         struct drm_i915_gem_object *obj;
10535         struct drm_framebuffer *fb;
10536
10537         if (!dev_priv->fbdev)
10538                 return NULL;
10539
10540         if (!dev_priv->fbdev->fb)
10541                 return NULL;
10542
10543         obj = dev_priv->fbdev->fb->obj;
10544         BUG_ON(!obj);
10545
10546         fb = &dev_priv->fbdev->fb->base;
10547         if (fb->pitches[0] < intel_framebuffer_pitch_for_width(mode->hdisplay,
10548                                                                fb->bits_per_pixel))
10549                 return NULL;
10550
10551         if (obj->base.size < mode->vdisplay * fb->pitches[0])
10552                 return NULL;
10553
10554         drm_framebuffer_reference(fb);
10555         return fb;
10556 #else
10557         return NULL;
10558 #endif
10559 }
10560
10561 static int intel_modeset_setup_plane_state(struct drm_atomic_state *state,
10562                                            struct drm_crtc *crtc,
10563                                            struct drm_display_mode *mode,
10564                                            struct drm_framebuffer *fb,
10565                                            int x, int y)
10566 {
10567         struct drm_plane_state *plane_state;
10568         int hdisplay, vdisplay;
10569         int ret;
10570
10571         plane_state = drm_atomic_get_plane_state(state, crtc->primary);
10572         if (IS_ERR(plane_state))
10573                 return PTR_ERR(plane_state);
10574
10575         if (mode)
10576                 drm_crtc_get_hv_timing(mode, &hdisplay, &vdisplay);
10577         else
10578                 hdisplay = vdisplay = 0;
10579
10580         ret = drm_atomic_set_crtc_for_plane(plane_state, fb ? crtc : NULL);
10581         if (ret)
10582                 return ret;
10583         drm_atomic_set_fb_for_plane(plane_state, fb);
10584         plane_state->crtc_x = 0;
10585         plane_state->crtc_y = 0;
10586         plane_state->crtc_w = hdisplay;
10587         plane_state->crtc_h = vdisplay;
10588         plane_state->src_x = x << 16;
10589         plane_state->src_y = y << 16;
10590         plane_state->src_w = hdisplay << 16;
10591         plane_state->src_h = vdisplay << 16;
10592
10593         return 0;
10594 }
10595
10596 bool intel_get_load_detect_pipe(struct drm_connector *connector,
10597                                 struct drm_display_mode *mode,
10598                                 struct intel_load_detect_pipe *old,
10599                                 struct drm_modeset_acquire_ctx *ctx)
10600 {
10601         struct intel_crtc *intel_crtc;
10602         struct intel_encoder *intel_encoder =
10603                 intel_attached_encoder(connector);
10604         struct drm_crtc *possible_crtc;
10605         struct drm_encoder *encoder = &intel_encoder->base;
10606         struct drm_crtc *crtc = NULL;
10607         struct drm_device *dev = encoder->dev;
10608         struct drm_framebuffer *fb;
10609         struct drm_mode_config *config = &dev->mode_config;
10610         struct drm_atomic_state *state = NULL, *restore_state = NULL;
10611         struct drm_connector_state *connector_state;
10612         struct intel_crtc_state *crtc_state;
10613         int ret, i = -1;
10614
10615         DRM_DEBUG_KMS("[CONNECTOR:%d:%s], [ENCODER:%d:%s]\n",
10616                       connector->base.id, connector->name,
10617                       encoder->base.id, encoder->name);
10618
10619         old->restore_state = NULL;
10620
10621 retry:
10622         ret = drm_modeset_lock(&config->connection_mutex, ctx);
10623         if (ret)
10624                 goto fail;
10625
10626         /*
10627          * Algorithm gets a little messy:
10628          *
10629          *   - if the connector already has an assigned crtc, use it (but make
10630          *     sure it's on first)
10631          *
10632          *   - try to find the first unused crtc that can drive this connector,
10633          *     and use that if we find one
10634          */
10635
10636         /* See if we already have a CRTC for this connector */
10637         if (connector->state->crtc) {
10638                 crtc = connector->state->crtc;
10639
10640                 ret = drm_modeset_lock(&crtc->mutex, ctx);
10641                 if (ret)
10642                         goto fail;
10643
10644                 /* Make sure the crtc and connector are running */
10645                 goto found;
10646         }
10647
10648         /* Find an unused one (if possible) */
10649         for_each_crtc(dev, possible_crtc) {
10650                 i++;
10651                 if (!(encoder->possible_crtcs & (1 << i)))
10652                         continue;
10653
10654                 ret = drm_modeset_lock(&possible_crtc->mutex, ctx);
10655                 if (ret)
10656                         goto fail;
10657
10658                 if (possible_crtc->state->enable) {
10659                         drm_modeset_unlock(&possible_crtc->mutex);
10660                         continue;
10661                 }
10662
10663                 crtc = possible_crtc;
10664                 break;
10665         }
10666
10667         /*
10668          * If we didn't find an unused CRTC, don't use any.
10669          */
10670         if (!crtc) {
10671                 DRM_DEBUG_KMS("no pipe available for load-detect\n");
10672                 goto fail;
10673         }
10674
10675 found:
10676         intel_crtc = to_intel_crtc(crtc);
10677
10678         ret = drm_modeset_lock(&crtc->primary->mutex, ctx);
10679         if (ret)
10680                 goto fail;
10681
10682         state = drm_atomic_state_alloc(dev);
10683         restore_state = drm_atomic_state_alloc(dev);
10684         if (!state || !restore_state) {
10685                 ret = -ENOMEM;
10686                 goto fail;
10687         }
10688
10689         state->acquire_ctx = ctx;
10690         restore_state->acquire_ctx = ctx;
10691
10692         connector_state = drm_atomic_get_connector_state(state, connector);
10693         if (IS_ERR(connector_state)) {
10694                 ret = PTR_ERR(connector_state);
10695                 goto fail;
10696         }
10697
10698         ret = drm_atomic_set_crtc_for_connector(connector_state, crtc);
10699         if (ret)
10700                 goto fail;
10701
10702         crtc_state = intel_atomic_get_crtc_state(state, intel_crtc);
10703         if (IS_ERR(crtc_state)) {
10704                 ret = PTR_ERR(crtc_state);
10705                 goto fail;
10706         }
10707
10708         crtc_state->base.active = crtc_state->base.enable = true;
10709
10710         if (!mode)
10711                 mode = &load_detect_mode;
10712
10713         /* We need a framebuffer large enough to accommodate all accesses
10714          * that the plane may generate whilst we perform load detection.
10715          * We can not rely on the fbcon either being present (we get called
10716          * during its initialisation to detect all boot displays, or it may
10717          * not even exist) or that it is large enough to satisfy the
10718          * requested mode.
10719          */
10720         fb = mode_fits_in_fbdev(dev, mode);
10721         if (fb == NULL) {
10722                 DRM_DEBUG_KMS("creating tmp fb for load-detection\n");
10723                 fb = intel_framebuffer_create_for_mode(dev, mode, 24, 32);
10724         } else
10725                 DRM_DEBUG_KMS("reusing fbdev for load-detection framebuffer\n");
10726         if (IS_ERR(fb)) {
10727                 DRM_DEBUG_KMS("failed to allocate framebuffer for load-detection\n");
10728                 goto fail;
10729         }
10730
10731         ret = intel_modeset_setup_plane_state(state, crtc, mode, fb, 0, 0);
10732         if (ret)
10733                 goto fail;
10734
10735         drm_framebuffer_unreference(fb);
10736
10737         ret = drm_atomic_set_mode_for_crtc(&crtc_state->base, mode);
10738         if (ret)
10739                 goto fail;
10740
10741         ret = PTR_ERR_OR_ZERO(drm_atomic_get_connector_state(restore_state, connector));
10742         if (!ret)
10743                 ret = PTR_ERR_OR_ZERO(drm_atomic_get_crtc_state(restore_state, crtc));
10744         if (!ret)
10745                 ret = PTR_ERR_OR_ZERO(drm_atomic_get_plane_state(restore_state, crtc->primary));
10746         if (ret) {
10747                 DRM_DEBUG_KMS("Failed to create a copy of old state to restore: %i\n", ret);
10748                 goto fail;
10749         }
10750
10751         ret = drm_atomic_commit(state);
10752         if (ret) {
10753                 DRM_DEBUG_KMS("failed to set mode on load-detect pipe\n");
10754                 goto fail;
10755         }
10756
10757         old->restore_state = restore_state;
10758
10759         /* let the connector get through one full cycle before testing */
10760         intel_wait_for_vblank(dev, intel_crtc->pipe);
10761         return true;
10762
10763 fail:
10764         drm_atomic_state_free(state);
10765         drm_atomic_state_free(restore_state);
10766         restore_state = state = NULL;
10767
10768         if (ret == -EDEADLK) {
10769                 drm_modeset_backoff(ctx);
10770                 goto retry;
10771         }
10772
10773         return false;
10774 }
10775
10776 void intel_release_load_detect_pipe(struct drm_connector *connector,
10777                                     struct intel_load_detect_pipe *old,
10778                                     struct drm_modeset_acquire_ctx *ctx)
10779 {
10780         struct intel_encoder *intel_encoder =
10781                 intel_attached_encoder(connector);
10782         struct drm_encoder *encoder = &intel_encoder->base;
10783         struct drm_atomic_state *state = old->restore_state;
10784         int ret;
10785
10786         DRM_DEBUG_KMS("[CONNECTOR:%d:%s], [ENCODER:%d:%s]\n",
10787                       connector->base.id, connector->name,
10788                       encoder->base.id, encoder->name);
10789
10790         if (!state)
10791                 return;
10792
10793         ret = drm_atomic_commit(state);
10794         if (ret) {
10795                 DRM_DEBUG_KMS("Couldn't release load detect pipe: %i\n", ret);
10796                 drm_atomic_state_free(state);
10797         }
10798 }
10799
10800 static int i9xx_pll_refclk(struct drm_device *dev,
10801                            const struct intel_crtc_state *pipe_config)
10802 {
10803         struct drm_i915_private *dev_priv = to_i915(dev);
10804         u32 dpll = pipe_config->dpll_hw_state.dpll;
10805
10806         if ((dpll & PLL_REF_INPUT_MASK) == PLLB_REF_INPUT_SPREADSPECTRUMIN)
10807                 return dev_priv->vbt.lvds_ssc_freq;
10808         else if (HAS_PCH_SPLIT(dev))
10809                 return 120000;
10810         else if (!IS_GEN2(dev))
10811                 return 96000;
10812         else
10813                 return 48000;
10814 }
10815
10816 /* Returns the clock of the currently programmed mode of the given pipe. */
10817 static void i9xx_crtc_clock_get(struct intel_crtc *crtc,
10818                                 struct intel_crtc_state *pipe_config)
10819 {
10820         struct drm_device *dev = crtc->base.dev;
10821         struct drm_i915_private *dev_priv = to_i915(dev);
10822         int pipe = pipe_config->cpu_transcoder;
10823         u32 dpll = pipe_config->dpll_hw_state.dpll;
10824         u32 fp;
10825         struct dpll clock;
10826         int port_clock;
10827         int refclk = i9xx_pll_refclk(dev, pipe_config);
10828
10829         if ((dpll & DISPLAY_RATE_SELECT_FPA1) == 0)
10830                 fp = pipe_config->dpll_hw_state.fp0;
10831         else
10832                 fp = pipe_config->dpll_hw_state.fp1;
10833
10834         clock.m1 = (fp & FP_M1_DIV_MASK) >> FP_M1_DIV_SHIFT;
10835         if (IS_PINEVIEW(dev)) {
10836                 clock.n = ffs((fp & FP_N_PINEVIEW_DIV_MASK) >> FP_N_DIV_SHIFT) - 1;
10837                 clock.m2 = (fp & FP_M2_PINEVIEW_DIV_MASK) >> FP_M2_DIV_SHIFT;
10838         } else {
10839                 clock.n = (fp & FP_N_DIV_MASK) >> FP_N_DIV_SHIFT;
10840                 clock.m2 = (fp & FP_M2_DIV_MASK) >> FP_M2_DIV_SHIFT;
10841         }
10842
10843         if (!IS_GEN2(dev)) {
10844                 if (IS_PINEVIEW(dev))
10845                         clock.p1 = ffs((dpll & DPLL_FPA01_P1_POST_DIV_MASK_PINEVIEW) >>
10846                                 DPLL_FPA01_P1_POST_DIV_SHIFT_PINEVIEW);
10847                 else
10848                         clock.p1 = ffs((dpll & DPLL_FPA01_P1_POST_DIV_MASK) >>
10849                                DPLL_FPA01_P1_POST_DIV_SHIFT);
10850
10851                 switch (dpll & DPLL_MODE_MASK) {
10852                 case DPLLB_MODE_DAC_SERIAL:
10853                         clock.p2 = dpll & DPLL_DAC_SERIAL_P2_CLOCK_DIV_5 ?
10854                                 5 : 10;
10855                         break;
10856                 case DPLLB_MODE_LVDS:
10857                         clock.p2 = dpll & DPLLB_LVDS_P2_CLOCK_DIV_7 ?
10858                                 7 : 14;
10859                         break;
10860                 default:
10861                         DRM_DEBUG_KMS("Unknown DPLL mode %08x in programmed "
10862                                   "mode\n", (int)(dpll & DPLL_MODE_MASK));
10863                         return;
10864                 }
10865
10866                 if (IS_PINEVIEW(dev))
10867                         port_clock = pnv_calc_dpll_params(refclk, &clock);
10868                 else
10869                         port_clock = i9xx_calc_dpll_params(refclk, &clock);
10870         } else {
10871                 u32 lvds = IS_I830(dev) ? 0 : I915_READ(LVDS);
10872                 bool is_lvds = (pipe == 1) && (lvds & LVDS_PORT_EN);
10873
10874                 if (is_lvds) {
10875                         clock.p1 = ffs((dpll & DPLL_FPA01_P1_POST_DIV_MASK_I830_LVDS) >>
10876                                        DPLL_FPA01_P1_POST_DIV_SHIFT);
10877
10878                         if (lvds & LVDS_CLKB_POWER_UP)
10879                                 clock.p2 = 7;
10880                         else
10881                                 clock.p2 = 14;
10882                 } else {
10883                         if (dpll & PLL_P1_DIVIDE_BY_TWO)
10884                                 clock.p1 = 2;
10885                         else {
10886                                 clock.p1 = ((dpll & DPLL_FPA01_P1_POST_DIV_MASK_I830) >>
10887                                             DPLL_FPA01_P1_POST_DIV_SHIFT) + 2;
10888                         }
10889                         if (dpll & PLL_P2_DIVIDE_BY_4)
10890                                 clock.p2 = 4;
10891                         else
10892                                 clock.p2 = 2;
10893                 }
10894
10895                 port_clock = i9xx_calc_dpll_params(refclk, &clock);
10896         }
10897
10898         /*
10899          * This value includes pixel_multiplier. We will use
10900          * port_clock to compute adjusted_mode.crtc_clock in the
10901          * encoder's get_config() function.
10902          */
10903         pipe_config->port_clock = port_clock;
10904 }
10905
10906 int intel_dotclock_calculate(int link_freq,
10907                              const struct intel_link_m_n *m_n)
10908 {
10909         /*
10910          * The calculation for the data clock is:
10911          * pixel_clock = ((m/n)*(link_clock * nr_lanes))/bpp
10912          * But we want to avoid losing precison if possible, so:
10913          * pixel_clock = ((m * link_clock * nr_lanes)/(n*bpp))
10914          *
10915          * and the link clock is simpler:
10916          * link_clock = (m * link_clock) / n
10917          */
10918
10919         if (!m_n->link_n)
10920                 return 0;
10921
10922         return div_u64((u64)m_n->link_m * link_freq, m_n->link_n);
10923 }
10924
10925 static void ironlake_pch_clock_get(struct intel_crtc *crtc,
10926                                    struct intel_crtc_state *pipe_config)
10927 {
10928         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
10929
10930         /* read out port_clock from the DPLL */
10931         i9xx_crtc_clock_get(crtc, pipe_config);
10932
10933         /*
10934          * In case there is an active pipe without active ports,
10935          * we may need some idea for the dotclock anyway.
10936          * Calculate one based on the FDI configuration.
10937          */
10938         pipe_config->base.adjusted_mode.crtc_clock =
10939                 intel_dotclock_calculate(intel_fdi_link_freq(dev_priv, pipe_config),
10940                                          &pipe_config->fdi_m_n);
10941 }
10942
10943 /** Returns the currently programmed mode of the given pipe. */
10944 struct drm_display_mode *intel_crtc_mode_get(struct drm_device *dev,
10945                                              struct drm_crtc *crtc)
10946 {
10947         struct drm_i915_private *dev_priv = to_i915(dev);
10948         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
10949         enum transcoder cpu_transcoder = intel_crtc->config->cpu_transcoder;
10950         struct drm_display_mode *mode;
10951         struct intel_crtc_state *pipe_config;
10952         int htot = I915_READ(HTOTAL(cpu_transcoder));
10953         int hsync = I915_READ(HSYNC(cpu_transcoder));
10954         int vtot = I915_READ(VTOTAL(cpu_transcoder));
10955         int vsync = I915_READ(VSYNC(cpu_transcoder));
10956         enum pipe pipe = intel_crtc->pipe;
10957
10958         mode = kzalloc(sizeof(*mode), GFP_KERNEL);
10959         if (!mode)
10960                 return NULL;
10961
10962         pipe_config = kzalloc(sizeof(*pipe_config), GFP_KERNEL);
10963         if (!pipe_config) {
10964                 kfree(mode);
10965                 return NULL;
10966         }
10967
10968         /*
10969          * Construct a pipe_config sufficient for getting the clock info
10970          * back out of crtc_clock_get.
10971          *
10972          * Note, if LVDS ever uses a non-1 pixel multiplier, we'll need
10973          * to use a real value here instead.
10974          */
10975         pipe_config->cpu_transcoder = (enum transcoder) pipe;
10976         pipe_config->pixel_multiplier = 1;
10977         pipe_config->dpll_hw_state.dpll = I915_READ(DPLL(pipe));
10978         pipe_config->dpll_hw_state.fp0 = I915_READ(FP0(pipe));
10979         pipe_config->dpll_hw_state.fp1 = I915_READ(FP1(pipe));
10980         i9xx_crtc_clock_get(intel_crtc, pipe_config);
10981
10982         mode->clock = pipe_config->port_clock / pipe_config->pixel_multiplier;
10983         mode->hdisplay = (htot & 0xffff) + 1;
10984         mode->htotal = ((htot & 0xffff0000) >> 16) + 1;
10985         mode->hsync_start = (hsync & 0xffff) + 1;
10986         mode->hsync_end = ((hsync & 0xffff0000) >> 16) + 1;
10987         mode->vdisplay = (vtot & 0xffff) + 1;
10988         mode->vtotal = ((vtot & 0xffff0000) >> 16) + 1;
10989         mode->vsync_start = (vsync & 0xffff) + 1;
10990         mode->vsync_end = ((vsync & 0xffff0000) >> 16) + 1;
10991
10992         drm_mode_set_name(mode);
10993
10994         kfree(pipe_config);
10995
10996         return mode;
10997 }
10998
10999 static void intel_crtc_destroy(struct drm_crtc *crtc)
11000 {
11001         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
11002         struct drm_device *dev = crtc->dev;
11003         struct intel_flip_work *work;
11004
11005         spin_lock_irq(&dev->event_lock);
11006         work = intel_crtc->flip_work;
11007         intel_crtc->flip_work = NULL;
11008         spin_unlock_irq(&dev->event_lock);
11009
11010         if (work) {
11011                 cancel_work_sync(&work->mmio_work);
11012                 cancel_work_sync(&work->unpin_work);
11013                 kfree(work);
11014         }
11015
11016         drm_crtc_cleanup(crtc);
11017
11018         kfree(intel_crtc);
11019 }
11020
11021 static void intel_unpin_work_fn(struct work_struct *__work)
11022 {
11023         struct intel_flip_work *work =
11024                 container_of(__work, struct intel_flip_work, unpin_work);
11025         struct intel_crtc *crtc = to_intel_crtc(work->crtc);
11026         struct drm_device *dev = crtc->base.dev;
11027         struct drm_plane *primary = crtc->base.primary;
11028
11029         if (is_mmio_work(work))
11030                 flush_work(&work->mmio_work);
11031
11032         mutex_lock(&dev->struct_mutex);
11033         intel_unpin_fb_obj(work->old_fb, primary->state->rotation);
11034         i915_gem_object_put(work->pending_flip_obj);
11035         mutex_unlock(&dev->struct_mutex);
11036
11037         i915_gem_request_put(work->flip_queued_req);
11038
11039         intel_frontbuffer_flip_complete(to_i915(dev),
11040                                         to_intel_plane(primary)->frontbuffer_bit);
11041         intel_fbc_post_update(crtc);
11042         drm_framebuffer_unreference(work->old_fb);
11043
11044         BUG_ON(atomic_read(&crtc->unpin_work_count) == 0);
11045         atomic_dec(&crtc->unpin_work_count);
11046
11047         kfree(work);
11048 }
11049
11050 /* Is 'a' after or equal to 'b'? */
11051 static bool g4x_flip_count_after_eq(u32 a, u32 b)
11052 {
11053         return !((a - b) & 0x80000000);
11054 }
11055
11056 static bool __pageflip_finished_cs(struct intel_crtc *crtc,
11057                                    struct intel_flip_work *work)
11058 {
11059         struct drm_device *dev = crtc->base.dev;
11060         struct drm_i915_private *dev_priv = to_i915(dev);
11061         unsigned reset_counter;
11062
11063         reset_counter = i915_reset_counter(&dev_priv->gpu_error);
11064         if (crtc->reset_counter != reset_counter)
11065                 return true;
11066
11067         /*
11068          * The relevant registers doen't exist on pre-ctg.
11069          * As the flip done interrupt doesn't trigger for mmio
11070          * flips on gmch platforms, a flip count check isn't
11071          * really needed there. But since ctg has the registers,
11072          * include it in the check anyway.
11073          */
11074         if (INTEL_INFO(dev)->gen < 5 && !IS_G4X(dev))
11075                 return true;
11076
11077         /*
11078          * BDW signals flip done immediately if the plane
11079          * is disabled, even if the plane enable is already
11080          * armed to occur at the next vblank :(
11081          */
11082
11083         /*
11084          * A DSPSURFLIVE check isn't enough in case the mmio and CS flips
11085          * used the same base address. In that case the mmio flip might
11086          * have completed, but the CS hasn't even executed the flip yet.
11087          *
11088          * A flip count check isn't enough as the CS might have updated
11089          * the base address just after start of vblank, but before we
11090          * managed to process the interrupt. This means we'd complete the
11091          * CS flip too soon.
11092          *
11093          * Combining both checks should get us a good enough result. It may
11094          * still happen that the CS flip has been executed, but has not
11095          * yet actually completed. But in case the base address is the same
11096          * anyway, we don't really care.
11097          */
11098         return (I915_READ(DSPSURFLIVE(crtc->plane)) & ~0xfff) ==
11099                 crtc->flip_work->gtt_offset &&
11100                 g4x_flip_count_after_eq(I915_READ(PIPE_FLIPCOUNT_G4X(crtc->pipe)),
11101                                     crtc->flip_work->flip_count);
11102 }
11103
11104 static bool
11105 __pageflip_finished_mmio(struct intel_crtc *crtc,
11106                                struct intel_flip_work *work)
11107 {
11108         /*
11109          * MMIO work completes when vblank is different from
11110          * flip_queued_vblank.
11111          *
11112          * Reset counter value doesn't matter, this is handled by
11113          * i915_wait_request finishing early, so no need to handle
11114          * reset here.
11115          */
11116         return intel_crtc_get_vblank_counter(crtc) != work->flip_queued_vblank;
11117 }
11118
11119
11120 static bool pageflip_finished(struct intel_crtc *crtc,
11121                               struct intel_flip_work *work)
11122 {
11123         if (!atomic_read(&work->pending))
11124                 return false;
11125
11126         smp_rmb();
11127
11128         if (is_mmio_work(work))
11129                 return __pageflip_finished_mmio(crtc, work);
11130         else
11131                 return __pageflip_finished_cs(crtc, work);
11132 }
11133
11134 void intel_finish_page_flip_cs(struct drm_i915_private *dev_priv, int pipe)
11135 {
11136         struct drm_device *dev = &dev_priv->drm;
11137         struct drm_crtc *crtc = dev_priv->pipe_to_crtc_mapping[pipe];
11138         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
11139         struct intel_flip_work *work;
11140         unsigned long flags;
11141
11142         /* Ignore early vblank irqs */
11143         if (!crtc)
11144                 return;
11145
11146         /*
11147          * This is called both by irq handlers and the reset code (to complete
11148          * lost pageflips) so needs the full irqsave spinlocks.
11149          */
11150         spin_lock_irqsave(&dev->event_lock, flags);
11151         work = intel_crtc->flip_work;
11152
11153         if (work != NULL &&
11154             !is_mmio_work(work) &&
11155             pageflip_finished(intel_crtc, work))
11156                 page_flip_completed(intel_crtc);
11157
11158         spin_unlock_irqrestore(&dev->event_lock, flags);
11159 }
11160
11161 void intel_finish_page_flip_mmio(struct drm_i915_private *dev_priv, int pipe)
11162 {
11163         struct drm_device *dev = &dev_priv->drm;
11164         struct drm_crtc *crtc = dev_priv->pipe_to_crtc_mapping[pipe];
11165         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
11166         struct intel_flip_work *work;
11167         unsigned long flags;
11168
11169         /* Ignore early vblank irqs */
11170         if (!crtc)
11171                 return;
11172
11173         /*
11174          * This is called both by irq handlers and the reset code (to complete
11175          * lost pageflips) so needs the full irqsave spinlocks.
11176          */
11177         spin_lock_irqsave(&dev->event_lock, flags);
11178         work = intel_crtc->flip_work;
11179
11180         if (work != NULL &&
11181             is_mmio_work(work) &&
11182             pageflip_finished(intel_crtc, work))
11183                 page_flip_completed(intel_crtc);
11184
11185         spin_unlock_irqrestore(&dev->event_lock, flags);
11186 }
11187
11188 static inline void intel_mark_page_flip_active(struct intel_crtc *crtc,
11189                                                struct intel_flip_work *work)
11190 {
11191         work->flip_queued_vblank = intel_crtc_get_vblank_counter(crtc);
11192
11193         /* Ensure that the work item is consistent when activating it ... */
11194         smp_mb__before_atomic();
11195         atomic_set(&work->pending, 1);
11196 }
11197
11198 static int intel_gen2_queue_flip(struct drm_device *dev,
11199                                  struct drm_crtc *crtc,
11200                                  struct drm_framebuffer *fb,
11201                                  struct drm_i915_gem_object *obj,
11202                                  struct drm_i915_gem_request *req,
11203                                  uint32_t flags)
11204 {
11205         struct intel_ring *ring = req->ring;
11206         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
11207         u32 flip_mask;
11208         int ret;
11209
11210         ret = intel_ring_begin(req, 6);
11211         if (ret)
11212                 return ret;
11213
11214         /* Can't queue multiple flips, so wait for the previous
11215          * one to finish before executing the next.
11216          */
11217         if (intel_crtc->plane)
11218                 flip_mask = MI_WAIT_FOR_PLANE_B_FLIP;
11219         else
11220                 flip_mask = MI_WAIT_FOR_PLANE_A_FLIP;
11221         intel_ring_emit(ring, MI_WAIT_FOR_EVENT | flip_mask);
11222         intel_ring_emit(ring, MI_NOOP);
11223         intel_ring_emit(ring, MI_DISPLAY_FLIP |
11224                         MI_DISPLAY_FLIP_PLANE(intel_crtc->plane));
11225         intel_ring_emit(ring, fb->pitches[0]);
11226         intel_ring_emit(ring, intel_crtc->flip_work->gtt_offset);
11227         intel_ring_emit(ring, 0); /* aux display base address, unused */
11228
11229         return 0;
11230 }
11231
11232 static int intel_gen3_queue_flip(struct drm_device *dev,
11233                                  struct drm_crtc *crtc,
11234                                  struct drm_framebuffer *fb,
11235                                  struct drm_i915_gem_object *obj,
11236                                  struct drm_i915_gem_request *req,
11237                                  uint32_t flags)
11238 {
11239         struct intel_ring *ring = req->ring;
11240         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
11241         u32 flip_mask;
11242         int ret;
11243
11244         ret = intel_ring_begin(req, 6);
11245         if (ret)
11246                 return ret;
11247
11248         if (intel_crtc->plane)
11249                 flip_mask = MI_WAIT_FOR_PLANE_B_FLIP;
11250         else
11251                 flip_mask = MI_WAIT_FOR_PLANE_A_FLIP;
11252         intel_ring_emit(ring, MI_WAIT_FOR_EVENT | flip_mask);
11253         intel_ring_emit(ring, MI_NOOP);
11254         intel_ring_emit(ring, MI_DISPLAY_FLIP_I915 |
11255                         MI_DISPLAY_FLIP_PLANE(intel_crtc->plane));
11256         intel_ring_emit(ring, fb->pitches[0]);
11257         intel_ring_emit(ring, intel_crtc->flip_work->gtt_offset);
11258         intel_ring_emit(ring, MI_NOOP);
11259
11260         return 0;
11261 }
11262
11263 static int intel_gen4_queue_flip(struct drm_device *dev,
11264                                  struct drm_crtc *crtc,
11265                                  struct drm_framebuffer *fb,
11266                                  struct drm_i915_gem_object *obj,
11267                                  struct drm_i915_gem_request *req,
11268                                  uint32_t flags)
11269 {
11270         struct intel_ring *ring = req->ring;
11271         struct drm_i915_private *dev_priv = to_i915(dev);
11272         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
11273         uint32_t pf, pipesrc;
11274         int ret;
11275
11276         ret = intel_ring_begin(req, 4);
11277         if (ret)
11278                 return ret;
11279
11280         /* i965+ uses the linear or tiled offsets from the
11281          * Display Registers (which do not change across a page-flip)
11282          * so we need only reprogram the base address.
11283          */
11284         intel_ring_emit(ring, MI_DISPLAY_FLIP |
11285                         MI_DISPLAY_FLIP_PLANE(intel_crtc->plane));
11286         intel_ring_emit(ring, fb->pitches[0]);
11287         intel_ring_emit(ring, intel_crtc->flip_work->gtt_offset |
11288                         i915_gem_object_get_tiling(obj));
11289
11290         /* XXX Enabling the panel-fitter across page-flip is so far
11291          * untested on non-native modes, so ignore it for now.
11292          * pf = I915_READ(pipe == 0 ? PFA_CTL_1 : PFB_CTL_1) & PF_ENABLE;
11293          */
11294         pf = 0;
11295         pipesrc = I915_READ(PIPESRC(intel_crtc->pipe)) & 0x0fff0fff;
11296         intel_ring_emit(ring, pf | pipesrc);
11297
11298         return 0;
11299 }
11300
11301 static int intel_gen6_queue_flip(struct drm_device *dev,
11302                                  struct drm_crtc *crtc,
11303                                  struct drm_framebuffer *fb,
11304                                  struct drm_i915_gem_object *obj,
11305                                  struct drm_i915_gem_request *req,
11306                                  uint32_t flags)
11307 {
11308         struct intel_ring *ring = req->ring;
11309         struct drm_i915_private *dev_priv = to_i915(dev);
11310         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
11311         uint32_t pf, pipesrc;
11312         int ret;
11313
11314         ret = intel_ring_begin(req, 4);
11315         if (ret)
11316                 return ret;
11317
11318         intel_ring_emit(ring, MI_DISPLAY_FLIP |
11319                         MI_DISPLAY_FLIP_PLANE(intel_crtc->plane));
11320         intel_ring_emit(ring, fb->pitches[0] | i915_gem_object_get_tiling(obj));
11321         intel_ring_emit(ring, intel_crtc->flip_work->gtt_offset);
11322
11323         /* Contrary to the suggestions in the documentation,
11324          * "Enable Panel Fitter" does not seem to be required when page
11325          * flipping with a non-native mode, and worse causes a normal
11326          * modeset to fail.
11327          * pf = I915_READ(PF_CTL(intel_crtc->pipe)) & PF_ENABLE;
11328          */
11329         pf = 0;
11330         pipesrc = I915_READ(PIPESRC(intel_crtc->pipe)) & 0x0fff0fff;
11331         intel_ring_emit(ring, pf | pipesrc);
11332
11333         return 0;
11334 }
11335
11336 static int intel_gen7_queue_flip(struct drm_device *dev,
11337                                  struct drm_crtc *crtc,
11338                                  struct drm_framebuffer *fb,
11339                                  struct drm_i915_gem_object *obj,
11340                                  struct drm_i915_gem_request *req,
11341                                  uint32_t flags)
11342 {
11343         struct intel_ring *ring = req->ring;
11344         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
11345         uint32_t plane_bit = 0;
11346         int len, ret;
11347
11348         switch (intel_crtc->plane) {
11349         case PLANE_A:
11350                 plane_bit = MI_DISPLAY_FLIP_IVB_PLANE_A;
11351                 break;
11352         case PLANE_B:
11353                 plane_bit = MI_DISPLAY_FLIP_IVB_PLANE_B;
11354                 break;
11355         case PLANE_C:
11356                 plane_bit = MI_DISPLAY_FLIP_IVB_PLANE_C;
11357                 break;
11358         default:
11359                 WARN_ONCE(1, "unknown plane in flip command\n");
11360                 return -ENODEV;
11361         }
11362
11363         len = 4;
11364         if (req->engine->id == RCS) {
11365                 len += 6;
11366                 /*
11367                  * On Gen 8, SRM is now taking an extra dword to accommodate
11368                  * 48bits addresses, and we need a NOOP for the batch size to
11369                  * stay even.
11370                  */
11371                 if (IS_GEN8(dev))
11372                         len += 2;
11373         }
11374
11375         /*
11376          * BSpec MI_DISPLAY_FLIP for IVB:
11377          * "The full packet must be contained within the same cache line."
11378          *
11379          * Currently the LRI+SRM+MI_DISPLAY_FLIP all fit within the same
11380          * cacheline, if we ever start emitting more commands before
11381          * the MI_DISPLAY_FLIP we may need to first emit everything else,
11382          * then do the cacheline alignment, and finally emit the
11383          * MI_DISPLAY_FLIP.
11384          */
11385         ret = intel_ring_cacheline_align(req);
11386         if (ret)
11387                 return ret;
11388
11389         ret = intel_ring_begin(req, len);
11390         if (ret)
11391                 return ret;
11392
11393         /* Unmask the flip-done completion message. Note that the bspec says that
11394          * we should do this for both the BCS and RCS, and that we must not unmask
11395          * more than one flip event at any time (or ensure that one flip message
11396          * can be sent by waiting for flip-done prior to queueing new flips).
11397          * Experimentation says that BCS works despite DERRMR masking all
11398          * flip-done completion events and that unmasking all planes at once
11399          * for the RCS also doesn't appear to drop events. Setting the DERRMR
11400          * to zero does lead to lockups within MI_DISPLAY_FLIP.
11401          */
11402         if (req->engine->id == RCS) {
11403                 intel_ring_emit(ring, MI_LOAD_REGISTER_IMM(1));
11404                 intel_ring_emit_reg(ring, DERRMR);
11405                 intel_ring_emit(ring, ~(DERRMR_PIPEA_PRI_FLIP_DONE |
11406                                           DERRMR_PIPEB_PRI_FLIP_DONE |
11407                                           DERRMR_PIPEC_PRI_FLIP_DONE));
11408                 if (IS_GEN8(dev))
11409                         intel_ring_emit(ring, MI_STORE_REGISTER_MEM_GEN8 |
11410                                               MI_SRM_LRM_GLOBAL_GTT);
11411                 else
11412                         intel_ring_emit(ring, MI_STORE_REGISTER_MEM |
11413                                               MI_SRM_LRM_GLOBAL_GTT);
11414                 intel_ring_emit_reg(ring, DERRMR);
11415                 intel_ring_emit(ring, req->engine->scratch.gtt_offset + 256);
11416                 if (IS_GEN8(dev)) {
11417                         intel_ring_emit(ring, 0);
11418                         intel_ring_emit(ring, MI_NOOP);
11419                 }
11420         }
11421
11422         intel_ring_emit(ring, MI_DISPLAY_FLIP_I915 | plane_bit);
11423         intel_ring_emit(ring, fb->pitches[0] | i915_gem_object_get_tiling(obj));
11424         intel_ring_emit(ring, intel_crtc->flip_work->gtt_offset);
11425         intel_ring_emit(ring, (MI_NOOP));
11426
11427         return 0;
11428 }
11429
11430 static bool use_mmio_flip(struct intel_engine_cs *engine,
11431                           struct drm_i915_gem_object *obj)
11432 {
11433         struct reservation_object *resv;
11434
11435         /*
11436          * This is not being used for older platforms, because
11437          * non-availability of flip done interrupt forces us to use
11438          * CS flips. Older platforms derive flip done using some clever
11439          * tricks involving the flip_pending status bits and vblank irqs.
11440          * So using MMIO flips there would disrupt this mechanism.
11441          */
11442
11443         if (engine == NULL)
11444                 return true;
11445
11446         if (INTEL_GEN(engine->i915) < 5)
11447                 return false;
11448
11449         if (i915.use_mmio_flip < 0)
11450                 return false;
11451         else if (i915.use_mmio_flip > 0)
11452                 return true;
11453         else if (i915.enable_execlists)
11454                 return true;
11455
11456         resv = i915_gem_object_get_dmabuf_resv(obj);
11457         if (resv && !reservation_object_test_signaled_rcu(resv, false))
11458                 return true;
11459
11460         return engine != i915_gem_active_get_engine(&obj->last_write,
11461                                                     &obj->base.dev->struct_mutex);
11462 }
11463
11464 static void skl_do_mmio_flip(struct intel_crtc *intel_crtc,
11465                              unsigned int rotation,
11466                              struct intel_flip_work *work)
11467 {
11468         struct drm_device *dev = intel_crtc->base.dev;
11469         struct drm_i915_private *dev_priv = to_i915(dev);
11470         struct drm_framebuffer *fb = intel_crtc->base.primary->fb;
11471         const enum pipe pipe = intel_crtc->pipe;
11472         u32 ctl, stride, tile_height;
11473
11474         ctl = I915_READ(PLANE_CTL(pipe, 0));
11475         ctl &= ~PLANE_CTL_TILED_MASK;
11476         switch (fb->modifier[0]) {
11477         case DRM_FORMAT_MOD_NONE:
11478                 break;
11479         case I915_FORMAT_MOD_X_TILED:
11480                 ctl |= PLANE_CTL_TILED_X;
11481                 break;
11482         case I915_FORMAT_MOD_Y_TILED:
11483                 ctl |= PLANE_CTL_TILED_Y;
11484                 break;
11485         case I915_FORMAT_MOD_Yf_TILED:
11486                 ctl |= PLANE_CTL_TILED_YF;
11487                 break;
11488         default:
11489                 MISSING_CASE(fb->modifier[0]);
11490         }
11491
11492         /*
11493          * The stride is either expressed as a multiple of 64 bytes chunks for
11494          * linear buffers or in number of tiles for tiled buffers.
11495          */
11496         if (intel_rotation_90_or_270(rotation)) {
11497                 /* stride = Surface height in tiles */
11498                 tile_height = intel_tile_height(dev_priv, fb->modifier[0], 0);
11499                 stride = DIV_ROUND_UP(fb->height, tile_height);
11500         } else {
11501                 stride = fb->pitches[0] /
11502                         intel_fb_stride_alignment(dev_priv, fb->modifier[0],
11503                                                   fb->pixel_format);
11504         }
11505
11506         /*
11507          * Both PLANE_CTL and PLANE_STRIDE are not updated on vblank but on
11508          * PLANE_SURF updates, the update is then guaranteed to be atomic.
11509          */
11510         I915_WRITE(PLANE_CTL(pipe, 0), ctl);
11511         I915_WRITE(PLANE_STRIDE(pipe, 0), stride);
11512
11513         I915_WRITE(PLANE_SURF(pipe, 0), work->gtt_offset);
11514         POSTING_READ(PLANE_SURF(pipe, 0));
11515 }
11516
11517 static void ilk_do_mmio_flip(struct intel_crtc *intel_crtc,
11518                              struct intel_flip_work *work)
11519 {
11520         struct drm_device *dev = intel_crtc->base.dev;
11521         struct drm_i915_private *dev_priv = to_i915(dev);
11522         struct intel_framebuffer *intel_fb =
11523                 to_intel_framebuffer(intel_crtc->base.primary->fb);
11524         struct drm_i915_gem_object *obj = intel_fb->obj;
11525         i915_reg_t reg = DSPCNTR(intel_crtc->plane);
11526         u32 dspcntr;
11527
11528         dspcntr = I915_READ(reg);
11529
11530         if (i915_gem_object_is_tiled(obj))
11531                 dspcntr |= DISPPLANE_TILED;
11532         else
11533                 dspcntr &= ~DISPPLANE_TILED;
11534
11535         I915_WRITE(reg, dspcntr);
11536
11537         I915_WRITE(DSPSURF(intel_crtc->plane), work->gtt_offset);
11538         POSTING_READ(DSPSURF(intel_crtc->plane));
11539 }
11540
11541 static void intel_mmio_flip_work_func(struct work_struct *w)
11542 {
11543         struct intel_flip_work *work =
11544                 container_of(w, struct intel_flip_work, mmio_work);
11545         struct intel_crtc *crtc = to_intel_crtc(work->crtc);
11546         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
11547         struct intel_framebuffer *intel_fb =
11548                 to_intel_framebuffer(crtc->base.primary->fb);
11549         struct drm_i915_gem_object *obj = intel_fb->obj;
11550         struct reservation_object *resv;
11551
11552         if (work->flip_queued_req)
11553                 WARN_ON(i915_wait_request(work->flip_queued_req,
11554                                           false, NULL,
11555                                           NO_WAITBOOST));
11556
11557         /* For framebuffer backed by dmabuf, wait for fence */
11558         resv = i915_gem_object_get_dmabuf_resv(obj);
11559         if (resv)
11560                 WARN_ON(reservation_object_wait_timeout_rcu(resv, false, false,
11561                                                             MAX_SCHEDULE_TIMEOUT) < 0);
11562
11563         intel_pipe_update_start(crtc);
11564
11565         if (INTEL_GEN(dev_priv) >= 9)
11566                 skl_do_mmio_flip(crtc, work->rotation, work);
11567         else
11568                 /* use_mmio_flip() retricts MMIO flips to ilk+ */
11569                 ilk_do_mmio_flip(crtc, work);
11570
11571         intel_pipe_update_end(crtc, work);
11572 }
11573
11574 static int intel_default_queue_flip(struct drm_device *dev,
11575                                     struct drm_crtc *crtc,
11576                                     struct drm_framebuffer *fb,
11577                                     struct drm_i915_gem_object *obj,
11578                                     struct drm_i915_gem_request *req,
11579                                     uint32_t flags)
11580 {
11581         return -ENODEV;
11582 }
11583
11584 static bool __pageflip_stall_check_cs(struct drm_i915_private *dev_priv,
11585                                       struct intel_crtc *intel_crtc,
11586                                       struct intel_flip_work *work)
11587 {
11588         u32 addr, vblank;
11589
11590         if (!atomic_read(&work->pending))
11591                 return false;
11592
11593         smp_rmb();
11594
11595         vblank = intel_crtc_get_vblank_counter(intel_crtc);
11596         if (work->flip_ready_vblank == 0) {
11597                 if (work->flip_queued_req &&
11598                     !i915_gem_request_completed(work->flip_queued_req))
11599                         return false;
11600
11601                 work->flip_ready_vblank = vblank;
11602         }
11603
11604         if (vblank - work->flip_ready_vblank < 3)
11605                 return false;
11606
11607         /* Potential stall - if we see that the flip has happened,
11608          * assume a missed interrupt. */
11609         if (INTEL_GEN(dev_priv) >= 4)
11610                 addr = I915_HI_DISPBASE(I915_READ(DSPSURF(intel_crtc->plane)));
11611         else
11612                 addr = I915_READ(DSPADDR(intel_crtc->plane));
11613
11614         /* There is a potential issue here with a false positive after a flip
11615          * to the same address. We could address this by checking for a
11616          * non-incrementing frame counter.
11617          */
11618         return addr == work->gtt_offset;
11619 }
11620
11621 void intel_check_page_flip(struct drm_i915_private *dev_priv, int pipe)
11622 {
11623         struct drm_device *dev = &dev_priv->drm;
11624         struct drm_crtc *crtc = dev_priv->pipe_to_crtc_mapping[pipe];
11625         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
11626         struct intel_flip_work *work;
11627
11628         WARN_ON(!in_interrupt());
11629
11630         if (crtc == NULL)
11631                 return;
11632
11633         spin_lock(&dev->event_lock);
11634         work = intel_crtc->flip_work;
11635
11636         if (work != NULL && !is_mmio_work(work) &&
11637             __pageflip_stall_check_cs(dev_priv, intel_crtc, work)) {
11638                 WARN_ONCE(1,
11639                           "Kicking stuck page flip: queued at %d, now %d\n",
11640                         work->flip_queued_vblank, intel_crtc_get_vblank_counter(intel_crtc));
11641                 page_flip_completed(intel_crtc);
11642                 work = NULL;
11643         }
11644
11645         if (work != NULL && !is_mmio_work(work) &&
11646             intel_crtc_get_vblank_counter(intel_crtc) - work->flip_queued_vblank > 1)
11647                 intel_queue_rps_boost_for_request(work->flip_queued_req);
11648         spin_unlock(&dev->event_lock);
11649 }
11650
11651 static int intel_crtc_page_flip(struct drm_crtc *crtc,
11652                                 struct drm_framebuffer *fb,
11653                                 struct drm_pending_vblank_event *event,
11654                                 uint32_t page_flip_flags)
11655 {
11656         struct drm_device *dev = crtc->dev;
11657         struct drm_i915_private *dev_priv = to_i915(dev);
11658         struct drm_framebuffer *old_fb = crtc->primary->fb;
11659         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
11660         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
11661         struct drm_plane *primary = crtc->primary;
11662         enum pipe pipe = intel_crtc->pipe;
11663         struct intel_flip_work *work;
11664         struct intel_engine_cs *engine;
11665         bool mmio_flip;
11666         struct drm_i915_gem_request *request;
11667         int ret;
11668
11669         /*
11670          * drm_mode_page_flip_ioctl() should already catch this, but double
11671          * check to be safe.  In the future we may enable pageflipping from
11672          * a disabled primary plane.
11673          */
11674         if (WARN_ON(intel_fb_obj(old_fb) == NULL))
11675                 return -EBUSY;
11676
11677         /* Can't change pixel format via MI display flips. */
11678         if (fb->pixel_format != crtc->primary->fb->pixel_format)
11679                 return -EINVAL;
11680
11681         /*
11682          * TILEOFF/LINOFF registers can't be changed via MI display flips.
11683          * Note that pitch changes could also affect these register.
11684          */
11685         if (INTEL_INFO(dev)->gen > 3 &&
11686             (fb->offsets[0] != crtc->primary->fb->offsets[0] ||
11687              fb->pitches[0] != crtc->primary->fb->pitches[0]))
11688                 return -EINVAL;
11689
11690         if (i915_terminally_wedged(&dev_priv->gpu_error))
11691                 goto out_hang;
11692
11693         work = kzalloc(sizeof(*work), GFP_KERNEL);
11694         if (work == NULL)
11695                 return -ENOMEM;
11696
11697         work->event = event;
11698         work->crtc = crtc;
11699         work->old_fb = old_fb;
11700         INIT_WORK(&work->unpin_work, intel_unpin_work_fn);
11701
11702         ret = drm_crtc_vblank_get(crtc);
11703         if (ret)
11704                 goto free_work;
11705
11706         /* We borrow the event spin lock for protecting flip_work */
11707         spin_lock_irq(&dev->event_lock);
11708         if (intel_crtc->flip_work) {
11709                 /* Before declaring the flip queue wedged, check if
11710                  * the hardware completed the operation behind our backs.
11711                  */
11712                 if (pageflip_finished(intel_crtc, intel_crtc->flip_work)) {
11713                         DRM_DEBUG_DRIVER("flip queue: previous flip completed, continuing\n");
11714                         page_flip_completed(intel_crtc);
11715                 } else {
11716                         DRM_DEBUG_DRIVER("flip queue: crtc already busy\n");
11717                         spin_unlock_irq(&dev->event_lock);
11718
11719                         drm_crtc_vblank_put(crtc);
11720                         kfree(work);
11721                         return -EBUSY;
11722                 }
11723         }
11724         intel_crtc->flip_work = work;
11725         spin_unlock_irq(&dev->event_lock);
11726
11727         if (atomic_read(&intel_crtc->unpin_work_count) >= 2)
11728                 flush_workqueue(dev_priv->wq);
11729
11730         /* Reference the objects for the scheduled work. */
11731         drm_framebuffer_reference(work->old_fb);
11732
11733         crtc->primary->fb = fb;
11734         update_state_fb(crtc->primary);
11735
11736         intel_fbc_pre_update(intel_crtc, intel_crtc->config,
11737                              to_intel_plane_state(primary->state));
11738
11739         work->pending_flip_obj = i915_gem_object_get(obj);
11740
11741         ret = i915_mutex_lock_interruptible(dev);
11742         if (ret)
11743                 goto cleanup;
11744
11745         intel_crtc->reset_counter = i915_reset_counter(&dev_priv->gpu_error);
11746         if (__i915_reset_in_progress_or_wedged(intel_crtc->reset_counter)) {
11747                 ret = -EIO;
11748                 goto cleanup;
11749         }
11750
11751         atomic_inc(&intel_crtc->unpin_work_count);
11752
11753         if (INTEL_INFO(dev)->gen >= 5 || IS_G4X(dev))
11754                 work->flip_count = I915_READ(PIPE_FLIPCOUNT_G4X(pipe)) + 1;
11755
11756         if (IS_VALLEYVIEW(dev) || IS_CHERRYVIEW(dev)) {
11757                 engine = &dev_priv->engine[BCS];
11758                 if (i915_gem_object_get_tiling(obj) !=
11759                     i915_gem_object_get_tiling(intel_fb_obj(work->old_fb)))
11760                         /* vlv: DISPLAY_FLIP fails to change tiling */
11761                         engine = NULL;
11762         } else if (IS_IVYBRIDGE(dev) || IS_HASWELL(dev)) {
11763                 engine = &dev_priv->engine[BCS];
11764         } else if (INTEL_INFO(dev)->gen >= 7) {
11765                 engine = i915_gem_active_get_engine(&obj->last_write,
11766                                                     &obj->base.dev->struct_mutex);
11767                 if (engine == NULL || engine->id != RCS)
11768                         engine = &dev_priv->engine[BCS];
11769         } else {
11770                 engine = &dev_priv->engine[RCS];
11771         }
11772
11773         mmio_flip = use_mmio_flip(engine, obj);
11774
11775         ret = intel_pin_and_fence_fb_obj(fb, primary->state->rotation);
11776         if (ret)
11777                 goto cleanup_pending;
11778
11779         work->gtt_offset = intel_plane_obj_offset(to_intel_plane(primary),
11780                                                   obj, 0);
11781         work->gtt_offset += intel_crtc->dspaddr_offset;
11782         work->rotation = crtc->primary->state->rotation;
11783
11784         if (mmio_flip) {
11785                 INIT_WORK(&work->mmio_work, intel_mmio_flip_work_func);
11786
11787                 work->flip_queued_req = i915_gem_active_get(&obj->last_write,
11788                                                             &obj->base.dev->struct_mutex);
11789                 schedule_work(&work->mmio_work);
11790         } else {
11791                 request = i915_gem_request_alloc(engine, engine->last_context);
11792                 if (IS_ERR(request)) {
11793                         ret = PTR_ERR(request);
11794                         goto cleanup_unpin;
11795                 }
11796
11797                 ret = i915_gem_object_sync(obj, request);
11798                 if (ret)
11799                         goto cleanup_request;
11800
11801                 ret = dev_priv->display.queue_flip(dev, crtc, fb, obj, request,
11802                                                    page_flip_flags);
11803                 if (ret)
11804                         goto cleanup_request;
11805
11806                 intel_mark_page_flip_active(intel_crtc, work);
11807
11808                 work->flip_queued_req = i915_gem_request_get(request);
11809                 i915_add_request_no_flush(request);
11810         }
11811
11812         i915_gem_track_fb(intel_fb_obj(old_fb), obj,
11813                           to_intel_plane(primary)->frontbuffer_bit);
11814         mutex_unlock(&dev->struct_mutex);
11815
11816         intel_frontbuffer_flip_prepare(to_i915(dev),
11817                                        to_intel_plane(primary)->frontbuffer_bit);
11818
11819         trace_i915_flip_request(intel_crtc->plane, obj);
11820
11821         return 0;
11822
11823 cleanup_request:
11824         i915_add_request_no_flush(request);
11825 cleanup_unpin:
11826         intel_unpin_fb_obj(fb, crtc->primary->state->rotation);
11827 cleanup_pending:
11828         atomic_dec(&intel_crtc->unpin_work_count);
11829         mutex_unlock(&dev->struct_mutex);
11830 cleanup:
11831         crtc->primary->fb = old_fb;
11832         update_state_fb(crtc->primary);
11833
11834         i915_gem_object_put_unlocked(obj);
11835         drm_framebuffer_unreference(work->old_fb);
11836
11837         spin_lock_irq(&dev->event_lock);
11838         intel_crtc->flip_work = NULL;
11839         spin_unlock_irq(&dev->event_lock);
11840
11841         drm_crtc_vblank_put(crtc);
11842 free_work:
11843         kfree(work);
11844
11845         if (ret == -EIO) {
11846                 struct drm_atomic_state *state;
11847                 struct drm_plane_state *plane_state;
11848
11849 out_hang:
11850                 state = drm_atomic_state_alloc(dev);
11851                 if (!state)
11852                         return -ENOMEM;
11853                 state->acquire_ctx = drm_modeset_legacy_acquire_ctx(crtc);
11854
11855 retry:
11856                 plane_state = drm_atomic_get_plane_state(state, primary);
11857                 ret = PTR_ERR_OR_ZERO(plane_state);
11858                 if (!ret) {
11859                         drm_atomic_set_fb_for_plane(plane_state, fb);
11860
11861                         ret = drm_atomic_set_crtc_for_plane(plane_state, crtc);
11862                         if (!ret)
11863                                 ret = drm_atomic_commit(state);
11864                 }
11865
11866                 if (ret == -EDEADLK) {
11867                         drm_modeset_backoff(state->acquire_ctx);
11868                         drm_atomic_state_clear(state);
11869                         goto retry;
11870                 }
11871
11872                 if (ret)
11873                         drm_atomic_state_free(state);
11874
11875                 if (ret == 0 && event) {
11876                         spin_lock_irq(&dev->event_lock);
11877                         drm_crtc_send_vblank_event(crtc, event);
11878                         spin_unlock_irq(&dev->event_lock);
11879                 }
11880         }
11881         return ret;
11882 }
11883
11884
11885 /**
11886  * intel_wm_need_update - Check whether watermarks need updating
11887  * @plane: drm plane
11888  * @state: new plane state
11889  *
11890  * Check current plane state versus the new one to determine whether
11891  * watermarks need to be recalculated.
11892  *
11893  * Returns true or false.
11894  */
11895 static bool intel_wm_need_update(struct drm_plane *plane,
11896                                  struct drm_plane_state *state)
11897 {
11898         struct intel_plane_state *new = to_intel_plane_state(state);
11899         struct intel_plane_state *cur = to_intel_plane_state(plane->state);
11900
11901         /* Update watermarks on tiling or size changes. */
11902         if (new->visible != cur->visible)
11903                 return true;
11904
11905         if (!cur->base.fb || !new->base.fb)
11906                 return false;
11907
11908         if (cur->base.fb->modifier[0] != new->base.fb->modifier[0] ||
11909             cur->base.rotation != new->base.rotation ||
11910             drm_rect_width(&new->src) != drm_rect_width(&cur->src) ||
11911             drm_rect_height(&new->src) != drm_rect_height(&cur->src) ||
11912             drm_rect_width(&new->dst) != drm_rect_width(&cur->dst) ||
11913             drm_rect_height(&new->dst) != drm_rect_height(&cur->dst))
11914                 return true;
11915
11916         return false;
11917 }
11918
11919 static bool needs_scaling(struct intel_plane_state *state)
11920 {
11921         int src_w = drm_rect_width(&state->src) >> 16;
11922         int src_h = drm_rect_height(&state->src) >> 16;
11923         int dst_w = drm_rect_width(&state->dst);
11924         int dst_h = drm_rect_height(&state->dst);
11925
11926         return (src_w != dst_w || src_h != dst_h);
11927 }
11928
11929 int intel_plane_atomic_calc_changes(struct drm_crtc_state *crtc_state,
11930                                     struct drm_plane_state *plane_state)
11931 {
11932         struct intel_crtc_state *pipe_config = to_intel_crtc_state(crtc_state);
11933         struct drm_crtc *crtc = crtc_state->crtc;
11934         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
11935         struct drm_plane *plane = plane_state->plane;
11936         struct drm_device *dev = crtc->dev;
11937         struct drm_i915_private *dev_priv = to_i915(dev);
11938         struct intel_plane_state *old_plane_state =
11939                 to_intel_plane_state(plane->state);
11940         bool mode_changed = needs_modeset(crtc_state);
11941         bool was_crtc_enabled = crtc->state->active;
11942         bool is_crtc_enabled = crtc_state->active;
11943         bool turn_off, turn_on, visible, was_visible;
11944         struct drm_framebuffer *fb = plane_state->fb;
11945         int ret;
11946
11947         if (INTEL_GEN(dev) >= 9 && plane->type != DRM_PLANE_TYPE_CURSOR) {
11948                 ret = skl_update_scaler_plane(
11949                         to_intel_crtc_state(crtc_state),
11950                         to_intel_plane_state(plane_state));
11951                 if (ret)
11952                         return ret;
11953         }
11954
11955         was_visible = old_plane_state->visible;
11956         visible = to_intel_plane_state(plane_state)->visible;
11957
11958         if (!was_crtc_enabled && WARN_ON(was_visible))
11959                 was_visible = false;
11960
11961         /*
11962          * Visibility is calculated as if the crtc was on, but
11963          * after scaler setup everything depends on it being off
11964          * when the crtc isn't active.
11965          *
11966          * FIXME this is wrong for watermarks. Watermarks should also
11967          * be computed as if the pipe would be active. Perhaps move
11968          * per-plane wm computation to the .check_plane() hook, and
11969          * only combine the results from all planes in the current place?
11970          */
11971         if (!is_crtc_enabled)
11972                 to_intel_plane_state(plane_state)->visible = visible = false;
11973
11974         if (!was_visible && !visible)
11975                 return 0;
11976
11977         if (fb != old_plane_state->base.fb)
11978                 pipe_config->fb_changed = true;
11979
11980         turn_off = was_visible && (!visible || mode_changed);
11981         turn_on = visible && (!was_visible || mode_changed);
11982
11983         DRM_DEBUG_ATOMIC("[CRTC:%d:%s] has [PLANE:%d:%s] with fb %i\n",
11984                          intel_crtc->base.base.id,
11985                          intel_crtc->base.name,
11986                          plane->base.id, plane->name,
11987                          fb ? fb->base.id : -1);
11988
11989         DRM_DEBUG_ATOMIC("[PLANE:%d:%s] visible %i -> %i, off %i, on %i, ms %i\n",
11990                          plane->base.id, plane->name,
11991                          was_visible, visible,
11992                          turn_off, turn_on, mode_changed);
11993
11994         if (turn_on) {
11995                 pipe_config->update_wm_pre = 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 (turn_off) {
12001                 pipe_config->update_wm_post = true;
12002
12003                 /* must disable cxsr around plane enable/disable */
12004                 if (plane->type != DRM_PLANE_TYPE_CURSOR)
12005                         pipe_config->disable_cxsr = true;
12006         } else if (intel_wm_need_update(plane, plane_state)) {
12007                 /* FIXME bollocks */
12008                 pipe_config->update_wm_pre = true;
12009                 pipe_config->update_wm_post = true;
12010         }
12011
12012         /* Pre-gen9 platforms need two-step watermark updates */
12013         if ((pipe_config->update_wm_pre || pipe_config->update_wm_post) &&
12014             INTEL_INFO(dev)->gen < 9 && dev_priv->display.optimize_watermarks)
12015                 to_intel_crtc_state(crtc_state)->wm.need_postvbl_update = true;
12016
12017         if (visible || was_visible)
12018                 pipe_config->fb_bits |= to_intel_plane(plane)->frontbuffer_bit;
12019
12020         /*
12021          * WaCxSRDisabledForSpriteScaling:ivb
12022          *
12023          * cstate->update_wm was already set above, so this flag will
12024          * take effect when we commit and program watermarks.
12025          */
12026         if (plane->type == DRM_PLANE_TYPE_OVERLAY && IS_IVYBRIDGE(dev) &&
12027             needs_scaling(to_intel_plane_state(plane_state)) &&
12028             !needs_scaling(old_plane_state))
12029                 pipe_config->disable_lp_wm = true;
12030
12031         return 0;
12032 }
12033
12034 static bool encoders_cloneable(const struct intel_encoder *a,
12035                                const struct intel_encoder *b)
12036 {
12037         /* masks could be asymmetric, so check both ways */
12038         return a == b || (a->cloneable & (1 << b->type) &&
12039                           b->cloneable & (1 << a->type));
12040 }
12041
12042 static bool check_single_encoder_cloning(struct drm_atomic_state *state,
12043                                          struct intel_crtc *crtc,
12044                                          struct intel_encoder *encoder)
12045 {
12046         struct intel_encoder *source_encoder;
12047         struct drm_connector *connector;
12048         struct drm_connector_state *connector_state;
12049         int i;
12050
12051         for_each_connector_in_state(state, connector, connector_state, i) {
12052                 if (connector_state->crtc != &crtc->base)
12053                         continue;
12054
12055                 source_encoder =
12056                         to_intel_encoder(connector_state->best_encoder);
12057                 if (!encoders_cloneable(encoder, source_encoder))
12058                         return false;
12059         }
12060
12061         return true;
12062 }
12063
12064 static int intel_crtc_atomic_check(struct drm_crtc *crtc,
12065                                    struct drm_crtc_state *crtc_state)
12066 {
12067         struct drm_device *dev = crtc->dev;
12068         struct drm_i915_private *dev_priv = to_i915(dev);
12069         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
12070         struct intel_crtc_state *pipe_config =
12071                 to_intel_crtc_state(crtc_state);
12072         struct drm_atomic_state *state = crtc_state->state;
12073         int ret;
12074         bool mode_changed = needs_modeset(crtc_state);
12075
12076         if (mode_changed && !crtc_state->active)
12077                 pipe_config->update_wm_post = true;
12078
12079         if (mode_changed && crtc_state->enable &&
12080             dev_priv->display.crtc_compute_clock &&
12081             !WARN_ON(pipe_config->shared_dpll)) {
12082                 ret = dev_priv->display.crtc_compute_clock(intel_crtc,
12083                                                            pipe_config);
12084                 if (ret)
12085                         return ret;
12086         }
12087
12088         if (crtc_state->color_mgmt_changed) {
12089                 ret = intel_color_check(crtc, crtc_state);
12090                 if (ret)
12091                         return ret;
12092
12093                 /*
12094                  * Changing color management on Intel hardware is
12095                  * handled as part of planes update.
12096                  */
12097                 crtc_state->planes_changed = true;
12098         }
12099
12100         ret = 0;
12101         if (dev_priv->display.compute_pipe_wm) {
12102                 ret = dev_priv->display.compute_pipe_wm(pipe_config);
12103                 if (ret) {
12104                         DRM_DEBUG_KMS("Target pipe watermarks are invalid\n");
12105                         return ret;
12106                 }
12107         }
12108
12109         if (dev_priv->display.compute_intermediate_wm &&
12110             !to_intel_atomic_state(state)->skip_intermediate_wm) {
12111                 if (WARN_ON(!dev_priv->display.compute_pipe_wm))
12112                         return 0;
12113
12114                 /*
12115                  * Calculate 'intermediate' watermarks that satisfy both the
12116                  * old state and the new state.  We can program these
12117                  * immediately.
12118                  */
12119                 ret = dev_priv->display.compute_intermediate_wm(crtc->dev,
12120                                                                 intel_crtc,
12121                                                                 pipe_config);
12122                 if (ret) {
12123                         DRM_DEBUG_KMS("No valid intermediate pipe watermarks are possible\n");
12124                         return ret;
12125                 }
12126         } else if (dev_priv->display.compute_intermediate_wm) {
12127                 if (HAS_PCH_SPLIT(dev_priv) && INTEL_GEN(dev_priv) < 9)
12128                         pipe_config->wm.ilk.intermediate = pipe_config->wm.ilk.optimal;
12129         }
12130
12131         if (INTEL_INFO(dev)->gen >= 9) {
12132                 if (mode_changed)
12133                         ret = skl_update_scaler_crtc(pipe_config);
12134
12135                 if (!ret)
12136                         ret = intel_atomic_setup_scalers(dev, intel_crtc,
12137                                                          pipe_config);
12138         }
12139
12140         return ret;
12141 }
12142
12143 static const struct drm_crtc_helper_funcs intel_helper_funcs = {
12144         .mode_set_base_atomic = intel_pipe_set_base_atomic,
12145         .atomic_begin = intel_begin_crtc_commit,
12146         .atomic_flush = intel_finish_crtc_commit,
12147         .atomic_check = intel_crtc_atomic_check,
12148 };
12149
12150 static void intel_modeset_update_connector_atomic_state(struct drm_device *dev)
12151 {
12152         struct intel_connector *connector;
12153
12154         for_each_intel_connector(dev, connector) {
12155                 if (connector->base.state->crtc)
12156                         drm_connector_unreference(&connector->base);
12157
12158                 if (connector->base.encoder) {
12159                         connector->base.state->best_encoder =
12160                                 connector->base.encoder;
12161                         connector->base.state->crtc =
12162                                 connector->base.encoder->crtc;
12163
12164                         drm_connector_reference(&connector->base);
12165                 } else {
12166                         connector->base.state->best_encoder = NULL;
12167                         connector->base.state->crtc = NULL;
12168                 }
12169         }
12170 }
12171
12172 static void
12173 connected_sink_compute_bpp(struct intel_connector *connector,
12174                            struct intel_crtc_state *pipe_config)
12175 {
12176         int bpp = pipe_config->pipe_bpp;
12177
12178         DRM_DEBUG_KMS("[CONNECTOR:%d:%s] checking for sink bpp constrains\n",
12179                 connector->base.base.id,
12180                 connector->base.name);
12181
12182         /* Don't use an invalid EDID bpc value */
12183         if (connector->base.display_info.bpc &&
12184             connector->base.display_info.bpc * 3 < bpp) {
12185                 DRM_DEBUG_KMS("clamping display bpp (was %d) to EDID reported max of %d\n",
12186                               bpp, connector->base.display_info.bpc*3);
12187                 pipe_config->pipe_bpp = connector->base.display_info.bpc*3;
12188         }
12189
12190         /* Clamp bpp to default limit on screens without EDID 1.4 */
12191         if (connector->base.display_info.bpc == 0) {
12192                 int type = connector->base.connector_type;
12193                 int clamp_bpp = 24;
12194
12195                 /* Fall back to 18 bpp when DP sink capability is unknown. */
12196                 if (type == DRM_MODE_CONNECTOR_DisplayPort ||
12197                     type == DRM_MODE_CONNECTOR_eDP)
12198                         clamp_bpp = 18;
12199
12200                 if (bpp > clamp_bpp) {
12201                         DRM_DEBUG_KMS("clamping display bpp (was %d) to default limit of %d\n",
12202                                       bpp, clamp_bpp);
12203                         pipe_config->pipe_bpp = clamp_bpp;
12204                 }
12205         }
12206 }
12207
12208 static int
12209 compute_baseline_pipe_bpp(struct intel_crtc *crtc,
12210                           struct intel_crtc_state *pipe_config)
12211 {
12212         struct drm_device *dev = crtc->base.dev;
12213         struct drm_atomic_state *state;
12214         struct drm_connector *connector;
12215         struct drm_connector_state *connector_state;
12216         int bpp, i;
12217
12218         if ((IS_G4X(dev) || IS_VALLEYVIEW(dev) || IS_CHERRYVIEW(dev)))
12219                 bpp = 10*3;
12220         else if (INTEL_INFO(dev)->gen >= 5)
12221                 bpp = 12*3;
12222         else
12223                 bpp = 8*3;
12224
12225
12226         pipe_config->pipe_bpp = bpp;
12227
12228         state = pipe_config->base.state;
12229
12230         /* Clamp display bpp to EDID value */
12231         for_each_connector_in_state(state, connector, connector_state, i) {
12232                 if (connector_state->crtc != &crtc->base)
12233                         continue;
12234
12235                 connected_sink_compute_bpp(to_intel_connector(connector),
12236                                            pipe_config);
12237         }
12238
12239         return bpp;
12240 }
12241
12242 static void intel_dump_crtc_timings(const struct drm_display_mode *mode)
12243 {
12244         DRM_DEBUG_KMS("crtc timings: %d %d %d %d %d %d %d %d %d, "
12245                         "type: 0x%x flags: 0x%x\n",
12246                 mode->crtc_clock,
12247                 mode->crtc_hdisplay, mode->crtc_hsync_start,
12248                 mode->crtc_hsync_end, mode->crtc_htotal,
12249                 mode->crtc_vdisplay, mode->crtc_vsync_start,
12250                 mode->crtc_vsync_end, mode->crtc_vtotal, mode->type, mode->flags);
12251 }
12252
12253 static void intel_dump_pipe_config(struct intel_crtc *crtc,
12254                                    struct intel_crtc_state *pipe_config,
12255                                    const char *context)
12256 {
12257         struct drm_device *dev = crtc->base.dev;
12258         struct drm_plane *plane;
12259         struct intel_plane *intel_plane;
12260         struct intel_plane_state *state;
12261         struct drm_framebuffer *fb;
12262
12263         DRM_DEBUG_KMS("[CRTC:%d:%s]%s config %p for pipe %c\n",
12264                       crtc->base.base.id, crtc->base.name,
12265                       context, pipe_config, pipe_name(crtc->pipe));
12266
12267         DRM_DEBUG_KMS("cpu_transcoder: %s\n", transcoder_name(pipe_config->cpu_transcoder));
12268         DRM_DEBUG_KMS("pipe bpp: %i, dithering: %i\n",
12269                       pipe_config->pipe_bpp, pipe_config->dither);
12270         DRM_DEBUG_KMS("fdi/pch: %i, lanes: %i, gmch_m: %u, gmch_n: %u, link_m: %u, link_n: %u, tu: %u\n",
12271                       pipe_config->has_pch_encoder,
12272                       pipe_config->fdi_lanes,
12273                       pipe_config->fdi_m_n.gmch_m, pipe_config->fdi_m_n.gmch_n,
12274                       pipe_config->fdi_m_n.link_m, pipe_config->fdi_m_n.link_n,
12275                       pipe_config->fdi_m_n.tu);
12276         DRM_DEBUG_KMS("dp: %i, lanes: %i, gmch_m: %u, gmch_n: %u, link_m: %u, link_n: %u, tu: %u\n",
12277                       intel_crtc_has_dp_encoder(pipe_config),
12278                       pipe_config->lane_count,
12279                       pipe_config->dp_m_n.gmch_m, pipe_config->dp_m_n.gmch_n,
12280                       pipe_config->dp_m_n.link_m, pipe_config->dp_m_n.link_n,
12281                       pipe_config->dp_m_n.tu);
12282
12283         DRM_DEBUG_KMS("dp: %i, lanes: %i, gmch_m2: %u, gmch_n2: %u, link_m2: %u, link_n2: %u, tu2: %u\n",
12284                       intel_crtc_has_dp_encoder(pipe_config),
12285                       pipe_config->lane_count,
12286                       pipe_config->dp_m2_n2.gmch_m,
12287                       pipe_config->dp_m2_n2.gmch_n,
12288                       pipe_config->dp_m2_n2.link_m,
12289                       pipe_config->dp_m2_n2.link_n,
12290                       pipe_config->dp_m2_n2.tu);
12291
12292         DRM_DEBUG_KMS("audio: %i, infoframes: %i\n",
12293                       pipe_config->has_audio,
12294                       pipe_config->has_infoframe);
12295
12296         DRM_DEBUG_KMS("requested mode:\n");
12297         drm_mode_debug_printmodeline(&pipe_config->base.mode);
12298         DRM_DEBUG_KMS("adjusted mode:\n");
12299         drm_mode_debug_printmodeline(&pipe_config->base.adjusted_mode);
12300         intel_dump_crtc_timings(&pipe_config->base.adjusted_mode);
12301         DRM_DEBUG_KMS("port clock: %d\n", pipe_config->port_clock);
12302         DRM_DEBUG_KMS("pipe src size: %dx%d\n",
12303                       pipe_config->pipe_src_w, pipe_config->pipe_src_h);
12304         DRM_DEBUG_KMS("num_scalers: %d, scaler_users: 0x%x, scaler_id: %d\n",
12305                       crtc->num_scalers,
12306                       pipe_config->scaler_state.scaler_users,
12307                       pipe_config->scaler_state.scaler_id);
12308         DRM_DEBUG_KMS("gmch pfit: control: 0x%08x, ratios: 0x%08x, lvds border: 0x%08x\n",
12309                       pipe_config->gmch_pfit.control,
12310                       pipe_config->gmch_pfit.pgm_ratios,
12311                       pipe_config->gmch_pfit.lvds_border_bits);
12312         DRM_DEBUG_KMS("pch pfit: pos: 0x%08x, size: 0x%08x, %s\n",
12313                       pipe_config->pch_pfit.pos,
12314                       pipe_config->pch_pfit.size,
12315                       pipe_config->pch_pfit.enabled ? "enabled" : "disabled");
12316         DRM_DEBUG_KMS("ips: %i\n", pipe_config->ips_enabled);
12317         DRM_DEBUG_KMS("double wide: %i\n", pipe_config->double_wide);
12318
12319         if (IS_BROXTON(dev)) {
12320                 DRM_DEBUG_KMS("ddi_pll_sel: %u; dpll_hw_state: ebb0: 0x%x, ebb4: 0x%x,"
12321                               "pll0: 0x%x, pll1: 0x%x, pll2: 0x%x, pll3: 0x%x, "
12322                               "pll6: 0x%x, pll8: 0x%x, pll9: 0x%x, pll10: 0x%x, pcsdw12: 0x%x\n",
12323                               pipe_config->ddi_pll_sel,
12324                               pipe_config->dpll_hw_state.ebb0,
12325                               pipe_config->dpll_hw_state.ebb4,
12326                               pipe_config->dpll_hw_state.pll0,
12327                               pipe_config->dpll_hw_state.pll1,
12328                               pipe_config->dpll_hw_state.pll2,
12329                               pipe_config->dpll_hw_state.pll3,
12330                               pipe_config->dpll_hw_state.pll6,
12331                               pipe_config->dpll_hw_state.pll8,
12332                               pipe_config->dpll_hw_state.pll9,
12333                               pipe_config->dpll_hw_state.pll10,
12334                               pipe_config->dpll_hw_state.pcsdw12);
12335         } else if (IS_SKYLAKE(dev) || IS_KABYLAKE(dev)) {
12336                 DRM_DEBUG_KMS("ddi_pll_sel: %u; dpll_hw_state: "
12337                               "ctrl1: 0x%x, cfgcr1: 0x%x, cfgcr2: 0x%x\n",
12338                               pipe_config->ddi_pll_sel,
12339                               pipe_config->dpll_hw_state.ctrl1,
12340                               pipe_config->dpll_hw_state.cfgcr1,
12341                               pipe_config->dpll_hw_state.cfgcr2);
12342         } else if (HAS_DDI(dev)) {
12343                 DRM_DEBUG_KMS("ddi_pll_sel: 0x%x; dpll_hw_state: wrpll: 0x%x spll: 0x%x\n",
12344                               pipe_config->ddi_pll_sel,
12345                               pipe_config->dpll_hw_state.wrpll,
12346                               pipe_config->dpll_hw_state.spll);
12347         } else {
12348                 DRM_DEBUG_KMS("dpll_hw_state: dpll: 0x%x, dpll_md: 0x%x, "
12349                               "fp0: 0x%x, fp1: 0x%x\n",
12350                               pipe_config->dpll_hw_state.dpll,
12351                               pipe_config->dpll_hw_state.dpll_md,
12352                               pipe_config->dpll_hw_state.fp0,
12353                               pipe_config->dpll_hw_state.fp1);
12354         }
12355
12356         DRM_DEBUG_KMS("planes on this crtc\n");
12357         list_for_each_entry(plane, &dev->mode_config.plane_list, head) {
12358                 intel_plane = to_intel_plane(plane);
12359                 if (intel_plane->pipe != crtc->pipe)
12360                         continue;
12361
12362                 state = to_intel_plane_state(plane->state);
12363                 fb = state->base.fb;
12364                 if (!fb) {
12365                         DRM_DEBUG_KMS("[PLANE:%d:%s] disabled, scaler_id = %d\n",
12366                                       plane->base.id, plane->name, state->scaler_id);
12367                         continue;
12368                 }
12369
12370                 DRM_DEBUG_KMS("[PLANE:%d:%s] enabled",
12371                               plane->base.id, plane->name);
12372                 DRM_DEBUG_KMS("\tFB:%d, fb = %ux%u format = %s",
12373                               fb->base.id, fb->width, fb->height,
12374                               drm_get_format_name(fb->pixel_format));
12375                 DRM_DEBUG_KMS("\tscaler:%d src %dx%d+%d+%d dst %dx%d+%d+%d\n",
12376                               state->scaler_id,
12377                               state->src.x1 >> 16, state->src.y1 >> 16,
12378                               drm_rect_width(&state->src) >> 16,
12379                               drm_rect_height(&state->src) >> 16,
12380                               state->dst.x1, state->dst.y1,
12381                               drm_rect_width(&state->dst),
12382                               drm_rect_height(&state->dst));
12383         }
12384 }
12385
12386 static bool check_digital_port_conflicts(struct drm_atomic_state *state)
12387 {
12388         struct drm_device *dev = state->dev;
12389         struct drm_connector *connector;
12390         unsigned int used_ports = 0;
12391         unsigned int used_mst_ports = 0;
12392
12393         /*
12394          * Walk the connector list instead of the encoder
12395          * list to detect the problem on ddi platforms
12396          * where there's just one encoder per digital port.
12397          */
12398         drm_for_each_connector(connector, dev) {
12399                 struct drm_connector_state *connector_state;
12400                 struct intel_encoder *encoder;
12401
12402                 connector_state = drm_atomic_get_existing_connector_state(state, connector);
12403                 if (!connector_state)
12404                         connector_state = connector->state;
12405
12406                 if (!connector_state->best_encoder)
12407                         continue;
12408
12409                 encoder = to_intel_encoder(connector_state->best_encoder);
12410
12411                 WARN_ON(!connector_state->crtc);
12412
12413                 switch (encoder->type) {
12414                         unsigned int port_mask;
12415                 case INTEL_OUTPUT_UNKNOWN:
12416                         if (WARN_ON(!HAS_DDI(dev)))
12417                                 break;
12418                 case INTEL_OUTPUT_DP:
12419                 case INTEL_OUTPUT_HDMI:
12420                 case INTEL_OUTPUT_EDP:
12421                         port_mask = 1 << enc_to_dig_port(&encoder->base)->port;
12422
12423                         /* the same port mustn't appear more than once */
12424                         if (used_ports & port_mask)
12425                                 return false;
12426
12427                         used_ports |= port_mask;
12428                         break;
12429                 case INTEL_OUTPUT_DP_MST:
12430                         used_mst_ports |=
12431                                 1 << enc_to_mst(&encoder->base)->primary->port;
12432                         break;
12433                 default:
12434                         break;
12435                 }
12436         }
12437
12438         /* can't mix MST and SST/HDMI on the same port */
12439         if (used_ports & used_mst_ports)
12440                 return false;
12441
12442         return true;
12443 }
12444
12445 static void
12446 clear_intel_crtc_state(struct intel_crtc_state *crtc_state)
12447 {
12448         struct drm_crtc_state tmp_state;
12449         struct intel_crtc_scaler_state scaler_state;
12450         struct intel_dpll_hw_state dpll_hw_state;
12451         struct intel_shared_dpll *shared_dpll;
12452         uint32_t ddi_pll_sel;
12453         bool force_thru;
12454
12455         /* FIXME: before the switch to atomic started, a new pipe_config was
12456          * kzalloc'd. Code that depends on any field being zero should be
12457          * fixed, so that the crtc_state can be safely duplicated. For now,
12458          * only fields that are know to not cause problems are preserved. */
12459
12460         tmp_state = crtc_state->base;
12461         scaler_state = crtc_state->scaler_state;
12462         shared_dpll = crtc_state->shared_dpll;
12463         dpll_hw_state = crtc_state->dpll_hw_state;
12464         ddi_pll_sel = crtc_state->ddi_pll_sel;
12465         force_thru = crtc_state->pch_pfit.force_thru;
12466
12467         memset(crtc_state, 0, sizeof *crtc_state);
12468
12469         crtc_state->base = tmp_state;
12470         crtc_state->scaler_state = scaler_state;
12471         crtc_state->shared_dpll = shared_dpll;
12472         crtc_state->dpll_hw_state = dpll_hw_state;
12473         crtc_state->ddi_pll_sel = ddi_pll_sel;
12474         crtc_state->pch_pfit.force_thru = force_thru;
12475 }
12476
12477 static int
12478 intel_modeset_pipe_config(struct drm_crtc *crtc,
12479                           struct intel_crtc_state *pipe_config)
12480 {
12481         struct drm_atomic_state *state = pipe_config->base.state;
12482         struct intel_encoder *encoder;
12483         struct drm_connector *connector;
12484         struct drm_connector_state *connector_state;
12485         int base_bpp, ret = -EINVAL;
12486         int i;
12487         bool retry = true;
12488
12489         clear_intel_crtc_state(pipe_config);
12490
12491         pipe_config->cpu_transcoder =
12492                 (enum transcoder) to_intel_crtc(crtc)->pipe;
12493
12494         /*
12495          * Sanitize sync polarity flags based on requested ones. If neither
12496          * positive or negative polarity is requested, treat this as meaning
12497          * negative polarity.
12498          */
12499         if (!(pipe_config->base.adjusted_mode.flags &
12500               (DRM_MODE_FLAG_PHSYNC | DRM_MODE_FLAG_NHSYNC)))
12501                 pipe_config->base.adjusted_mode.flags |= DRM_MODE_FLAG_NHSYNC;
12502
12503         if (!(pipe_config->base.adjusted_mode.flags &
12504               (DRM_MODE_FLAG_PVSYNC | DRM_MODE_FLAG_NVSYNC)))
12505                 pipe_config->base.adjusted_mode.flags |= DRM_MODE_FLAG_NVSYNC;
12506
12507         base_bpp = compute_baseline_pipe_bpp(to_intel_crtc(crtc),
12508                                              pipe_config);
12509         if (base_bpp < 0)
12510                 goto fail;
12511
12512         /*
12513          * Determine the real pipe dimensions. Note that stereo modes can
12514          * increase the actual pipe size due to the frame doubling and
12515          * insertion of additional space for blanks between the frame. This
12516          * is stored in the crtc timings. We use the requested mode to do this
12517          * computation to clearly distinguish it from the adjusted mode, which
12518          * can be changed by the connectors in the below retry loop.
12519          */
12520         drm_crtc_get_hv_timing(&pipe_config->base.mode,
12521                                &pipe_config->pipe_src_w,
12522                                &pipe_config->pipe_src_h);
12523
12524         for_each_connector_in_state(state, connector, connector_state, i) {
12525                 if (connector_state->crtc != crtc)
12526                         continue;
12527
12528                 encoder = to_intel_encoder(connector_state->best_encoder);
12529
12530                 if (!check_single_encoder_cloning(state, to_intel_crtc(crtc), encoder)) {
12531                         DRM_DEBUG_KMS("rejecting invalid cloning configuration\n");
12532                         goto fail;
12533                 }
12534
12535                 /*
12536                  * Determine output_types before calling the .compute_config()
12537                  * hooks so that the hooks can use this information safely.
12538                  */
12539                 pipe_config->output_types |= 1 << encoder->type;
12540         }
12541
12542 encoder_retry:
12543         /* Ensure the port clock defaults are reset when retrying. */
12544         pipe_config->port_clock = 0;
12545         pipe_config->pixel_multiplier = 1;
12546
12547         /* Fill in default crtc timings, allow encoders to overwrite them. */
12548         drm_mode_set_crtcinfo(&pipe_config->base.adjusted_mode,
12549                               CRTC_STEREO_DOUBLE);
12550
12551         /* Pass our mode to the connectors and the CRTC to give them a chance to
12552          * adjust it according to limitations or connector properties, and also
12553          * a chance to reject the mode entirely.
12554          */
12555         for_each_connector_in_state(state, connector, connector_state, i) {
12556                 if (connector_state->crtc != crtc)
12557                         continue;
12558
12559                 encoder = to_intel_encoder(connector_state->best_encoder);
12560
12561                 if (!(encoder->compute_config(encoder, pipe_config))) {
12562                         DRM_DEBUG_KMS("Encoder config failure\n");
12563                         goto fail;
12564                 }
12565         }
12566
12567         /* Set default port clock if not overwritten by the encoder. Needs to be
12568          * done afterwards in case the encoder adjusts the mode. */
12569         if (!pipe_config->port_clock)
12570                 pipe_config->port_clock = pipe_config->base.adjusted_mode.crtc_clock
12571                         * pipe_config->pixel_multiplier;
12572
12573         ret = intel_crtc_compute_config(to_intel_crtc(crtc), pipe_config);
12574         if (ret < 0) {
12575                 DRM_DEBUG_KMS("CRTC fixup failed\n");
12576                 goto fail;
12577         }
12578
12579         if (ret == RETRY) {
12580                 if (WARN(!retry, "loop in pipe configuration computation\n")) {
12581                         ret = -EINVAL;
12582                         goto fail;
12583                 }
12584
12585                 DRM_DEBUG_KMS("CRTC bw constrained, retrying\n");
12586                 retry = false;
12587                 goto encoder_retry;
12588         }
12589
12590         /* Dithering seems to not pass-through bits correctly when it should, so
12591          * only enable it on 6bpc panels. */
12592         pipe_config->dither = pipe_config->pipe_bpp == 6*3;
12593         DRM_DEBUG_KMS("hw max bpp: %i, pipe bpp: %i, dithering: %i\n",
12594                       base_bpp, pipe_config->pipe_bpp, pipe_config->dither);
12595
12596 fail:
12597         return ret;
12598 }
12599
12600 static void
12601 intel_modeset_update_crtc_state(struct drm_atomic_state *state)
12602 {
12603         struct drm_crtc *crtc;
12604         struct drm_crtc_state *crtc_state;
12605         int i;
12606
12607         /* Double check state. */
12608         for_each_crtc_in_state(state, crtc, crtc_state, i) {
12609                 to_intel_crtc(crtc)->config = to_intel_crtc_state(crtc->state);
12610
12611                 /* Update hwmode for vblank functions */
12612                 if (crtc->state->active)
12613                         crtc->hwmode = crtc->state->adjusted_mode;
12614                 else
12615                         crtc->hwmode.crtc_clock = 0;
12616
12617                 /*
12618                  * Update legacy state to satisfy fbc code. This can
12619                  * be removed when fbc uses the atomic state.
12620                  */
12621                 if (drm_atomic_get_existing_plane_state(state, crtc->primary)) {
12622                         struct drm_plane_state *plane_state = crtc->primary->state;
12623
12624                         crtc->primary->fb = plane_state->fb;
12625                         crtc->x = plane_state->src_x >> 16;
12626                         crtc->y = plane_state->src_y >> 16;
12627                 }
12628         }
12629 }
12630
12631 static bool intel_fuzzy_clock_check(int clock1, int clock2)
12632 {
12633         int diff;
12634
12635         if (clock1 == clock2)
12636                 return true;
12637
12638         if (!clock1 || !clock2)
12639                 return false;
12640
12641         diff = abs(clock1 - clock2);
12642
12643         if (((((diff + clock1 + clock2) * 100)) / (clock1 + clock2)) < 105)
12644                 return true;
12645
12646         return false;
12647 }
12648
12649 #define for_each_intel_crtc_masked(dev, mask, intel_crtc) \
12650         list_for_each_entry((intel_crtc), \
12651                             &(dev)->mode_config.crtc_list, \
12652                             base.head) \
12653                 for_each_if (mask & (1 <<(intel_crtc)->pipe))
12654
12655 static bool
12656 intel_compare_m_n(unsigned int m, unsigned int n,
12657                   unsigned int m2, unsigned int n2,
12658                   bool exact)
12659 {
12660         if (m == m2 && n == n2)
12661                 return true;
12662
12663         if (exact || !m || !n || !m2 || !n2)
12664                 return false;
12665
12666         BUILD_BUG_ON(DATA_LINK_M_N_MASK > INT_MAX);
12667
12668         if (n > n2) {
12669                 while (n > n2) {
12670                         m2 <<= 1;
12671                         n2 <<= 1;
12672                 }
12673         } else if (n < n2) {
12674                 while (n < n2) {
12675                         m <<= 1;
12676                         n <<= 1;
12677                 }
12678         }
12679
12680         if (n != n2)
12681                 return false;
12682
12683         return intel_fuzzy_clock_check(m, m2);
12684 }
12685
12686 static bool
12687 intel_compare_link_m_n(const struct intel_link_m_n *m_n,
12688                        struct intel_link_m_n *m2_n2,
12689                        bool adjust)
12690 {
12691         if (m_n->tu == m2_n2->tu &&
12692             intel_compare_m_n(m_n->gmch_m, m_n->gmch_n,
12693                               m2_n2->gmch_m, m2_n2->gmch_n, !adjust) &&
12694             intel_compare_m_n(m_n->link_m, m_n->link_n,
12695                               m2_n2->link_m, m2_n2->link_n, !adjust)) {
12696                 if (adjust)
12697                         *m2_n2 = *m_n;
12698
12699                 return true;
12700         }
12701
12702         return false;
12703 }
12704
12705 static bool
12706 intel_pipe_config_compare(struct drm_device *dev,
12707                           struct intel_crtc_state *current_config,
12708                           struct intel_crtc_state *pipe_config,
12709                           bool adjust)
12710 {
12711         bool ret = true;
12712
12713 #define INTEL_ERR_OR_DBG_KMS(fmt, ...) \
12714         do { \
12715                 if (!adjust) \
12716                         DRM_ERROR(fmt, ##__VA_ARGS__); \
12717                 else \
12718                         DRM_DEBUG_KMS(fmt, ##__VA_ARGS__); \
12719         } while (0)
12720
12721 #define PIPE_CONF_CHECK_X(name) \
12722         if (current_config->name != pipe_config->name) { \
12723                 INTEL_ERR_OR_DBG_KMS("mismatch in " #name " " \
12724                           "(expected 0x%08x, found 0x%08x)\n", \
12725                           current_config->name, \
12726                           pipe_config->name); \
12727                 ret = false; \
12728         }
12729
12730 #define PIPE_CONF_CHECK_I(name) \
12731         if (current_config->name != pipe_config->name) { \
12732                 INTEL_ERR_OR_DBG_KMS("mismatch in " #name " " \
12733                           "(expected %i, found %i)\n", \
12734                           current_config->name, \
12735                           pipe_config->name); \
12736                 ret = false; \
12737         }
12738
12739 #define PIPE_CONF_CHECK_P(name) \
12740         if (current_config->name != pipe_config->name) { \
12741                 INTEL_ERR_OR_DBG_KMS("mismatch in " #name " " \
12742                           "(expected %p, found %p)\n", \
12743                           current_config->name, \
12744                           pipe_config->name); \
12745                 ret = false; \
12746         }
12747
12748 #define PIPE_CONF_CHECK_M_N(name) \
12749         if (!intel_compare_link_m_n(&current_config->name, \
12750                                     &pipe_config->name,\
12751                                     adjust)) { \
12752                 INTEL_ERR_OR_DBG_KMS("mismatch in " #name " " \
12753                           "(expected tu %i gmch %i/%i link %i/%i, " \
12754                           "found tu %i, gmch %i/%i link %i/%i)\n", \
12755                           current_config->name.tu, \
12756                           current_config->name.gmch_m, \
12757                           current_config->name.gmch_n, \
12758                           current_config->name.link_m, \
12759                           current_config->name.link_n, \
12760                           pipe_config->name.tu, \
12761                           pipe_config->name.gmch_m, \
12762                           pipe_config->name.gmch_n, \
12763                           pipe_config->name.link_m, \
12764                           pipe_config->name.link_n); \
12765                 ret = false; \
12766         }
12767
12768 /* This is required for BDW+ where there is only one set of registers for
12769  * switching between high and low RR.
12770  * This macro can be used whenever a comparison has to be made between one
12771  * hw state and multiple sw state variables.
12772  */
12773 #define PIPE_CONF_CHECK_M_N_ALT(name, alt_name) \
12774         if (!intel_compare_link_m_n(&current_config->name, \
12775                                     &pipe_config->name, adjust) && \
12776             !intel_compare_link_m_n(&current_config->alt_name, \
12777                                     &pipe_config->name, adjust)) { \
12778                 INTEL_ERR_OR_DBG_KMS("mismatch in " #name " " \
12779                           "(expected tu %i gmch %i/%i link %i/%i, " \
12780                           "or tu %i gmch %i/%i link %i/%i, " \
12781                           "found tu %i, gmch %i/%i link %i/%i)\n", \
12782                           current_config->name.tu, \
12783                           current_config->name.gmch_m, \
12784                           current_config->name.gmch_n, \
12785                           current_config->name.link_m, \
12786                           current_config->name.link_n, \
12787                           current_config->alt_name.tu, \
12788                           current_config->alt_name.gmch_m, \
12789                           current_config->alt_name.gmch_n, \
12790                           current_config->alt_name.link_m, \
12791                           current_config->alt_name.link_n, \
12792                           pipe_config->name.tu, \
12793                           pipe_config->name.gmch_m, \
12794                           pipe_config->name.gmch_n, \
12795                           pipe_config->name.link_m, \
12796                           pipe_config->name.link_n); \
12797                 ret = false; \
12798         }
12799
12800 #define PIPE_CONF_CHECK_FLAGS(name, mask)       \
12801         if ((current_config->name ^ pipe_config->name) & (mask)) { \
12802                 INTEL_ERR_OR_DBG_KMS("mismatch in " #name "(" #mask ") " \
12803                           "(expected %i, found %i)\n", \
12804                           current_config->name & (mask), \
12805                           pipe_config->name & (mask)); \
12806                 ret = false; \
12807         }
12808
12809 #define PIPE_CONF_CHECK_CLOCK_FUZZY(name) \
12810         if (!intel_fuzzy_clock_check(current_config->name, pipe_config->name)) { \
12811                 INTEL_ERR_OR_DBG_KMS("mismatch in " #name " " \
12812                           "(expected %i, found %i)\n", \
12813                           current_config->name, \
12814                           pipe_config->name); \
12815                 ret = false; \
12816         }
12817
12818 #define PIPE_CONF_QUIRK(quirk)  \
12819         ((current_config->quirks | pipe_config->quirks) & (quirk))
12820
12821         PIPE_CONF_CHECK_I(cpu_transcoder);
12822
12823         PIPE_CONF_CHECK_I(has_pch_encoder);
12824         PIPE_CONF_CHECK_I(fdi_lanes);
12825         PIPE_CONF_CHECK_M_N(fdi_m_n);
12826
12827         PIPE_CONF_CHECK_I(lane_count);
12828         PIPE_CONF_CHECK_X(lane_lat_optim_mask);
12829
12830         if (INTEL_INFO(dev)->gen < 8) {
12831                 PIPE_CONF_CHECK_M_N(dp_m_n);
12832
12833                 if (current_config->has_drrs)
12834                         PIPE_CONF_CHECK_M_N(dp_m2_n2);
12835         } else
12836                 PIPE_CONF_CHECK_M_N_ALT(dp_m_n, dp_m2_n2);
12837
12838         PIPE_CONF_CHECK_X(output_types);
12839
12840         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hdisplay);
12841         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_htotal);
12842         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hblank_start);
12843         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hblank_end);
12844         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hsync_start);
12845         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hsync_end);
12846
12847         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vdisplay);
12848         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vtotal);
12849         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vblank_start);
12850         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vblank_end);
12851         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vsync_start);
12852         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vsync_end);
12853
12854         PIPE_CONF_CHECK_I(pixel_multiplier);
12855         PIPE_CONF_CHECK_I(has_hdmi_sink);
12856         if ((INTEL_INFO(dev)->gen < 8 && !IS_HASWELL(dev)) ||
12857             IS_VALLEYVIEW(dev) || IS_CHERRYVIEW(dev))
12858                 PIPE_CONF_CHECK_I(limited_color_range);
12859         PIPE_CONF_CHECK_I(has_infoframe);
12860
12861         PIPE_CONF_CHECK_I(has_audio);
12862
12863         PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
12864                               DRM_MODE_FLAG_INTERLACE);
12865
12866         if (!PIPE_CONF_QUIRK(PIPE_CONFIG_QUIRK_MODE_SYNC_FLAGS)) {
12867                 PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
12868                                       DRM_MODE_FLAG_PHSYNC);
12869                 PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
12870                                       DRM_MODE_FLAG_NHSYNC);
12871                 PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
12872                                       DRM_MODE_FLAG_PVSYNC);
12873                 PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
12874                                       DRM_MODE_FLAG_NVSYNC);
12875         }
12876
12877         PIPE_CONF_CHECK_X(gmch_pfit.control);
12878         /* pfit ratios are autocomputed by the hw on gen4+ */
12879         if (INTEL_INFO(dev)->gen < 4)
12880                 PIPE_CONF_CHECK_X(gmch_pfit.pgm_ratios);
12881         PIPE_CONF_CHECK_X(gmch_pfit.lvds_border_bits);
12882
12883         if (!adjust) {
12884                 PIPE_CONF_CHECK_I(pipe_src_w);
12885                 PIPE_CONF_CHECK_I(pipe_src_h);
12886
12887                 PIPE_CONF_CHECK_I(pch_pfit.enabled);
12888                 if (current_config->pch_pfit.enabled) {
12889                         PIPE_CONF_CHECK_X(pch_pfit.pos);
12890                         PIPE_CONF_CHECK_X(pch_pfit.size);
12891                 }
12892
12893                 PIPE_CONF_CHECK_I(scaler_state.scaler_id);
12894         }
12895
12896         /* BDW+ don't expose a synchronous way to read the state */
12897         if (IS_HASWELL(dev))
12898                 PIPE_CONF_CHECK_I(ips_enabled);
12899
12900         PIPE_CONF_CHECK_I(double_wide);
12901
12902         PIPE_CONF_CHECK_X(ddi_pll_sel);
12903
12904         PIPE_CONF_CHECK_P(shared_dpll);
12905         PIPE_CONF_CHECK_X(dpll_hw_state.dpll);
12906         PIPE_CONF_CHECK_X(dpll_hw_state.dpll_md);
12907         PIPE_CONF_CHECK_X(dpll_hw_state.fp0);
12908         PIPE_CONF_CHECK_X(dpll_hw_state.fp1);
12909         PIPE_CONF_CHECK_X(dpll_hw_state.wrpll);
12910         PIPE_CONF_CHECK_X(dpll_hw_state.spll);
12911         PIPE_CONF_CHECK_X(dpll_hw_state.ctrl1);
12912         PIPE_CONF_CHECK_X(dpll_hw_state.cfgcr1);
12913         PIPE_CONF_CHECK_X(dpll_hw_state.cfgcr2);
12914
12915         PIPE_CONF_CHECK_X(dsi_pll.ctrl);
12916         PIPE_CONF_CHECK_X(dsi_pll.div);
12917
12918         if (IS_G4X(dev) || INTEL_INFO(dev)->gen >= 5)
12919                 PIPE_CONF_CHECK_I(pipe_bpp);
12920
12921         PIPE_CONF_CHECK_CLOCK_FUZZY(base.adjusted_mode.crtc_clock);
12922         PIPE_CONF_CHECK_CLOCK_FUZZY(port_clock);
12923
12924 #undef PIPE_CONF_CHECK_X
12925 #undef PIPE_CONF_CHECK_I
12926 #undef PIPE_CONF_CHECK_P
12927 #undef PIPE_CONF_CHECK_FLAGS
12928 #undef PIPE_CONF_CHECK_CLOCK_FUZZY
12929 #undef PIPE_CONF_QUIRK
12930 #undef INTEL_ERR_OR_DBG_KMS
12931
12932         return ret;
12933 }
12934
12935 static void intel_pipe_config_sanity_check(struct drm_i915_private *dev_priv,
12936                                            const struct intel_crtc_state *pipe_config)
12937 {
12938         if (pipe_config->has_pch_encoder) {
12939                 int fdi_dotclock = intel_dotclock_calculate(intel_fdi_link_freq(dev_priv, pipe_config),
12940                                                             &pipe_config->fdi_m_n);
12941                 int dotclock = pipe_config->base.adjusted_mode.crtc_clock;
12942
12943                 /*
12944                  * FDI already provided one idea for the dotclock.
12945                  * Yell if the encoder disagrees.
12946                  */
12947                 WARN(!intel_fuzzy_clock_check(fdi_dotclock, dotclock),
12948                      "FDI dotclock and encoder dotclock mismatch, fdi: %i, encoder: %i\n",
12949                      fdi_dotclock, dotclock);
12950         }
12951 }
12952
12953 static void verify_wm_state(struct drm_crtc *crtc,
12954                             struct drm_crtc_state *new_state)
12955 {
12956         struct drm_device *dev = crtc->dev;
12957         struct drm_i915_private *dev_priv = to_i915(dev);
12958         struct skl_ddb_allocation hw_ddb, *sw_ddb;
12959         struct skl_ddb_entry *hw_entry, *sw_entry;
12960         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
12961         const enum pipe pipe = intel_crtc->pipe;
12962         int plane;
12963
12964         if (INTEL_INFO(dev)->gen < 9 || !new_state->active)
12965                 return;
12966
12967         skl_ddb_get_hw_state(dev_priv, &hw_ddb);
12968         sw_ddb = &dev_priv->wm.skl_hw.ddb;
12969
12970         /* planes */
12971         for_each_plane(dev_priv, pipe, plane) {
12972                 hw_entry = &hw_ddb.plane[pipe][plane];
12973                 sw_entry = &sw_ddb->plane[pipe][plane];
12974
12975                 if (skl_ddb_entry_equal(hw_entry, sw_entry))
12976                         continue;
12977
12978                 DRM_ERROR("mismatch in DDB state pipe %c plane %d "
12979                           "(expected (%u,%u), found (%u,%u))\n",
12980                           pipe_name(pipe), plane + 1,
12981                           sw_entry->start, sw_entry->end,
12982                           hw_entry->start, hw_entry->end);
12983         }
12984
12985         /* cursor */
12986         hw_entry = &hw_ddb.plane[pipe][PLANE_CURSOR];
12987         sw_entry = &sw_ddb->plane[pipe][PLANE_CURSOR];
12988
12989         if (!skl_ddb_entry_equal(hw_entry, sw_entry)) {
12990                 DRM_ERROR("mismatch in DDB state pipe %c cursor "
12991                           "(expected (%u,%u), found (%u,%u))\n",
12992                           pipe_name(pipe),
12993                           sw_entry->start, sw_entry->end,
12994                           hw_entry->start, hw_entry->end);
12995         }
12996 }
12997
12998 static void
12999 verify_connector_state(struct drm_device *dev, struct drm_crtc *crtc)
13000 {
13001         struct drm_connector *connector;
13002
13003         drm_for_each_connector(connector, dev) {
13004                 struct drm_encoder *encoder = connector->encoder;
13005                 struct drm_connector_state *state = connector->state;
13006
13007                 if (state->crtc != crtc)
13008                         continue;
13009
13010                 intel_connector_verify_state(to_intel_connector(connector));
13011
13012                 I915_STATE_WARN(state->best_encoder != encoder,
13013                      "connector's atomic encoder doesn't match legacy encoder\n");
13014         }
13015 }
13016
13017 static void
13018 verify_encoder_state(struct drm_device *dev)
13019 {
13020         struct intel_encoder *encoder;
13021         struct intel_connector *connector;
13022
13023         for_each_intel_encoder(dev, encoder) {
13024                 bool enabled = false;
13025                 enum pipe pipe;
13026
13027                 DRM_DEBUG_KMS("[ENCODER:%d:%s]\n",
13028                               encoder->base.base.id,
13029                               encoder->base.name);
13030
13031                 for_each_intel_connector(dev, connector) {
13032                         if (connector->base.state->best_encoder != &encoder->base)
13033                                 continue;
13034                         enabled = true;
13035
13036                         I915_STATE_WARN(connector->base.state->crtc !=
13037                                         encoder->base.crtc,
13038                              "connector's crtc doesn't match encoder crtc\n");
13039                 }
13040
13041                 I915_STATE_WARN(!!encoder->base.crtc != enabled,
13042                      "encoder's enabled state mismatch "
13043                      "(expected %i, found %i)\n",
13044                      !!encoder->base.crtc, enabled);
13045
13046                 if (!encoder->base.crtc) {
13047                         bool active;
13048
13049                         active = encoder->get_hw_state(encoder, &pipe);
13050                         I915_STATE_WARN(active,
13051                              "encoder detached but still enabled on pipe %c.\n",
13052                              pipe_name(pipe));
13053                 }
13054         }
13055 }
13056
13057 static void
13058 verify_crtc_state(struct drm_crtc *crtc,
13059                   struct drm_crtc_state *old_crtc_state,
13060                   struct drm_crtc_state *new_crtc_state)
13061 {
13062         struct drm_device *dev = crtc->dev;
13063         struct drm_i915_private *dev_priv = to_i915(dev);
13064         struct intel_encoder *encoder;
13065         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
13066         struct intel_crtc_state *pipe_config, *sw_config;
13067         struct drm_atomic_state *old_state;
13068         bool active;
13069
13070         old_state = old_crtc_state->state;
13071         __drm_atomic_helper_crtc_destroy_state(old_crtc_state);
13072         pipe_config = to_intel_crtc_state(old_crtc_state);
13073         memset(pipe_config, 0, sizeof(*pipe_config));
13074         pipe_config->base.crtc = crtc;
13075         pipe_config->base.state = old_state;
13076
13077         DRM_DEBUG_KMS("[CRTC:%d:%s]\n", crtc->base.id, crtc->name);
13078
13079         active = dev_priv->display.get_pipe_config(intel_crtc, pipe_config);
13080
13081         /* hw state is inconsistent with the pipe quirk */
13082         if ((intel_crtc->pipe == PIPE_A && dev_priv->quirks & QUIRK_PIPEA_FORCE) ||
13083             (intel_crtc->pipe == PIPE_B && dev_priv->quirks & QUIRK_PIPEB_FORCE))
13084                 active = new_crtc_state->active;
13085
13086         I915_STATE_WARN(new_crtc_state->active != active,
13087              "crtc active state doesn't match with hw state "
13088              "(expected %i, found %i)\n", new_crtc_state->active, active);
13089
13090         I915_STATE_WARN(intel_crtc->active != new_crtc_state->active,
13091              "transitional active state does not match atomic hw state "
13092              "(expected %i, found %i)\n", new_crtc_state->active, intel_crtc->active);
13093
13094         for_each_encoder_on_crtc(dev, crtc, encoder) {
13095                 enum pipe pipe;
13096
13097                 active = encoder->get_hw_state(encoder, &pipe);
13098                 I915_STATE_WARN(active != new_crtc_state->active,
13099                         "[ENCODER:%i] active %i with crtc active %i\n",
13100                         encoder->base.base.id, active, new_crtc_state->active);
13101
13102                 I915_STATE_WARN(active && intel_crtc->pipe != pipe,
13103                                 "Encoder connected to wrong pipe %c\n",
13104                                 pipe_name(pipe));
13105
13106                 if (active) {
13107                         pipe_config->output_types |= 1 << encoder->type;
13108                         encoder->get_config(encoder, pipe_config);
13109                 }
13110         }
13111
13112         if (!new_crtc_state->active)
13113                 return;
13114
13115         intel_pipe_config_sanity_check(dev_priv, pipe_config);
13116
13117         sw_config = to_intel_crtc_state(crtc->state);
13118         if (!intel_pipe_config_compare(dev, sw_config,
13119                                        pipe_config, false)) {
13120                 I915_STATE_WARN(1, "pipe state doesn't match!\n");
13121                 intel_dump_pipe_config(intel_crtc, pipe_config,
13122                                        "[hw state]");
13123                 intel_dump_pipe_config(intel_crtc, sw_config,
13124                                        "[sw state]");
13125         }
13126 }
13127
13128 static void
13129 verify_single_dpll_state(struct drm_i915_private *dev_priv,
13130                          struct intel_shared_dpll *pll,
13131                          struct drm_crtc *crtc,
13132                          struct drm_crtc_state *new_state)
13133 {
13134         struct intel_dpll_hw_state dpll_hw_state;
13135         unsigned crtc_mask;
13136         bool active;
13137
13138         memset(&dpll_hw_state, 0, sizeof(dpll_hw_state));
13139
13140         DRM_DEBUG_KMS("%s\n", pll->name);
13141
13142         active = pll->funcs.get_hw_state(dev_priv, pll, &dpll_hw_state);
13143
13144         if (!(pll->flags & INTEL_DPLL_ALWAYS_ON)) {
13145                 I915_STATE_WARN(!pll->on && pll->active_mask,
13146                      "pll in active use but not on in sw tracking\n");
13147                 I915_STATE_WARN(pll->on && !pll->active_mask,
13148                      "pll is on but not used by any active crtc\n");
13149                 I915_STATE_WARN(pll->on != active,
13150                      "pll on state mismatch (expected %i, found %i)\n",
13151                      pll->on, active);
13152         }
13153
13154         if (!crtc) {
13155                 I915_STATE_WARN(pll->active_mask & ~pll->config.crtc_mask,
13156                                 "more active pll users than references: %x vs %x\n",
13157                                 pll->active_mask, pll->config.crtc_mask);
13158
13159                 return;
13160         }
13161
13162         crtc_mask = 1 << drm_crtc_index(crtc);
13163
13164         if (new_state->active)
13165                 I915_STATE_WARN(!(pll->active_mask & crtc_mask),
13166                                 "pll active mismatch (expected pipe %c in active mask 0x%02x)\n",
13167                                 pipe_name(drm_crtc_index(crtc)), pll->active_mask);
13168         else
13169                 I915_STATE_WARN(pll->active_mask & crtc_mask,
13170                                 "pll active mismatch (didn't expect pipe %c in active mask 0x%02x)\n",
13171                                 pipe_name(drm_crtc_index(crtc)), pll->active_mask);
13172
13173         I915_STATE_WARN(!(pll->config.crtc_mask & crtc_mask),
13174                         "pll enabled crtcs mismatch (expected 0x%x in 0x%02x)\n",
13175                         crtc_mask, pll->config.crtc_mask);
13176
13177         I915_STATE_WARN(pll->on && memcmp(&pll->config.hw_state,
13178                                           &dpll_hw_state,
13179                                           sizeof(dpll_hw_state)),
13180                         "pll hw state mismatch\n");
13181 }
13182
13183 static void
13184 verify_shared_dpll_state(struct drm_device *dev, struct drm_crtc *crtc,
13185                          struct drm_crtc_state *old_crtc_state,
13186                          struct drm_crtc_state *new_crtc_state)
13187 {
13188         struct drm_i915_private *dev_priv = to_i915(dev);
13189         struct intel_crtc_state *old_state = to_intel_crtc_state(old_crtc_state);
13190         struct intel_crtc_state *new_state = to_intel_crtc_state(new_crtc_state);
13191
13192         if (new_state->shared_dpll)
13193                 verify_single_dpll_state(dev_priv, new_state->shared_dpll, crtc, new_crtc_state);
13194
13195         if (old_state->shared_dpll &&
13196             old_state->shared_dpll != new_state->shared_dpll) {
13197                 unsigned crtc_mask = 1 << drm_crtc_index(crtc);
13198                 struct intel_shared_dpll *pll = old_state->shared_dpll;
13199
13200                 I915_STATE_WARN(pll->active_mask & crtc_mask,
13201                                 "pll active mismatch (didn't expect pipe %c in active mask)\n",
13202                                 pipe_name(drm_crtc_index(crtc)));
13203                 I915_STATE_WARN(pll->config.crtc_mask & crtc_mask,
13204                                 "pll enabled crtcs mismatch (found %x in enabled mask)\n",
13205                                 pipe_name(drm_crtc_index(crtc)));
13206         }
13207 }
13208
13209 static void
13210 intel_modeset_verify_crtc(struct drm_crtc *crtc,
13211                          struct drm_crtc_state *old_state,
13212                          struct drm_crtc_state *new_state)
13213 {
13214         if (!needs_modeset(new_state) &&
13215             !to_intel_crtc_state(new_state)->update_pipe)
13216                 return;
13217
13218         verify_wm_state(crtc, new_state);
13219         verify_connector_state(crtc->dev, crtc);
13220         verify_crtc_state(crtc, old_state, new_state);
13221         verify_shared_dpll_state(crtc->dev, crtc, old_state, new_state);
13222 }
13223
13224 static void
13225 verify_disabled_dpll_state(struct drm_device *dev)
13226 {
13227         struct drm_i915_private *dev_priv = to_i915(dev);
13228         int i;
13229
13230         for (i = 0; i < dev_priv->num_shared_dpll; i++)
13231                 verify_single_dpll_state(dev_priv, &dev_priv->shared_dplls[i], NULL, NULL);
13232 }
13233
13234 static void
13235 intel_modeset_verify_disabled(struct drm_device *dev)
13236 {
13237         verify_encoder_state(dev);
13238         verify_connector_state(dev, NULL);
13239         verify_disabled_dpll_state(dev);
13240 }
13241
13242 static void update_scanline_offset(struct intel_crtc *crtc)
13243 {
13244         struct drm_device *dev = crtc->base.dev;
13245
13246         /*
13247          * The scanline counter increments at the leading edge of hsync.
13248          *
13249          * On most platforms it starts counting from vtotal-1 on the
13250          * first active line. That means the scanline counter value is
13251          * always one less than what we would expect. Ie. just after
13252          * start of vblank, which also occurs at start of hsync (on the
13253          * last active line), the scanline counter will read vblank_start-1.
13254          *
13255          * On gen2 the scanline counter starts counting from 1 instead
13256          * of vtotal-1, so we have to subtract one (or rather add vtotal-1
13257          * to keep the value positive), instead of adding one.
13258          *
13259          * On HSW+ the behaviour of the scanline counter depends on the output
13260          * type. For DP ports it behaves like most other platforms, but on HDMI
13261          * there's an extra 1 line difference. So we need to add two instead of
13262          * one to the value.
13263          */
13264         if (IS_GEN2(dev)) {
13265                 const struct drm_display_mode *adjusted_mode = &crtc->config->base.adjusted_mode;
13266                 int vtotal;
13267
13268                 vtotal = adjusted_mode->crtc_vtotal;
13269                 if (adjusted_mode->flags & DRM_MODE_FLAG_INTERLACE)
13270                         vtotal /= 2;
13271
13272                 crtc->scanline_offset = vtotal - 1;
13273         } else if (HAS_DDI(dev) &&
13274                    intel_crtc_has_type(crtc->config, INTEL_OUTPUT_HDMI)) {
13275                 crtc->scanline_offset = 2;
13276         } else
13277                 crtc->scanline_offset = 1;
13278 }
13279
13280 static void intel_modeset_clear_plls(struct drm_atomic_state *state)
13281 {
13282         struct drm_device *dev = state->dev;
13283         struct drm_i915_private *dev_priv = to_i915(dev);
13284         struct intel_shared_dpll_config *shared_dpll = NULL;
13285         struct drm_crtc *crtc;
13286         struct drm_crtc_state *crtc_state;
13287         int i;
13288
13289         if (!dev_priv->display.crtc_compute_clock)
13290                 return;
13291
13292         for_each_crtc_in_state(state, crtc, crtc_state, i) {
13293                 struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
13294                 struct intel_shared_dpll *old_dpll =
13295                         to_intel_crtc_state(crtc->state)->shared_dpll;
13296
13297                 if (!needs_modeset(crtc_state))
13298                         continue;
13299
13300                 to_intel_crtc_state(crtc_state)->shared_dpll = NULL;
13301
13302                 if (!old_dpll)
13303                         continue;
13304
13305                 if (!shared_dpll)
13306                         shared_dpll = intel_atomic_get_shared_dpll_state(state);
13307
13308                 intel_shared_dpll_config_put(shared_dpll, old_dpll, intel_crtc);
13309         }
13310 }
13311
13312 /*
13313  * This implements the workaround described in the "notes" section of the mode
13314  * set sequence documentation. When going from no pipes or single pipe to
13315  * multiple pipes, and planes are enabled after the pipe, we need to wait at
13316  * least 2 vblanks on the first pipe before enabling planes on the second pipe.
13317  */
13318 static int haswell_mode_set_planes_workaround(struct drm_atomic_state *state)
13319 {
13320         struct drm_crtc_state *crtc_state;
13321         struct intel_crtc *intel_crtc;
13322         struct drm_crtc *crtc;
13323         struct intel_crtc_state *first_crtc_state = NULL;
13324         struct intel_crtc_state *other_crtc_state = NULL;
13325         enum pipe first_pipe = INVALID_PIPE, enabled_pipe = INVALID_PIPE;
13326         int i;
13327
13328         /* look at all crtc's that are going to be enabled in during modeset */
13329         for_each_crtc_in_state(state, crtc, crtc_state, i) {
13330                 intel_crtc = to_intel_crtc(crtc);
13331
13332                 if (!crtc_state->active || !needs_modeset(crtc_state))
13333                         continue;
13334
13335                 if (first_crtc_state) {
13336                         other_crtc_state = to_intel_crtc_state(crtc_state);
13337                         break;
13338                 } else {
13339                         first_crtc_state = to_intel_crtc_state(crtc_state);
13340                         first_pipe = intel_crtc->pipe;
13341                 }
13342         }
13343
13344         /* No workaround needed? */
13345         if (!first_crtc_state)
13346                 return 0;
13347
13348         /* w/a possibly needed, check how many crtc's are already enabled. */
13349         for_each_intel_crtc(state->dev, intel_crtc) {
13350                 struct intel_crtc_state *pipe_config;
13351
13352                 pipe_config = intel_atomic_get_crtc_state(state, intel_crtc);
13353                 if (IS_ERR(pipe_config))
13354                         return PTR_ERR(pipe_config);
13355
13356                 pipe_config->hsw_workaround_pipe = INVALID_PIPE;
13357
13358                 if (!pipe_config->base.active ||
13359                     needs_modeset(&pipe_config->base))
13360                         continue;
13361
13362                 /* 2 or more enabled crtcs means no need for w/a */
13363                 if (enabled_pipe != INVALID_PIPE)
13364                         return 0;
13365
13366                 enabled_pipe = intel_crtc->pipe;
13367         }
13368
13369         if (enabled_pipe != INVALID_PIPE)
13370                 first_crtc_state->hsw_workaround_pipe = enabled_pipe;
13371         else if (other_crtc_state)
13372                 other_crtc_state->hsw_workaround_pipe = first_pipe;
13373
13374         return 0;
13375 }
13376
13377 static int intel_modeset_all_pipes(struct drm_atomic_state *state)
13378 {
13379         struct drm_crtc *crtc;
13380         struct drm_crtc_state *crtc_state;
13381         int ret = 0;
13382
13383         /* add all active pipes to the state */
13384         for_each_crtc(state->dev, crtc) {
13385                 crtc_state = drm_atomic_get_crtc_state(state, crtc);
13386                 if (IS_ERR(crtc_state))
13387                         return PTR_ERR(crtc_state);
13388
13389                 if (!crtc_state->active || needs_modeset(crtc_state))
13390                         continue;
13391
13392                 crtc_state->mode_changed = true;
13393
13394                 ret = drm_atomic_add_affected_connectors(state, crtc);
13395                 if (ret)
13396                         break;
13397
13398                 ret = drm_atomic_add_affected_planes(state, crtc);
13399                 if (ret)
13400                         break;
13401         }
13402
13403         return ret;
13404 }
13405
13406 static int intel_modeset_checks(struct drm_atomic_state *state)
13407 {
13408         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
13409         struct drm_i915_private *dev_priv = to_i915(state->dev);
13410         struct drm_crtc *crtc;
13411         struct drm_crtc_state *crtc_state;
13412         int ret = 0, i;
13413
13414         if (!check_digital_port_conflicts(state)) {
13415                 DRM_DEBUG_KMS("rejecting conflicting digital port configuration\n");
13416                 return -EINVAL;
13417         }
13418
13419         intel_state->modeset = true;
13420         intel_state->active_crtcs = dev_priv->active_crtcs;
13421
13422         for_each_crtc_in_state(state, crtc, crtc_state, i) {
13423                 if (crtc_state->active)
13424                         intel_state->active_crtcs |= 1 << i;
13425                 else
13426                         intel_state->active_crtcs &= ~(1 << i);
13427
13428                 if (crtc_state->active != crtc->state->active)
13429                         intel_state->active_pipe_changes |= drm_crtc_mask(crtc);
13430         }
13431
13432         /*
13433          * See if the config requires any additional preparation, e.g.
13434          * to adjust global state with pipes off.  We need to do this
13435          * here so we can get the modeset_pipe updated config for the new
13436          * mode set on this crtc.  For other crtcs we need to use the
13437          * adjusted_mode bits in the crtc directly.
13438          */
13439         if (dev_priv->display.modeset_calc_cdclk) {
13440                 if (!intel_state->cdclk_pll_vco)
13441                         intel_state->cdclk_pll_vco = dev_priv->cdclk_pll.vco;
13442                 if (!intel_state->cdclk_pll_vco)
13443                         intel_state->cdclk_pll_vco = dev_priv->skl_preferred_vco_freq;
13444
13445                 ret = dev_priv->display.modeset_calc_cdclk(state);
13446                 if (ret < 0)
13447                         return ret;
13448
13449                 if (intel_state->dev_cdclk != dev_priv->cdclk_freq ||
13450                     intel_state->cdclk_pll_vco != dev_priv->cdclk_pll.vco)
13451                         ret = intel_modeset_all_pipes(state);
13452
13453                 if (ret < 0)
13454                         return ret;
13455
13456                 DRM_DEBUG_KMS("New cdclk calculated to be atomic %u, actual %u\n",
13457                               intel_state->cdclk, intel_state->dev_cdclk);
13458         } else
13459                 to_intel_atomic_state(state)->cdclk = dev_priv->atomic_cdclk_freq;
13460
13461         intel_modeset_clear_plls(state);
13462
13463         if (IS_HASWELL(dev_priv))
13464                 return haswell_mode_set_planes_workaround(state);
13465
13466         return 0;
13467 }
13468
13469 /*
13470  * Handle calculation of various watermark data at the end of the atomic check
13471  * phase.  The code here should be run after the per-crtc and per-plane 'check'
13472  * handlers to ensure that all derived state has been updated.
13473  */
13474 static int calc_watermark_data(struct drm_atomic_state *state)
13475 {
13476         struct drm_device *dev = state->dev;
13477         struct drm_i915_private *dev_priv = to_i915(dev);
13478
13479         /* Is there platform-specific watermark information to calculate? */
13480         if (dev_priv->display.compute_global_watermarks)
13481                 return dev_priv->display.compute_global_watermarks(state);
13482
13483         return 0;
13484 }
13485
13486 /**
13487  * intel_atomic_check - validate state object
13488  * @dev: drm device
13489  * @state: state to validate
13490  */
13491 static int intel_atomic_check(struct drm_device *dev,
13492                               struct drm_atomic_state *state)
13493 {
13494         struct drm_i915_private *dev_priv = to_i915(dev);
13495         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
13496         struct drm_crtc *crtc;
13497         struct drm_crtc_state *crtc_state;
13498         int ret, i;
13499         bool any_ms = false;
13500
13501         ret = drm_atomic_helper_check_modeset(dev, state);
13502         if (ret)
13503                 return ret;
13504
13505         for_each_crtc_in_state(state, crtc, crtc_state, i) {
13506                 struct intel_crtc_state *pipe_config =
13507                         to_intel_crtc_state(crtc_state);
13508
13509                 /* Catch I915_MODE_FLAG_INHERITED */
13510                 if (crtc_state->mode.private_flags != crtc->state->mode.private_flags)
13511                         crtc_state->mode_changed = true;
13512
13513                 if (!needs_modeset(crtc_state))
13514                         continue;
13515
13516                 if (!crtc_state->enable) {
13517                         any_ms = true;
13518                         continue;
13519                 }
13520
13521                 /* FIXME: For only active_changed we shouldn't need to do any
13522                  * state recomputation at all. */
13523
13524                 ret = drm_atomic_add_affected_connectors(state, crtc);
13525                 if (ret)
13526                         return ret;
13527
13528                 ret = intel_modeset_pipe_config(crtc, pipe_config);
13529                 if (ret) {
13530                         intel_dump_pipe_config(to_intel_crtc(crtc),
13531                                                pipe_config, "[failed]");
13532                         return ret;
13533                 }
13534
13535                 if (i915.fastboot &&
13536                     intel_pipe_config_compare(dev,
13537                                         to_intel_crtc_state(crtc->state),
13538                                         pipe_config, true)) {
13539                         crtc_state->mode_changed = false;
13540                         to_intel_crtc_state(crtc_state)->update_pipe = true;
13541                 }
13542
13543                 if (needs_modeset(crtc_state))
13544                         any_ms = true;
13545
13546                 ret = drm_atomic_add_affected_planes(state, crtc);
13547                 if (ret)
13548                         return ret;
13549
13550                 intel_dump_pipe_config(to_intel_crtc(crtc), pipe_config,
13551                                        needs_modeset(crtc_state) ?
13552                                        "[modeset]" : "[fastset]");
13553         }
13554
13555         if (any_ms) {
13556                 ret = intel_modeset_checks(state);
13557
13558                 if (ret)
13559                         return ret;
13560         } else
13561                 intel_state->cdclk = dev_priv->cdclk_freq;
13562
13563         ret = drm_atomic_helper_check_planes(dev, state);
13564         if (ret)
13565                 return ret;
13566
13567         intel_fbc_choose_crtc(dev_priv, state);
13568         return calc_watermark_data(state);
13569 }
13570
13571 static int intel_atomic_prepare_commit(struct drm_device *dev,
13572                                        struct drm_atomic_state *state,
13573                                        bool nonblock)
13574 {
13575         struct drm_i915_private *dev_priv = to_i915(dev);
13576         struct drm_plane_state *plane_state;
13577         struct drm_crtc_state *crtc_state;
13578         struct drm_plane *plane;
13579         struct drm_crtc *crtc;
13580         int i, ret;
13581
13582         for_each_crtc_in_state(state, crtc, crtc_state, i) {
13583                 if (state->legacy_cursor_update)
13584                         continue;
13585
13586                 ret = intel_crtc_wait_for_pending_flips(crtc);
13587                 if (ret)
13588                         return ret;
13589
13590                 if (atomic_read(&to_intel_crtc(crtc)->unpin_work_count) >= 2)
13591                         flush_workqueue(dev_priv->wq);
13592         }
13593
13594         ret = mutex_lock_interruptible(&dev->struct_mutex);
13595         if (ret)
13596                 return ret;
13597
13598         ret = drm_atomic_helper_prepare_planes(dev, state);
13599         mutex_unlock(&dev->struct_mutex);
13600
13601         if (!ret && !nonblock) {
13602                 for_each_plane_in_state(state, plane, plane_state, i) {
13603                         struct intel_plane_state *intel_plane_state =
13604                                 to_intel_plane_state(plane_state);
13605
13606                         if (!intel_plane_state->wait_req)
13607                                 continue;
13608
13609                         ret = i915_wait_request(intel_plane_state->wait_req,
13610                                                 true, NULL, NULL);
13611                         if (ret) {
13612                                 /* Any hang should be swallowed by the wait */
13613                                 WARN_ON(ret == -EIO);
13614                                 mutex_lock(&dev->struct_mutex);
13615                                 drm_atomic_helper_cleanup_planes(dev, state);
13616                                 mutex_unlock(&dev->struct_mutex);
13617                                 break;
13618                         }
13619                 }
13620         }
13621
13622         return ret;
13623 }
13624
13625 u32 intel_crtc_get_vblank_counter(struct intel_crtc *crtc)
13626 {
13627         struct drm_device *dev = crtc->base.dev;
13628
13629         if (!dev->max_vblank_count)
13630                 return drm_accurate_vblank_count(&crtc->base);
13631
13632         return dev->driver->get_vblank_counter(dev, crtc->pipe);
13633 }
13634
13635 static void intel_atomic_wait_for_vblanks(struct drm_device *dev,
13636                                           struct drm_i915_private *dev_priv,
13637                                           unsigned crtc_mask)
13638 {
13639         unsigned last_vblank_count[I915_MAX_PIPES];
13640         enum pipe pipe;
13641         int ret;
13642
13643         if (!crtc_mask)
13644                 return;
13645
13646         for_each_pipe(dev_priv, pipe) {
13647                 struct drm_crtc *crtc = dev_priv->pipe_to_crtc_mapping[pipe];
13648
13649                 if (!((1 << pipe) & crtc_mask))
13650                         continue;
13651
13652                 ret = drm_crtc_vblank_get(crtc);
13653                 if (WARN_ON(ret != 0)) {
13654                         crtc_mask &= ~(1 << pipe);
13655                         continue;
13656                 }
13657
13658                 last_vblank_count[pipe] = drm_crtc_vblank_count(crtc);
13659         }
13660
13661         for_each_pipe(dev_priv, pipe) {
13662                 struct drm_crtc *crtc = dev_priv->pipe_to_crtc_mapping[pipe];
13663                 long lret;
13664
13665                 if (!((1 << pipe) & crtc_mask))
13666                         continue;
13667
13668                 lret = wait_event_timeout(dev->vblank[pipe].queue,
13669                                 last_vblank_count[pipe] !=
13670                                         drm_crtc_vblank_count(crtc),
13671                                 msecs_to_jiffies(50));
13672
13673                 WARN(!lret, "pipe %c vblank wait timed out\n", pipe_name(pipe));
13674
13675                 drm_crtc_vblank_put(crtc);
13676         }
13677 }
13678
13679 static bool needs_vblank_wait(struct intel_crtc_state *crtc_state)
13680 {
13681         /* fb updated, need to unpin old fb */
13682         if (crtc_state->fb_changed)
13683                 return true;
13684
13685         /* wm changes, need vblank before final wm's */
13686         if (crtc_state->update_wm_post)
13687                 return true;
13688
13689         /*
13690          * cxsr is re-enabled after vblank.
13691          * This is already handled by crtc_state->update_wm_post,
13692          * but added for clarity.
13693          */
13694         if (crtc_state->disable_cxsr)
13695                 return true;
13696
13697         return false;
13698 }
13699
13700 static void intel_atomic_commit_tail(struct drm_atomic_state *state)
13701 {
13702         struct drm_device *dev = state->dev;
13703         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
13704         struct drm_i915_private *dev_priv = to_i915(dev);
13705         struct drm_crtc_state *old_crtc_state;
13706         struct drm_crtc *crtc;
13707         struct intel_crtc_state *intel_cstate;
13708         struct drm_plane *plane;
13709         struct drm_plane_state *plane_state;
13710         bool hw_check = intel_state->modeset;
13711         unsigned long put_domains[I915_MAX_PIPES] = {};
13712         unsigned crtc_vblank_mask = 0;
13713         int i, ret;
13714
13715         for_each_plane_in_state(state, plane, plane_state, i) {
13716                 struct intel_plane_state *intel_plane_state =
13717                         to_intel_plane_state(plane_state);
13718
13719                 if (!intel_plane_state->wait_req)
13720                         continue;
13721
13722                 ret = i915_wait_request(intel_plane_state->wait_req,
13723                                         true, NULL, NULL);
13724                 /* EIO should be eaten, and we can't get interrupted in the
13725                  * worker, and blocking commits have waited already. */
13726                 WARN_ON(ret);
13727         }
13728
13729         drm_atomic_helper_wait_for_dependencies(state);
13730
13731         if (intel_state->modeset) {
13732                 memcpy(dev_priv->min_pixclk, intel_state->min_pixclk,
13733                        sizeof(intel_state->min_pixclk));
13734                 dev_priv->active_crtcs = intel_state->active_crtcs;
13735                 dev_priv->atomic_cdclk_freq = intel_state->cdclk;
13736
13737                 intel_display_power_get(dev_priv, POWER_DOMAIN_MODESET);
13738         }
13739
13740         for_each_crtc_in_state(state, crtc, old_crtc_state, i) {
13741                 struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
13742
13743                 if (needs_modeset(crtc->state) ||
13744                     to_intel_crtc_state(crtc->state)->update_pipe) {
13745                         hw_check = true;
13746
13747                         put_domains[to_intel_crtc(crtc)->pipe] =
13748                                 modeset_get_crtc_power_domains(crtc,
13749                                         to_intel_crtc_state(crtc->state));
13750                 }
13751
13752                 if (!needs_modeset(crtc->state))
13753                         continue;
13754
13755                 intel_pre_plane_update(to_intel_crtc_state(old_crtc_state));
13756
13757                 if (old_crtc_state->active) {
13758                         intel_crtc_disable_planes(crtc, old_crtc_state->plane_mask);
13759                         dev_priv->display.crtc_disable(crtc);
13760                         intel_crtc->active = false;
13761                         intel_fbc_disable(intel_crtc);
13762                         intel_disable_shared_dpll(intel_crtc);
13763
13764                         /*
13765                          * Underruns don't always raise
13766                          * interrupts, so check manually.
13767                          */
13768                         intel_check_cpu_fifo_underruns(dev_priv);
13769                         intel_check_pch_fifo_underruns(dev_priv);
13770
13771                         if (!crtc->state->active)
13772                                 intel_update_watermarks(crtc);
13773                 }
13774         }
13775
13776         /* Only after disabling all output pipelines that will be changed can we
13777          * update the the output configuration. */
13778         intel_modeset_update_crtc_state(state);
13779
13780         if (intel_state->modeset) {
13781                 drm_atomic_helper_update_legacy_modeset_state(state->dev, state);
13782
13783                 if (dev_priv->display.modeset_commit_cdclk &&
13784                     (intel_state->dev_cdclk != dev_priv->cdclk_freq ||
13785                      intel_state->cdclk_pll_vco != dev_priv->cdclk_pll.vco))
13786                         dev_priv->display.modeset_commit_cdclk(state);
13787
13788                 intel_modeset_verify_disabled(dev);
13789         }
13790
13791         /* Now enable the clocks, plane, pipe, and connectors that we set up. */
13792         for_each_crtc_in_state(state, crtc, old_crtc_state, i) {
13793                 struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
13794                 bool modeset = needs_modeset(crtc->state);
13795                 struct intel_crtc_state *pipe_config =
13796                         to_intel_crtc_state(crtc->state);
13797
13798                 if (modeset && crtc->state->active) {
13799                         update_scanline_offset(to_intel_crtc(crtc));
13800                         dev_priv->display.crtc_enable(crtc);
13801                 }
13802
13803                 /* Complete events for now disable pipes here. */
13804                 if (modeset && !crtc->state->active && crtc->state->event) {
13805                         spin_lock_irq(&dev->event_lock);
13806                         drm_crtc_send_vblank_event(crtc, crtc->state->event);
13807                         spin_unlock_irq(&dev->event_lock);
13808
13809                         crtc->state->event = NULL;
13810                 }
13811
13812                 if (!modeset)
13813                         intel_pre_plane_update(to_intel_crtc_state(old_crtc_state));
13814
13815                 if (crtc->state->active &&
13816                     drm_atomic_get_existing_plane_state(state, crtc->primary))
13817                         intel_fbc_enable(intel_crtc, pipe_config, to_intel_plane_state(crtc->primary->state));
13818
13819                 if (crtc->state->active)
13820                         drm_atomic_helper_commit_planes_on_crtc(old_crtc_state);
13821
13822                 if (pipe_config->base.active && needs_vblank_wait(pipe_config))
13823                         crtc_vblank_mask |= 1 << i;
13824         }
13825
13826         /* FIXME: We should call drm_atomic_helper_commit_hw_done() here
13827          * already, but still need the state for the delayed optimization. To
13828          * fix this:
13829          * - wrap the optimization/post_plane_update stuff into a per-crtc work.
13830          * - schedule that vblank worker _before_ calling hw_done
13831          * - at the start of commit_tail, cancel it _synchrously
13832          * - switch over to the vblank wait helper in the core after that since
13833          *   we don't need out special handling any more.
13834          */
13835         if (!state->legacy_cursor_update)
13836                 intel_atomic_wait_for_vblanks(dev, dev_priv, crtc_vblank_mask);
13837
13838         /*
13839          * Now that the vblank has passed, we can go ahead and program the
13840          * optimal watermarks on platforms that need two-step watermark
13841          * programming.
13842          *
13843          * TODO: Move this (and other cleanup) to an async worker eventually.
13844          */
13845         for_each_crtc_in_state(state, crtc, old_crtc_state, i) {
13846                 intel_cstate = to_intel_crtc_state(crtc->state);
13847
13848                 if (dev_priv->display.optimize_watermarks)
13849                         dev_priv->display.optimize_watermarks(intel_cstate);
13850         }
13851
13852         for_each_crtc_in_state(state, crtc, old_crtc_state, i) {
13853                 intel_post_plane_update(to_intel_crtc_state(old_crtc_state));
13854
13855                 if (put_domains[i])
13856                         modeset_put_power_domains(dev_priv, put_domains[i]);
13857
13858                 intel_modeset_verify_crtc(crtc, old_crtc_state, crtc->state);
13859         }
13860
13861         drm_atomic_helper_commit_hw_done(state);
13862
13863         if (intel_state->modeset)
13864                 intel_display_power_put(dev_priv, POWER_DOMAIN_MODESET);
13865
13866         mutex_lock(&dev->struct_mutex);
13867         drm_atomic_helper_cleanup_planes(dev, state);
13868         mutex_unlock(&dev->struct_mutex);
13869
13870         drm_atomic_helper_commit_cleanup_done(state);
13871
13872         drm_atomic_state_free(state);
13873
13874         /* As one of the primary mmio accessors, KMS has a high likelihood
13875          * of triggering bugs in unclaimed access. After we finish
13876          * modesetting, see if an error has been flagged, and if so
13877          * enable debugging for the next modeset - and hope we catch
13878          * the culprit.
13879          *
13880          * XXX note that we assume display power is on at this point.
13881          * This might hold true now but we need to add pm helper to check
13882          * unclaimed only when the hardware is on, as atomic commits
13883          * can happen also when the device is completely off.
13884          */
13885         intel_uncore_arm_unclaimed_mmio_detection(dev_priv);
13886 }
13887
13888 static void intel_atomic_commit_work(struct work_struct *work)
13889 {
13890         struct drm_atomic_state *state = container_of(work,
13891                                                       struct drm_atomic_state,
13892                                                       commit_work);
13893         intel_atomic_commit_tail(state);
13894 }
13895
13896 static void intel_atomic_track_fbs(struct drm_atomic_state *state)
13897 {
13898         struct drm_plane_state *old_plane_state;
13899         struct drm_plane *plane;
13900         int i;
13901
13902         for_each_plane_in_state(state, plane, old_plane_state, i)
13903                 i915_gem_track_fb(intel_fb_obj(old_plane_state->fb),
13904                                   intel_fb_obj(plane->state->fb),
13905                                   to_intel_plane(plane)->frontbuffer_bit);
13906 }
13907
13908 /**
13909  * intel_atomic_commit - commit validated state object
13910  * @dev: DRM device
13911  * @state: the top-level driver state object
13912  * @nonblock: nonblocking commit
13913  *
13914  * This function commits a top-level state object that has been validated
13915  * with drm_atomic_helper_check().
13916  *
13917  * FIXME:  Atomic modeset support for i915 is not yet complete.  At the moment
13918  * nonblocking commits are only safe for pure plane updates. Everything else
13919  * should work though.
13920  *
13921  * RETURNS
13922  * Zero for success or -errno.
13923  */
13924 static int intel_atomic_commit(struct drm_device *dev,
13925                                struct drm_atomic_state *state,
13926                                bool nonblock)
13927 {
13928         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
13929         struct drm_i915_private *dev_priv = to_i915(dev);
13930         int ret = 0;
13931
13932         if (intel_state->modeset && nonblock) {
13933                 DRM_DEBUG_KMS("nonblocking commit for modeset not yet implemented.\n");
13934                 return -EINVAL;
13935         }
13936
13937         ret = drm_atomic_helper_setup_commit(state, nonblock);
13938         if (ret)
13939                 return ret;
13940
13941         INIT_WORK(&state->commit_work, intel_atomic_commit_work);
13942
13943         ret = intel_atomic_prepare_commit(dev, state, nonblock);
13944         if (ret) {
13945                 DRM_DEBUG_ATOMIC("Preparing state failed with %i\n", ret);
13946                 return ret;
13947         }
13948
13949         drm_atomic_helper_swap_state(state, true);
13950         dev_priv->wm.distrust_bios_wm = false;
13951         dev_priv->wm.skl_results = intel_state->wm_results;
13952         intel_shared_dpll_commit(state);
13953         intel_atomic_track_fbs(state);
13954
13955         if (nonblock)
13956                 queue_work(system_unbound_wq, &state->commit_work);
13957         else
13958                 intel_atomic_commit_tail(state);
13959
13960         return 0;
13961 }
13962
13963 void intel_crtc_restore_mode(struct drm_crtc *crtc)
13964 {
13965         struct drm_device *dev = crtc->dev;
13966         struct drm_atomic_state *state;
13967         struct drm_crtc_state *crtc_state;
13968         int ret;
13969
13970         state = drm_atomic_state_alloc(dev);
13971         if (!state) {
13972                 DRM_DEBUG_KMS("[CRTC:%d:%s] crtc restore failed, out of memory",
13973                               crtc->base.id, crtc->name);
13974                 return;
13975         }
13976
13977         state->acquire_ctx = drm_modeset_legacy_acquire_ctx(crtc);
13978
13979 retry:
13980         crtc_state = drm_atomic_get_crtc_state(state, crtc);
13981         ret = PTR_ERR_OR_ZERO(crtc_state);
13982         if (!ret) {
13983                 if (!crtc_state->active)
13984                         goto out;
13985
13986                 crtc_state->mode_changed = true;
13987                 ret = drm_atomic_commit(state);
13988         }
13989
13990         if (ret == -EDEADLK) {
13991                 drm_atomic_state_clear(state);
13992                 drm_modeset_backoff(state->acquire_ctx);
13993                 goto retry;
13994         }
13995
13996         if (ret)
13997 out:
13998                 drm_atomic_state_free(state);
13999 }
14000
14001 #undef for_each_intel_crtc_masked
14002
14003 /*
14004  * FIXME: Remove this once i915 is fully DRIVER_ATOMIC by calling
14005  *        drm_atomic_helper_legacy_gamma_set() directly.
14006  */
14007 static int intel_atomic_legacy_gamma_set(struct drm_crtc *crtc,
14008                                          u16 *red, u16 *green, u16 *blue,
14009                                          uint32_t size)
14010 {
14011         struct drm_device *dev = crtc->dev;
14012         struct drm_mode_config *config = &dev->mode_config;
14013         struct drm_crtc_state *state;
14014         int ret;
14015
14016         ret = drm_atomic_helper_legacy_gamma_set(crtc, red, green, blue, size);
14017         if (ret)
14018                 return ret;
14019
14020         /*
14021          * Make sure we update the legacy properties so this works when
14022          * atomic is not enabled.
14023          */
14024
14025         state = crtc->state;
14026
14027         drm_object_property_set_value(&crtc->base,
14028                                       config->degamma_lut_property,
14029                                       (state->degamma_lut) ?
14030                                       state->degamma_lut->base.id : 0);
14031
14032         drm_object_property_set_value(&crtc->base,
14033                                       config->ctm_property,
14034                                       (state->ctm) ?
14035                                       state->ctm->base.id : 0);
14036
14037         drm_object_property_set_value(&crtc->base,
14038                                       config->gamma_lut_property,
14039                                       (state->gamma_lut) ?
14040                                       state->gamma_lut->base.id : 0);
14041
14042         return 0;
14043 }
14044
14045 static const struct drm_crtc_funcs intel_crtc_funcs = {
14046         .gamma_set = intel_atomic_legacy_gamma_set,
14047         .set_config = drm_atomic_helper_set_config,
14048         .set_property = drm_atomic_helper_crtc_set_property,
14049         .destroy = intel_crtc_destroy,
14050         .page_flip = intel_crtc_page_flip,
14051         .atomic_duplicate_state = intel_crtc_duplicate_state,
14052         .atomic_destroy_state = intel_crtc_destroy_state,
14053 };
14054
14055 /**
14056  * intel_prepare_plane_fb - Prepare fb for usage on plane
14057  * @plane: drm plane to prepare for
14058  * @fb: framebuffer to prepare for presentation
14059  *
14060  * Prepares a framebuffer for usage on a display plane.  Generally this
14061  * involves pinning the underlying object and updating the frontbuffer tracking
14062  * bits.  Some older platforms need special physical address handling for
14063  * cursor planes.
14064  *
14065  * Must be called with struct_mutex held.
14066  *
14067  * Returns 0 on success, negative error code on failure.
14068  */
14069 int
14070 intel_prepare_plane_fb(struct drm_plane *plane,
14071                        const struct drm_plane_state *new_state)
14072 {
14073         struct drm_device *dev = plane->dev;
14074         struct drm_framebuffer *fb = new_state->fb;
14075         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
14076         struct drm_i915_gem_object *old_obj = intel_fb_obj(plane->state->fb);
14077         struct reservation_object *resv;
14078         int ret = 0;
14079
14080         if (!obj && !old_obj)
14081                 return 0;
14082
14083         if (old_obj) {
14084                 struct drm_crtc_state *crtc_state =
14085                         drm_atomic_get_existing_crtc_state(new_state->state, plane->state->crtc);
14086
14087                 /* Big Hammer, we also need to ensure that any pending
14088                  * MI_WAIT_FOR_EVENT inside a user batch buffer on the
14089                  * current scanout is retired before unpinning the old
14090                  * framebuffer. Note that we rely on userspace rendering
14091                  * into the buffer attached to the pipe they are waiting
14092                  * on. If not, userspace generates a GPU hang with IPEHR
14093                  * point to the MI_WAIT_FOR_EVENT.
14094                  *
14095                  * This should only fail upon a hung GPU, in which case we
14096                  * can safely continue.
14097                  */
14098                 if (needs_modeset(crtc_state))
14099                         ret = i915_gem_object_wait_rendering(old_obj, true);
14100                 if (ret) {
14101                         /* GPU hangs should have been swallowed by the wait */
14102                         WARN_ON(ret == -EIO);
14103                         return ret;
14104                 }
14105         }
14106
14107         if (!obj)
14108                 return 0;
14109
14110         /* For framebuffer backed by dmabuf, wait for fence */
14111         resv = i915_gem_object_get_dmabuf_resv(obj);
14112         if (resv) {
14113                 long lret;
14114
14115                 lret = reservation_object_wait_timeout_rcu(resv, false, true,
14116                                                            MAX_SCHEDULE_TIMEOUT);
14117                 if (lret == -ERESTARTSYS)
14118                         return lret;
14119
14120                 WARN(lret < 0, "waiting returns %li\n", lret);
14121         }
14122
14123         if (plane->type == DRM_PLANE_TYPE_CURSOR &&
14124             INTEL_INFO(dev)->cursor_needs_physical) {
14125                 int align = IS_I830(dev) ? 16 * 1024 : 256;
14126                 ret = i915_gem_object_attach_phys(obj, align);
14127                 if (ret)
14128                         DRM_DEBUG_KMS("failed to attach phys object\n");
14129         } else {
14130                 ret = intel_pin_and_fence_fb_obj(fb, new_state->rotation);
14131         }
14132
14133         if (ret == 0) {
14134                 to_intel_plane_state(new_state)->wait_req =
14135                         i915_gem_active_get(&obj->last_write,
14136                                             &obj->base.dev->struct_mutex);
14137         }
14138
14139         return ret;
14140 }
14141
14142 /**
14143  * intel_cleanup_plane_fb - Cleans up an fb after plane use
14144  * @plane: drm plane to clean up for
14145  * @fb: old framebuffer that was on plane
14146  *
14147  * Cleans up a framebuffer that has just been removed from a plane.
14148  *
14149  * Must be called with struct_mutex held.
14150  */
14151 void
14152 intel_cleanup_plane_fb(struct drm_plane *plane,
14153                        const struct drm_plane_state *old_state)
14154 {
14155         struct drm_device *dev = plane->dev;
14156         struct intel_plane_state *old_intel_state;
14157         struct intel_plane_state *intel_state = to_intel_plane_state(plane->state);
14158         struct drm_i915_gem_object *old_obj = intel_fb_obj(old_state->fb);
14159         struct drm_i915_gem_object *obj = intel_fb_obj(plane->state->fb);
14160
14161         old_intel_state = to_intel_plane_state(old_state);
14162
14163         if (!obj && !old_obj)
14164                 return;
14165
14166         if (old_obj && (plane->type != DRM_PLANE_TYPE_CURSOR ||
14167             !INTEL_INFO(dev)->cursor_needs_physical))
14168                 intel_unpin_fb_obj(old_state->fb, old_state->rotation);
14169
14170         i915_gem_request_assign(&intel_state->wait_req, NULL);
14171         i915_gem_request_assign(&old_intel_state->wait_req, NULL);
14172 }
14173
14174 int
14175 skl_max_scale(struct intel_crtc *intel_crtc, struct intel_crtc_state *crtc_state)
14176 {
14177         int max_scale;
14178         int crtc_clock, cdclk;
14179
14180         if (!intel_crtc || !crtc_state->base.enable)
14181                 return DRM_PLANE_HELPER_NO_SCALING;
14182
14183         crtc_clock = crtc_state->base.adjusted_mode.crtc_clock;
14184         cdclk = to_intel_atomic_state(crtc_state->base.state)->cdclk;
14185
14186         if (WARN_ON_ONCE(!crtc_clock || cdclk < crtc_clock))
14187                 return DRM_PLANE_HELPER_NO_SCALING;
14188
14189         /*
14190          * skl max scale is lower of:
14191          *    close to 3 but not 3, -1 is for that purpose
14192          *            or
14193          *    cdclk/crtc_clock
14194          */
14195         max_scale = min((1 << 16) * 3 - 1, (1 << 8) * ((cdclk << 8) / crtc_clock));
14196
14197         return max_scale;
14198 }
14199
14200 static int
14201 intel_check_primary_plane(struct drm_plane *plane,
14202                           struct intel_crtc_state *crtc_state,
14203                           struct intel_plane_state *state)
14204 {
14205         struct drm_crtc *crtc = state->base.crtc;
14206         struct drm_framebuffer *fb = state->base.fb;
14207         int min_scale = DRM_PLANE_HELPER_NO_SCALING;
14208         int max_scale = DRM_PLANE_HELPER_NO_SCALING;
14209         bool can_position = false;
14210
14211         if (INTEL_INFO(plane->dev)->gen >= 9) {
14212                 /* use scaler when colorkey is not required */
14213                 if (state->ckey.flags == I915_SET_COLORKEY_NONE) {
14214                         min_scale = 1;
14215                         max_scale = skl_max_scale(to_intel_crtc(crtc), crtc_state);
14216                 }
14217                 can_position = true;
14218         }
14219
14220         return drm_plane_helper_check_update(plane, crtc, fb, &state->src,
14221                                              &state->dst, &state->clip,
14222                                              state->base.rotation,
14223                                              min_scale, max_scale,
14224                                              can_position, true,
14225                                              &state->visible);
14226 }
14227
14228 static void intel_begin_crtc_commit(struct drm_crtc *crtc,
14229                                     struct drm_crtc_state *old_crtc_state)
14230 {
14231         struct drm_device *dev = crtc->dev;
14232         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
14233         struct intel_crtc_state *old_intel_state =
14234                 to_intel_crtc_state(old_crtc_state);
14235         bool modeset = needs_modeset(crtc->state);
14236
14237         /* Perform vblank evasion around commit operation */
14238         intel_pipe_update_start(intel_crtc);
14239
14240         if (modeset)
14241                 return;
14242
14243         if (crtc->state->color_mgmt_changed || to_intel_crtc_state(crtc->state)->update_pipe) {
14244                 intel_color_set_csc(crtc->state);
14245                 intel_color_load_luts(crtc->state);
14246         }
14247
14248         if (to_intel_crtc_state(crtc->state)->update_pipe)
14249                 intel_update_pipe_config(intel_crtc, old_intel_state);
14250         else if (INTEL_INFO(dev)->gen >= 9)
14251                 skl_detach_scalers(intel_crtc);
14252 }
14253
14254 static void intel_finish_crtc_commit(struct drm_crtc *crtc,
14255                                      struct drm_crtc_state *old_crtc_state)
14256 {
14257         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
14258
14259         intel_pipe_update_end(intel_crtc, NULL);
14260 }
14261
14262 /**
14263  * intel_plane_destroy - destroy a plane
14264  * @plane: plane to destroy
14265  *
14266  * Common destruction function for all types of planes (primary, cursor,
14267  * sprite).
14268  */
14269 void intel_plane_destroy(struct drm_plane *plane)
14270 {
14271         if (!plane)
14272                 return;
14273
14274         drm_plane_cleanup(plane);
14275         kfree(to_intel_plane(plane));
14276 }
14277
14278 const struct drm_plane_funcs intel_plane_funcs = {
14279         .update_plane = drm_atomic_helper_update_plane,
14280         .disable_plane = drm_atomic_helper_disable_plane,
14281         .destroy = intel_plane_destroy,
14282         .set_property = drm_atomic_helper_plane_set_property,
14283         .atomic_get_property = intel_plane_atomic_get_property,
14284         .atomic_set_property = intel_plane_atomic_set_property,
14285         .atomic_duplicate_state = intel_plane_duplicate_state,
14286         .atomic_destroy_state = intel_plane_destroy_state,
14287
14288 };
14289
14290 static struct drm_plane *intel_primary_plane_create(struct drm_device *dev,
14291                                                     int pipe)
14292 {
14293         struct intel_plane *primary = NULL;
14294         struct intel_plane_state *state = NULL;
14295         const uint32_t *intel_primary_formats;
14296         unsigned int num_formats;
14297         int ret;
14298
14299         primary = kzalloc(sizeof(*primary), GFP_KERNEL);
14300         if (!primary)
14301                 goto fail;
14302
14303         state = intel_create_plane_state(&primary->base);
14304         if (!state)
14305                 goto fail;
14306         primary->base.state = &state->base;
14307
14308         primary->can_scale = false;
14309         primary->max_downscale = 1;
14310         if (INTEL_INFO(dev)->gen >= 9) {
14311                 primary->can_scale = true;
14312                 state->scaler_id = -1;
14313         }
14314         primary->pipe = pipe;
14315         primary->plane = pipe;
14316         primary->frontbuffer_bit = INTEL_FRONTBUFFER_PRIMARY(pipe);
14317         primary->check_plane = intel_check_primary_plane;
14318         if (HAS_FBC(dev) && INTEL_INFO(dev)->gen < 4)
14319                 primary->plane = !pipe;
14320
14321         if (INTEL_INFO(dev)->gen >= 9) {
14322                 intel_primary_formats = skl_primary_formats;
14323                 num_formats = ARRAY_SIZE(skl_primary_formats);
14324
14325                 primary->update_plane = skylake_update_primary_plane;
14326                 primary->disable_plane = skylake_disable_primary_plane;
14327         } else if (HAS_PCH_SPLIT(dev)) {
14328                 intel_primary_formats = i965_primary_formats;
14329                 num_formats = ARRAY_SIZE(i965_primary_formats);
14330
14331                 primary->update_plane = ironlake_update_primary_plane;
14332                 primary->disable_plane = i9xx_disable_primary_plane;
14333         } else if (INTEL_INFO(dev)->gen >= 4) {
14334                 intel_primary_formats = i965_primary_formats;
14335                 num_formats = ARRAY_SIZE(i965_primary_formats);
14336
14337                 primary->update_plane = i9xx_update_primary_plane;
14338                 primary->disable_plane = i9xx_disable_primary_plane;
14339         } else {
14340                 intel_primary_formats = i8xx_primary_formats;
14341                 num_formats = ARRAY_SIZE(i8xx_primary_formats);
14342
14343                 primary->update_plane = i9xx_update_primary_plane;
14344                 primary->disable_plane = i9xx_disable_primary_plane;
14345         }
14346
14347         if (INTEL_INFO(dev)->gen >= 9)
14348                 ret = drm_universal_plane_init(dev, &primary->base, 0,
14349                                                &intel_plane_funcs,
14350                                                intel_primary_formats, num_formats,
14351                                                DRM_PLANE_TYPE_PRIMARY,
14352                                                "plane 1%c", pipe_name(pipe));
14353         else if (INTEL_INFO(dev)->gen >= 5 || IS_G4X(dev))
14354                 ret = drm_universal_plane_init(dev, &primary->base, 0,
14355                                                &intel_plane_funcs,
14356                                                intel_primary_formats, num_formats,
14357                                                DRM_PLANE_TYPE_PRIMARY,
14358                                                "primary %c", pipe_name(pipe));
14359         else
14360                 ret = drm_universal_plane_init(dev, &primary->base, 0,
14361                                                &intel_plane_funcs,
14362                                                intel_primary_formats, num_formats,
14363                                                DRM_PLANE_TYPE_PRIMARY,
14364                                                "plane %c", plane_name(primary->plane));
14365         if (ret)
14366                 goto fail;
14367
14368         if (INTEL_INFO(dev)->gen >= 4)
14369                 intel_create_rotation_property(dev, primary);
14370
14371         drm_plane_helper_add(&primary->base, &intel_plane_helper_funcs);
14372
14373         return &primary->base;
14374
14375 fail:
14376         kfree(state);
14377         kfree(primary);
14378
14379         return NULL;
14380 }
14381
14382 void intel_create_rotation_property(struct drm_device *dev, struct intel_plane *plane)
14383 {
14384         if (!dev->mode_config.rotation_property) {
14385                 unsigned long flags = BIT(DRM_ROTATE_0) |
14386                         BIT(DRM_ROTATE_180);
14387
14388                 if (INTEL_INFO(dev)->gen >= 9)
14389                         flags |= BIT(DRM_ROTATE_90) | BIT(DRM_ROTATE_270);
14390
14391                 dev->mode_config.rotation_property =
14392                         drm_mode_create_rotation_property(dev, flags);
14393         }
14394         if (dev->mode_config.rotation_property)
14395                 drm_object_attach_property(&plane->base.base,
14396                                 dev->mode_config.rotation_property,
14397                                 plane->base.state->rotation);
14398 }
14399
14400 static int
14401 intel_check_cursor_plane(struct drm_plane *plane,
14402                          struct intel_crtc_state *crtc_state,
14403                          struct intel_plane_state *state)
14404 {
14405         struct drm_crtc *crtc = crtc_state->base.crtc;
14406         struct drm_framebuffer *fb = state->base.fb;
14407         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
14408         enum pipe pipe = to_intel_plane(plane)->pipe;
14409         unsigned stride;
14410         int ret;
14411
14412         ret = drm_plane_helper_check_update(plane, crtc, fb, &state->src,
14413                                             &state->dst, &state->clip,
14414                                             state->base.rotation,
14415                                             DRM_PLANE_HELPER_NO_SCALING,
14416                                             DRM_PLANE_HELPER_NO_SCALING,
14417                                             true, true, &state->visible);
14418         if (ret)
14419                 return ret;
14420
14421         /* if we want to turn off the cursor ignore width and height */
14422         if (!obj)
14423                 return 0;
14424
14425         /* Check for which cursor types we support */
14426         if (!cursor_size_ok(plane->dev, state->base.crtc_w, state->base.crtc_h)) {
14427                 DRM_DEBUG("Cursor dimension %dx%d not supported\n",
14428                           state->base.crtc_w, state->base.crtc_h);
14429                 return -EINVAL;
14430         }
14431
14432         stride = roundup_pow_of_two(state->base.crtc_w) * 4;
14433         if (obj->base.size < stride * state->base.crtc_h) {
14434                 DRM_DEBUG_KMS("buffer is too small\n");
14435                 return -ENOMEM;
14436         }
14437
14438         if (fb->modifier[0] != DRM_FORMAT_MOD_NONE) {
14439                 DRM_DEBUG_KMS("cursor cannot be tiled\n");
14440                 return -EINVAL;
14441         }
14442
14443         /*
14444          * There's something wrong with the cursor on CHV pipe C.
14445          * If it straddles the left edge of the screen then
14446          * moving it away from the edge or disabling it often
14447          * results in a pipe underrun, and often that can lead to
14448          * dead pipe (constant underrun reported, and it scans
14449          * out just a solid color). To recover from that, the
14450          * display power well must be turned off and on again.
14451          * Refuse the put the cursor into that compromised position.
14452          */
14453         if (IS_CHERRYVIEW(plane->dev) && pipe == PIPE_C &&
14454             state->visible && state->base.crtc_x < 0) {
14455                 DRM_DEBUG_KMS("CHV cursor C not allowed to straddle the left screen edge\n");
14456                 return -EINVAL;
14457         }
14458
14459         return 0;
14460 }
14461
14462 static void
14463 intel_disable_cursor_plane(struct drm_plane *plane,
14464                            struct drm_crtc *crtc)
14465 {
14466         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
14467
14468         intel_crtc->cursor_addr = 0;
14469         intel_crtc_update_cursor(crtc, NULL);
14470 }
14471
14472 static void
14473 intel_update_cursor_plane(struct drm_plane *plane,
14474                           const struct intel_crtc_state *crtc_state,
14475                           const struct intel_plane_state *state)
14476 {
14477         struct drm_crtc *crtc = crtc_state->base.crtc;
14478         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
14479         struct drm_device *dev = plane->dev;
14480         struct drm_i915_gem_object *obj = intel_fb_obj(state->base.fb);
14481         uint32_t addr;
14482
14483         if (!obj)
14484                 addr = 0;
14485         else if (!INTEL_INFO(dev)->cursor_needs_physical)
14486                 addr = i915_gem_obj_ggtt_offset(obj);
14487         else
14488                 addr = obj->phys_handle->busaddr;
14489
14490         intel_crtc->cursor_addr = addr;
14491         intel_crtc_update_cursor(crtc, state);
14492 }
14493
14494 static struct drm_plane *intel_cursor_plane_create(struct drm_device *dev,
14495                                                    int pipe)
14496 {
14497         struct intel_plane *cursor = NULL;
14498         struct intel_plane_state *state = NULL;
14499         int ret;
14500
14501         cursor = kzalloc(sizeof(*cursor), GFP_KERNEL);
14502         if (!cursor)
14503                 goto fail;
14504
14505         state = intel_create_plane_state(&cursor->base);
14506         if (!state)
14507                 goto fail;
14508         cursor->base.state = &state->base;
14509
14510         cursor->can_scale = false;
14511         cursor->max_downscale = 1;
14512         cursor->pipe = pipe;
14513         cursor->plane = pipe;
14514         cursor->frontbuffer_bit = INTEL_FRONTBUFFER_CURSOR(pipe);
14515         cursor->check_plane = intel_check_cursor_plane;
14516         cursor->update_plane = intel_update_cursor_plane;
14517         cursor->disable_plane = intel_disable_cursor_plane;
14518
14519         ret = drm_universal_plane_init(dev, &cursor->base, 0,
14520                                        &intel_plane_funcs,
14521                                        intel_cursor_formats,
14522                                        ARRAY_SIZE(intel_cursor_formats),
14523                                        DRM_PLANE_TYPE_CURSOR,
14524                                        "cursor %c", pipe_name(pipe));
14525         if (ret)
14526                 goto fail;
14527
14528         if (INTEL_INFO(dev)->gen >= 4) {
14529                 if (!dev->mode_config.rotation_property)
14530                         dev->mode_config.rotation_property =
14531                                 drm_mode_create_rotation_property(dev,
14532                                                         BIT(DRM_ROTATE_0) |
14533                                                         BIT(DRM_ROTATE_180));
14534                 if (dev->mode_config.rotation_property)
14535                         drm_object_attach_property(&cursor->base.base,
14536                                 dev->mode_config.rotation_property,
14537                                 state->base.rotation);
14538         }
14539
14540         if (INTEL_INFO(dev)->gen >=9)
14541                 state->scaler_id = -1;
14542
14543         drm_plane_helper_add(&cursor->base, &intel_plane_helper_funcs);
14544
14545         return &cursor->base;
14546
14547 fail:
14548         kfree(state);
14549         kfree(cursor);
14550
14551         return NULL;
14552 }
14553
14554 static void skl_init_scalers(struct drm_device *dev, struct intel_crtc *intel_crtc,
14555         struct intel_crtc_state *crtc_state)
14556 {
14557         int i;
14558         struct intel_scaler *intel_scaler;
14559         struct intel_crtc_scaler_state *scaler_state = &crtc_state->scaler_state;
14560
14561         for (i = 0; i < intel_crtc->num_scalers; i++) {
14562                 intel_scaler = &scaler_state->scalers[i];
14563                 intel_scaler->in_use = 0;
14564                 intel_scaler->mode = PS_SCALER_MODE_DYN;
14565         }
14566
14567         scaler_state->scaler_id = -1;
14568 }
14569
14570 static void intel_crtc_init(struct drm_device *dev, int pipe)
14571 {
14572         struct drm_i915_private *dev_priv = to_i915(dev);
14573         struct intel_crtc *intel_crtc;
14574         struct intel_crtc_state *crtc_state = NULL;
14575         struct drm_plane *primary = NULL;
14576         struct drm_plane *cursor = NULL;
14577         int ret;
14578
14579         intel_crtc = kzalloc(sizeof(*intel_crtc), GFP_KERNEL);
14580         if (intel_crtc == NULL)
14581                 return;
14582
14583         crtc_state = kzalloc(sizeof(*crtc_state), GFP_KERNEL);
14584         if (!crtc_state)
14585                 goto fail;
14586         intel_crtc->config = crtc_state;
14587         intel_crtc->base.state = &crtc_state->base;
14588         crtc_state->base.crtc = &intel_crtc->base;
14589
14590         /* initialize shared scalers */
14591         if (INTEL_INFO(dev)->gen >= 9) {
14592                 if (pipe == PIPE_C)
14593                         intel_crtc->num_scalers = 1;
14594                 else
14595                         intel_crtc->num_scalers = SKL_NUM_SCALERS;
14596
14597                 skl_init_scalers(dev, intel_crtc, crtc_state);
14598         }
14599
14600         primary = intel_primary_plane_create(dev, pipe);
14601         if (!primary)
14602                 goto fail;
14603
14604         cursor = intel_cursor_plane_create(dev, pipe);
14605         if (!cursor)
14606                 goto fail;
14607
14608         ret = drm_crtc_init_with_planes(dev, &intel_crtc->base, primary,
14609                                         cursor, &intel_crtc_funcs,
14610                                         "pipe %c", pipe_name(pipe));
14611         if (ret)
14612                 goto fail;
14613
14614         /*
14615          * On gen2/3 only plane A can do fbc, but the panel fitter and lvds port
14616          * is hooked to pipe B. Hence we want plane A feeding pipe B.
14617          */
14618         intel_crtc->pipe = pipe;
14619         intel_crtc->plane = pipe;
14620         if (HAS_FBC(dev) && INTEL_INFO(dev)->gen < 4) {
14621                 DRM_DEBUG_KMS("swapping pipes & planes for FBC\n");
14622                 intel_crtc->plane = !pipe;
14623         }
14624
14625         intel_crtc->cursor_base = ~0;
14626         intel_crtc->cursor_cntl = ~0;
14627         intel_crtc->cursor_size = ~0;
14628
14629         intel_crtc->wm.cxsr_allowed = true;
14630
14631         BUG_ON(pipe >= ARRAY_SIZE(dev_priv->plane_to_crtc_mapping) ||
14632                dev_priv->plane_to_crtc_mapping[intel_crtc->plane] != NULL);
14633         dev_priv->plane_to_crtc_mapping[intel_crtc->plane] = &intel_crtc->base;
14634         dev_priv->pipe_to_crtc_mapping[intel_crtc->pipe] = &intel_crtc->base;
14635
14636         drm_crtc_helper_add(&intel_crtc->base, &intel_helper_funcs);
14637
14638         intel_color_init(&intel_crtc->base);
14639
14640         WARN_ON(drm_crtc_index(&intel_crtc->base) != intel_crtc->pipe);
14641         return;
14642
14643 fail:
14644         intel_plane_destroy(primary);
14645         intel_plane_destroy(cursor);
14646         kfree(crtc_state);
14647         kfree(intel_crtc);
14648 }
14649
14650 enum pipe intel_get_pipe_from_connector(struct intel_connector *connector)
14651 {
14652         struct drm_encoder *encoder = connector->base.encoder;
14653         struct drm_device *dev = connector->base.dev;
14654
14655         WARN_ON(!drm_modeset_is_locked(&dev->mode_config.connection_mutex));
14656
14657         if (!encoder || WARN_ON(!encoder->crtc))
14658                 return INVALID_PIPE;
14659
14660         return to_intel_crtc(encoder->crtc)->pipe;
14661 }
14662
14663 int intel_get_pipe_from_crtc_id(struct drm_device *dev, void *data,
14664                                 struct drm_file *file)
14665 {
14666         struct drm_i915_get_pipe_from_crtc_id *pipe_from_crtc_id = data;
14667         struct drm_crtc *drmmode_crtc;
14668         struct intel_crtc *crtc;
14669
14670         drmmode_crtc = drm_crtc_find(dev, pipe_from_crtc_id->crtc_id);
14671         if (!drmmode_crtc)
14672                 return -ENOENT;
14673
14674         crtc = to_intel_crtc(drmmode_crtc);
14675         pipe_from_crtc_id->pipe = crtc->pipe;
14676
14677         return 0;
14678 }
14679
14680 static int intel_encoder_clones(struct intel_encoder *encoder)
14681 {
14682         struct drm_device *dev = encoder->base.dev;
14683         struct intel_encoder *source_encoder;
14684         int index_mask = 0;
14685         int entry = 0;
14686
14687         for_each_intel_encoder(dev, source_encoder) {
14688                 if (encoders_cloneable(encoder, source_encoder))
14689                         index_mask |= (1 << entry);
14690
14691                 entry++;
14692         }
14693
14694         return index_mask;
14695 }
14696
14697 static bool has_edp_a(struct drm_device *dev)
14698 {
14699         struct drm_i915_private *dev_priv = to_i915(dev);
14700
14701         if (!IS_MOBILE(dev))
14702                 return false;
14703
14704         if ((I915_READ(DP_A) & DP_DETECTED) == 0)
14705                 return false;
14706
14707         if (IS_GEN5(dev) && (I915_READ(FUSE_STRAP) & ILK_eDP_A_DISABLE))
14708                 return false;
14709
14710         return true;
14711 }
14712
14713 static bool intel_crt_present(struct drm_device *dev)
14714 {
14715         struct drm_i915_private *dev_priv = to_i915(dev);
14716
14717         if (INTEL_INFO(dev)->gen >= 9)
14718                 return false;
14719
14720         if (IS_HSW_ULT(dev) || IS_BDW_ULT(dev))
14721                 return false;
14722
14723         if (IS_CHERRYVIEW(dev))
14724                 return false;
14725
14726         if (HAS_PCH_LPT_H(dev) && I915_READ(SFUSE_STRAP) & SFUSE_STRAP_CRT_DISABLED)
14727                 return false;
14728
14729         /* DDI E can't be used if DDI A requires 4 lanes */
14730         if (HAS_DDI(dev) && I915_READ(DDI_BUF_CTL(PORT_A)) & DDI_A_4_LANES)
14731                 return false;
14732
14733         if (!dev_priv->vbt.int_crt_support)
14734                 return false;
14735
14736         return true;
14737 }
14738
14739 static void intel_setup_outputs(struct drm_device *dev)
14740 {
14741         struct drm_i915_private *dev_priv = to_i915(dev);
14742         struct intel_encoder *encoder;
14743         bool dpd_is_edp = false;
14744
14745         /*
14746          * intel_edp_init_connector() depends on this completing first, to
14747          * prevent the registeration of both eDP and LVDS and the incorrect
14748          * sharing of the PPS.
14749          */
14750         intel_lvds_init(dev);
14751
14752         if (intel_crt_present(dev))
14753                 intel_crt_init(dev);
14754
14755         if (IS_BROXTON(dev)) {
14756                 /*
14757                  * FIXME: Broxton doesn't support port detection via the
14758                  * DDI_BUF_CTL_A or SFUSE_STRAP registers, find another way to
14759                  * detect the ports.
14760                  */
14761                 intel_ddi_init(dev, PORT_A);
14762                 intel_ddi_init(dev, PORT_B);
14763                 intel_ddi_init(dev, PORT_C);
14764
14765                 intel_dsi_init(dev);
14766         } else if (HAS_DDI(dev)) {
14767                 int found;
14768
14769                 /*
14770                  * Haswell uses DDI functions to detect digital outputs.
14771                  * On SKL pre-D0 the strap isn't connected, so we assume
14772                  * it's there.
14773                  */
14774                 found = I915_READ(DDI_BUF_CTL(PORT_A)) & DDI_INIT_DISPLAY_DETECTED;
14775                 /* WaIgnoreDDIAStrap: skl */
14776                 if (found || IS_SKYLAKE(dev) || IS_KABYLAKE(dev))
14777                         intel_ddi_init(dev, PORT_A);
14778
14779                 /* DDI B, C and D detection is indicated by the SFUSE_STRAP
14780                  * register */
14781                 found = I915_READ(SFUSE_STRAP);
14782
14783                 if (found & SFUSE_STRAP_DDIB_DETECTED)
14784                         intel_ddi_init(dev, PORT_B);
14785                 if (found & SFUSE_STRAP_DDIC_DETECTED)
14786                         intel_ddi_init(dev, PORT_C);
14787                 if (found & SFUSE_STRAP_DDID_DETECTED)
14788                         intel_ddi_init(dev, PORT_D);
14789                 /*
14790                  * On SKL we don't have a way to detect DDI-E so we rely on VBT.
14791                  */
14792                 if ((IS_SKYLAKE(dev) || IS_KABYLAKE(dev)) &&
14793                     (dev_priv->vbt.ddi_port_info[PORT_E].supports_dp ||
14794                      dev_priv->vbt.ddi_port_info[PORT_E].supports_dvi ||
14795                      dev_priv->vbt.ddi_port_info[PORT_E].supports_hdmi))
14796                         intel_ddi_init(dev, PORT_E);
14797
14798         } else if (HAS_PCH_SPLIT(dev)) {
14799                 int found;
14800                 dpd_is_edp = intel_dp_is_edp(dev, PORT_D);
14801
14802                 if (has_edp_a(dev))
14803                         intel_dp_init(dev, DP_A, PORT_A);
14804
14805                 if (I915_READ(PCH_HDMIB) & SDVO_DETECTED) {
14806                         /* PCH SDVOB multiplex with HDMIB */
14807                         found = intel_sdvo_init(dev, PCH_SDVOB, PORT_B);
14808                         if (!found)
14809                                 intel_hdmi_init(dev, PCH_HDMIB, PORT_B);
14810                         if (!found && (I915_READ(PCH_DP_B) & DP_DETECTED))
14811                                 intel_dp_init(dev, PCH_DP_B, PORT_B);
14812                 }
14813
14814                 if (I915_READ(PCH_HDMIC) & SDVO_DETECTED)
14815                         intel_hdmi_init(dev, PCH_HDMIC, PORT_C);
14816
14817                 if (!dpd_is_edp && I915_READ(PCH_HDMID) & SDVO_DETECTED)
14818                         intel_hdmi_init(dev, PCH_HDMID, PORT_D);
14819
14820                 if (I915_READ(PCH_DP_C) & DP_DETECTED)
14821                         intel_dp_init(dev, PCH_DP_C, PORT_C);
14822
14823                 if (I915_READ(PCH_DP_D) & DP_DETECTED)
14824                         intel_dp_init(dev, PCH_DP_D, PORT_D);
14825         } else if (IS_VALLEYVIEW(dev) || IS_CHERRYVIEW(dev)) {
14826                 bool has_edp, has_port;
14827
14828                 /*
14829                  * The DP_DETECTED bit is the latched state of the DDC
14830                  * SDA pin at boot. However since eDP doesn't require DDC
14831                  * (no way to plug in a DP->HDMI dongle) the DDC pins for
14832                  * eDP ports may have been muxed to an alternate function.
14833                  * Thus we can't rely on the DP_DETECTED bit alone to detect
14834                  * eDP ports. Consult the VBT as well as DP_DETECTED to
14835                  * detect eDP ports.
14836                  *
14837                  * Sadly the straps seem to be missing sometimes even for HDMI
14838                  * ports (eg. on Voyo V3 - CHT x7-Z8700), so check both strap
14839                  * and VBT for the presence of the port. Additionally we can't
14840                  * trust the port type the VBT declares as we've seen at least
14841                  * HDMI ports that the VBT claim are DP or eDP.
14842                  */
14843                 has_edp = intel_dp_is_edp(dev, PORT_B);
14844                 has_port = intel_bios_is_port_present(dev_priv, PORT_B);
14845                 if (I915_READ(VLV_DP_B) & DP_DETECTED || has_port)
14846                         has_edp &= intel_dp_init(dev, VLV_DP_B, PORT_B);
14847                 if ((I915_READ(VLV_HDMIB) & SDVO_DETECTED || has_port) && !has_edp)
14848                         intel_hdmi_init(dev, VLV_HDMIB, PORT_B);
14849
14850                 has_edp = intel_dp_is_edp(dev, PORT_C);
14851                 has_port = intel_bios_is_port_present(dev_priv, PORT_C);
14852                 if (I915_READ(VLV_DP_C) & DP_DETECTED || has_port)
14853                         has_edp &= intel_dp_init(dev, VLV_DP_C, PORT_C);
14854                 if ((I915_READ(VLV_HDMIC) & SDVO_DETECTED || has_port) && !has_edp)
14855                         intel_hdmi_init(dev, VLV_HDMIC, PORT_C);
14856
14857                 if (IS_CHERRYVIEW(dev)) {
14858                         /*
14859                          * eDP not supported on port D,
14860                          * so no need to worry about it
14861                          */
14862                         has_port = intel_bios_is_port_present(dev_priv, PORT_D);
14863                         if (I915_READ(CHV_DP_D) & DP_DETECTED || has_port)
14864                                 intel_dp_init(dev, CHV_DP_D, PORT_D);
14865                         if (I915_READ(CHV_HDMID) & SDVO_DETECTED || has_port)
14866                                 intel_hdmi_init(dev, CHV_HDMID, PORT_D);
14867                 }
14868
14869                 intel_dsi_init(dev);
14870         } else if (!IS_GEN2(dev) && !IS_PINEVIEW(dev)) {
14871                 bool found = false;
14872
14873                 if (I915_READ(GEN3_SDVOB) & SDVO_DETECTED) {
14874                         DRM_DEBUG_KMS("probing SDVOB\n");
14875                         found = intel_sdvo_init(dev, GEN3_SDVOB, PORT_B);
14876                         if (!found && IS_G4X(dev)) {
14877                                 DRM_DEBUG_KMS("probing HDMI on SDVOB\n");
14878                                 intel_hdmi_init(dev, GEN4_HDMIB, PORT_B);
14879                         }
14880
14881                         if (!found && IS_G4X(dev))
14882                                 intel_dp_init(dev, DP_B, PORT_B);
14883                 }
14884
14885                 /* Before G4X SDVOC doesn't have its own detect register */
14886
14887                 if (I915_READ(GEN3_SDVOB) & SDVO_DETECTED) {
14888                         DRM_DEBUG_KMS("probing SDVOC\n");
14889                         found = intel_sdvo_init(dev, GEN3_SDVOC, PORT_C);
14890                 }
14891
14892                 if (!found && (I915_READ(GEN3_SDVOC) & SDVO_DETECTED)) {
14893
14894                         if (IS_G4X(dev)) {
14895                                 DRM_DEBUG_KMS("probing HDMI on SDVOC\n");
14896                                 intel_hdmi_init(dev, GEN4_HDMIC, PORT_C);
14897                         }
14898                         if (IS_G4X(dev))
14899                                 intel_dp_init(dev, DP_C, PORT_C);
14900                 }
14901
14902                 if (IS_G4X(dev) &&
14903                     (I915_READ(DP_D) & DP_DETECTED))
14904                         intel_dp_init(dev, DP_D, PORT_D);
14905         } else if (IS_GEN2(dev))
14906                 intel_dvo_init(dev);
14907
14908         if (SUPPORTS_TV(dev))
14909                 intel_tv_init(dev);
14910
14911         intel_psr_init(dev);
14912
14913         for_each_intel_encoder(dev, encoder) {
14914                 encoder->base.possible_crtcs = encoder->crtc_mask;
14915                 encoder->base.possible_clones =
14916                         intel_encoder_clones(encoder);
14917         }
14918
14919         intel_init_pch_refclk(dev);
14920
14921         drm_helper_move_panel_connectors_to_head(dev);
14922 }
14923
14924 static void intel_user_framebuffer_destroy(struct drm_framebuffer *fb)
14925 {
14926         struct drm_device *dev = fb->dev;
14927         struct intel_framebuffer *intel_fb = to_intel_framebuffer(fb);
14928
14929         drm_framebuffer_cleanup(fb);
14930         mutex_lock(&dev->struct_mutex);
14931         WARN_ON(!intel_fb->obj->framebuffer_references--);
14932         i915_gem_object_put(intel_fb->obj);
14933         mutex_unlock(&dev->struct_mutex);
14934         kfree(intel_fb);
14935 }
14936
14937 static int intel_user_framebuffer_create_handle(struct drm_framebuffer *fb,
14938                                                 struct drm_file *file,
14939                                                 unsigned int *handle)
14940 {
14941         struct intel_framebuffer *intel_fb = to_intel_framebuffer(fb);
14942         struct drm_i915_gem_object *obj = intel_fb->obj;
14943
14944         if (obj->userptr.mm) {
14945                 DRM_DEBUG("attempting to use a userptr for a framebuffer, denied\n");
14946                 return -EINVAL;
14947         }
14948
14949         return drm_gem_handle_create(file, &obj->base, handle);
14950 }
14951
14952 static int intel_user_framebuffer_dirty(struct drm_framebuffer *fb,
14953                                         struct drm_file *file,
14954                                         unsigned flags, unsigned color,
14955                                         struct drm_clip_rect *clips,
14956                                         unsigned num_clips)
14957 {
14958         struct drm_device *dev = fb->dev;
14959         struct intel_framebuffer *intel_fb = to_intel_framebuffer(fb);
14960         struct drm_i915_gem_object *obj = intel_fb->obj;
14961
14962         mutex_lock(&dev->struct_mutex);
14963         intel_fb_obj_flush(obj, false, ORIGIN_DIRTYFB);
14964         mutex_unlock(&dev->struct_mutex);
14965
14966         return 0;
14967 }
14968
14969 static const struct drm_framebuffer_funcs intel_fb_funcs = {
14970         .destroy = intel_user_framebuffer_destroy,
14971         .create_handle = intel_user_framebuffer_create_handle,
14972         .dirty = intel_user_framebuffer_dirty,
14973 };
14974
14975 static
14976 u32 intel_fb_pitch_limit(struct drm_device *dev, uint64_t fb_modifier,
14977                          uint32_t pixel_format)
14978 {
14979         u32 gen = INTEL_INFO(dev)->gen;
14980
14981         if (gen >= 9) {
14982                 int cpp = drm_format_plane_cpp(pixel_format, 0);
14983
14984                 /* "The stride in bytes must not exceed the of the size of 8K
14985                  *  pixels and 32K bytes."
14986                  */
14987                 return min(8192 * cpp, 32768);
14988         } else if (gen >= 5 && !IS_VALLEYVIEW(dev) && !IS_CHERRYVIEW(dev)) {
14989                 return 32*1024;
14990         } else if (gen >= 4) {
14991                 if (fb_modifier == I915_FORMAT_MOD_X_TILED)
14992                         return 16*1024;
14993                 else
14994                         return 32*1024;
14995         } else if (gen >= 3) {
14996                 if (fb_modifier == I915_FORMAT_MOD_X_TILED)
14997                         return 8*1024;
14998                 else
14999                         return 16*1024;
15000         } else {
15001                 /* XXX DSPC is limited to 4k tiled */
15002                 return 8*1024;
15003         }
15004 }
15005
15006 static int intel_framebuffer_init(struct drm_device *dev,
15007                                   struct intel_framebuffer *intel_fb,
15008                                   struct drm_mode_fb_cmd2 *mode_cmd,
15009                                   struct drm_i915_gem_object *obj)
15010 {
15011         struct drm_i915_private *dev_priv = to_i915(dev);
15012         unsigned int aligned_height;
15013         int ret;
15014         u32 pitch_limit, stride_alignment;
15015
15016         WARN_ON(!mutex_is_locked(&dev->struct_mutex));
15017
15018         if (mode_cmd->flags & DRM_MODE_FB_MODIFIERS) {
15019                 /* Enforce that fb modifier and tiling mode match, but only for
15020                  * X-tiled. This is needed for FBC. */
15021                 if (!!(i915_gem_object_get_tiling(obj) == I915_TILING_X) !=
15022                     !!(mode_cmd->modifier[0] == I915_FORMAT_MOD_X_TILED)) {
15023                         DRM_DEBUG("tiling_mode doesn't match fb modifier\n");
15024                         return -EINVAL;
15025                 }
15026         } else {
15027                 if (i915_gem_object_get_tiling(obj) == I915_TILING_X)
15028                         mode_cmd->modifier[0] = I915_FORMAT_MOD_X_TILED;
15029                 else if (i915_gem_object_get_tiling(obj) == I915_TILING_Y) {
15030                         DRM_DEBUG("No Y tiling for legacy addfb\n");
15031                         return -EINVAL;
15032                 }
15033         }
15034
15035         /* Passed in modifier sanity checking. */
15036         switch (mode_cmd->modifier[0]) {
15037         case I915_FORMAT_MOD_Y_TILED:
15038         case I915_FORMAT_MOD_Yf_TILED:
15039                 if (INTEL_INFO(dev)->gen < 9) {
15040                         DRM_DEBUG("Unsupported tiling 0x%llx!\n",
15041                                   mode_cmd->modifier[0]);
15042                         return -EINVAL;
15043                 }
15044         case DRM_FORMAT_MOD_NONE:
15045         case I915_FORMAT_MOD_X_TILED:
15046                 break;
15047         default:
15048                 DRM_DEBUG("Unsupported fb modifier 0x%llx!\n",
15049                           mode_cmd->modifier[0]);
15050                 return -EINVAL;
15051         }
15052
15053         stride_alignment = intel_fb_stride_alignment(dev_priv,
15054                                                      mode_cmd->modifier[0],
15055                                                      mode_cmd->pixel_format);
15056         if (mode_cmd->pitches[0] & (stride_alignment - 1)) {
15057                 DRM_DEBUG("pitch (%d) must be at least %u byte aligned\n",
15058                           mode_cmd->pitches[0], stride_alignment);
15059                 return -EINVAL;
15060         }
15061
15062         pitch_limit = intel_fb_pitch_limit(dev, mode_cmd->modifier[0],
15063                                            mode_cmd->pixel_format);
15064         if (mode_cmd->pitches[0] > pitch_limit) {
15065                 DRM_DEBUG("%s pitch (%u) must be at less than %d\n",
15066                           mode_cmd->modifier[0] != DRM_FORMAT_MOD_NONE ?
15067                           "tiled" : "linear",
15068                           mode_cmd->pitches[0], pitch_limit);
15069                 return -EINVAL;
15070         }
15071
15072         if (mode_cmd->modifier[0] == I915_FORMAT_MOD_X_TILED &&
15073             mode_cmd->pitches[0] != i915_gem_object_get_stride(obj)) {
15074                 DRM_DEBUG("pitch (%d) must match tiling stride (%d)\n",
15075                           mode_cmd->pitches[0],
15076                           i915_gem_object_get_stride(obj));
15077                 return -EINVAL;
15078         }
15079
15080         /* Reject formats not supported by any plane early. */
15081         switch (mode_cmd->pixel_format) {
15082         case DRM_FORMAT_C8:
15083         case DRM_FORMAT_RGB565:
15084         case DRM_FORMAT_XRGB8888:
15085         case DRM_FORMAT_ARGB8888:
15086                 break;
15087         case DRM_FORMAT_XRGB1555:
15088                 if (INTEL_INFO(dev)->gen > 3) {
15089                         DRM_DEBUG("unsupported pixel format: %s\n",
15090                                   drm_get_format_name(mode_cmd->pixel_format));
15091                         return -EINVAL;
15092                 }
15093                 break;
15094         case DRM_FORMAT_ABGR8888:
15095                 if (!IS_VALLEYVIEW(dev) && !IS_CHERRYVIEW(dev) &&
15096                     INTEL_INFO(dev)->gen < 9) {
15097                         DRM_DEBUG("unsupported pixel format: %s\n",
15098                                   drm_get_format_name(mode_cmd->pixel_format));
15099                         return -EINVAL;
15100                 }
15101                 break;
15102         case DRM_FORMAT_XBGR8888:
15103         case DRM_FORMAT_XRGB2101010:
15104         case DRM_FORMAT_XBGR2101010:
15105                 if (INTEL_INFO(dev)->gen < 4) {
15106                         DRM_DEBUG("unsupported pixel format: %s\n",
15107                                   drm_get_format_name(mode_cmd->pixel_format));
15108                         return -EINVAL;
15109                 }
15110                 break;
15111         case DRM_FORMAT_ABGR2101010:
15112                 if (!IS_VALLEYVIEW(dev) && !IS_CHERRYVIEW(dev)) {
15113                         DRM_DEBUG("unsupported pixel format: %s\n",
15114                                   drm_get_format_name(mode_cmd->pixel_format));
15115                         return -EINVAL;
15116                 }
15117                 break;
15118         case DRM_FORMAT_YUYV:
15119         case DRM_FORMAT_UYVY:
15120         case DRM_FORMAT_YVYU:
15121         case DRM_FORMAT_VYUY:
15122                 if (INTEL_INFO(dev)->gen < 5) {
15123                         DRM_DEBUG("unsupported pixel format: %s\n",
15124                                   drm_get_format_name(mode_cmd->pixel_format));
15125                         return -EINVAL;
15126                 }
15127                 break;
15128         default:
15129                 DRM_DEBUG("unsupported pixel format: %s\n",
15130                           drm_get_format_name(mode_cmd->pixel_format));
15131                 return -EINVAL;
15132         }
15133
15134         /* FIXME need to adjust LINOFF/TILEOFF accordingly. */
15135         if (mode_cmd->offsets[0] != 0)
15136                 return -EINVAL;
15137
15138         aligned_height = intel_fb_align_height(dev, mode_cmd->height,
15139                                                mode_cmd->pixel_format,
15140                                                mode_cmd->modifier[0]);
15141         /* FIXME drm helper for size checks (especially planar formats)? */
15142         if (obj->base.size < aligned_height * mode_cmd->pitches[0])
15143                 return -EINVAL;
15144
15145         drm_helper_mode_fill_fb_struct(&intel_fb->base, mode_cmd);
15146         intel_fb->obj = obj;
15147
15148         intel_fill_fb_info(dev_priv, &intel_fb->base);
15149
15150         ret = drm_framebuffer_init(dev, &intel_fb->base, &intel_fb_funcs);
15151         if (ret) {
15152                 DRM_ERROR("framebuffer init failed %d\n", ret);
15153                 return ret;
15154         }
15155
15156         intel_fb->obj->framebuffer_references++;
15157
15158         return 0;
15159 }
15160
15161 static struct drm_framebuffer *
15162 intel_user_framebuffer_create(struct drm_device *dev,
15163                               struct drm_file *filp,
15164                               const struct drm_mode_fb_cmd2 *user_mode_cmd)
15165 {
15166         struct drm_framebuffer *fb;
15167         struct drm_i915_gem_object *obj;
15168         struct drm_mode_fb_cmd2 mode_cmd = *user_mode_cmd;
15169
15170         obj = i915_gem_object_lookup(filp, mode_cmd.handles[0]);
15171         if (!obj)
15172                 return ERR_PTR(-ENOENT);
15173
15174         fb = intel_framebuffer_create(dev, &mode_cmd, obj);
15175         if (IS_ERR(fb))
15176                 i915_gem_object_put_unlocked(obj);
15177
15178         return fb;
15179 }
15180
15181 #ifndef CONFIG_DRM_FBDEV_EMULATION
15182 static inline void intel_fbdev_output_poll_changed(struct drm_device *dev)
15183 {
15184 }
15185 #endif
15186
15187 static const struct drm_mode_config_funcs intel_mode_funcs = {
15188         .fb_create = intel_user_framebuffer_create,
15189         .output_poll_changed = intel_fbdev_output_poll_changed,
15190         .atomic_check = intel_atomic_check,
15191         .atomic_commit = intel_atomic_commit,
15192         .atomic_state_alloc = intel_atomic_state_alloc,
15193         .atomic_state_clear = intel_atomic_state_clear,
15194 };
15195
15196 /**
15197  * intel_init_display_hooks - initialize the display modesetting hooks
15198  * @dev_priv: device private
15199  */
15200 void intel_init_display_hooks(struct drm_i915_private *dev_priv)
15201 {
15202         if (INTEL_INFO(dev_priv)->gen >= 9) {
15203                 dev_priv->display.get_pipe_config = haswell_get_pipe_config;
15204                 dev_priv->display.get_initial_plane_config =
15205                         skylake_get_initial_plane_config;
15206                 dev_priv->display.crtc_compute_clock =
15207                         haswell_crtc_compute_clock;
15208                 dev_priv->display.crtc_enable = haswell_crtc_enable;
15209                 dev_priv->display.crtc_disable = haswell_crtc_disable;
15210         } else if (HAS_DDI(dev_priv)) {
15211                 dev_priv->display.get_pipe_config = haswell_get_pipe_config;
15212                 dev_priv->display.get_initial_plane_config =
15213                         ironlake_get_initial_plane_config;
15214                 dev_priv->display.crtc_compute_clock =
15215                         haswell_crtc_compute_clock;
15216                 dev_priv->display.crtc_enable = haswell_crtc_enable;
15217                 dev_priv->display.crtc_disable = haswell_crtc_disable;
15218         } else if (HAS_PCH_SPLIT(dev_priv)) {
15219                 dev_priv->display.get_pipe_config = ironlake_get_pipe_config;
15220                 dev_priv->display.get_initial_plane_config =
15221                         ironlake_get_initial_plane_config;
15222                 dev_priv->display.crtc_compute_clock =
15223                         ironlake_crtc_compute_clock;
15224                 dev_priv->display.crtc_enable = ironlake_crtc_enable;
15225                 dev_priv->display.crtc_disable = ironlake_crtc_disable;
15226         } else if (IS_CHERRYVIEW(dev_priv)) {
15227                 dev_priv->display.get_pipe_config = i9xx_get_pipe_config;
15228                 dev_priv->display.get_initial_plane_config =
15229                         i9xx_get_initial_plane_config;
15230                 dev_priv->display.crtc_compute_clock = chv_crtc_compute_clock;
15231                 dev_priv->display.crtc_enable = valleyview_crtc_enable;
15232                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
15233         } else if (IS_VALLEYVIEW(dev_priv)) {
15234                 dev_priv->display.get_pipe_config = i9xx_get_pipe_config;
15235                 dev_priv->display.get_initial_plane_config =
15236                         i9xx_get_initial_plane_config;
15237                 dev_priv->display.crtc_compute_clock = vlv_crtc_compute_clock;
15238                 dev_priv->display.crtc_enable = valleyview_crtc_enable;
15239                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
15240         } else if (IS_G4X(dev_priv)) {
15241                 dev_priv->display.get_pipe_config = i9xx_get_pipe_config;
15242                 dev_priv->display.get_initial_plane_config =
15243                         i9xx_get_initial_plane_config;
15244                 dev_priv->display.crtc_compute_clock = g4x_crtc_compute_clock;
15245                 dev_priv->display.crtc_enable = i9xx_crtc_enable;
15246                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
15247         } else if (IS_PINEVIEW(dev_priv)) {
15248                 dev_priv->display.get_pipe_config = i9xx_get_pipe_config;
15249                 dev_priv->display.get_initial_plane_config =
15250                         i9xx_get_initial_plane_config;
15251                 dev_priv->display.crtc_compute_clock = pnv_crtc_compute_clock;
15252                 dev_priv->display.crtc_enable = i9xx_crtc_enable;
15253                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
15254         } else if (!IS_GEN2(dev_priv)) {
15255                 dev_priv->display.get_pipe_config = i9xx_get_pipe_config;
15256                 dev_priv->display.get_initial_plane_config =
15257                         i9xx_get_initial_plane_config;
15258                 dev_priv->display.crtc_compute_clock = i9xx_crtc_compute_clock;
15259                 dev_priv->display.crtc_enable = i9xx_crtc_enable;
15260                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
15261         } else {
15262                 dev_priv->display.get_pipe_config = i9xx_get_pipe_config;
15263                 dev_priv->display.get_initial_plane_config =
15264                         i9xx_get_initial_plane_config;
15265                 dev_priv->display.crtc_compute_clock = i8xx_crtc_compute_clock;
15266                 dev_priv->display.crtc_enable = i9xx_crtc_enable;
15267                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
15268         }
15269
15270         /* Returns the core display clock speed */
15271         if (IS_SKYLAKE(dev_priv) || IS_KABYLAKE(dev_priv))
15272                 dev_priv->display.get_display_clock_speed =
15273                         skylake_get_display_clock_speed;
15274         else if (IS_BROXTON(dev_priv))
15275                 dev_priv->display.get_display_clock_speed =
15276                         broxton_get_display_clock_speed;
15277         else if (IS_BROADWELL(dev_priv))
15278                 dev_priv->display.get_display_clock_speed =
15279                         broadwell_get_display_clock_speed;
15280         else if (IS_HASWELL(dev_priv))
15281                 dev_priv->display.get_display_clock_speed =
15282                         haswell_get_display_clock_speed;
15283         else if (IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv))
15284                 dev_priv->display.get_display_clock_speed =
15285                         valleyview_get_display_clock_speed;
15286         else if (IS_GEN5(dev_priv))
15287                 dev_priv->display.get_display_clock_speed =
15288                         ilk_get_display_clock_speed;
15289         else if (IS_I945G(dev_priv) || IS_BROADWATER(dev_priv) ||
15290                  IS_GEN6(dev_priv) || IS_IVYBRIDGE(dev_priv))
15291                 dev_priv->display.get_display_clock_speed =
15292                         i945_get_display_clock_speed;
15293         else if (IS_GM45(dev_priv))
15294                 dev_priv->display.get_display_clock_speed =
15295                         gm45_get_display_clock_speed;
15296         else if (IS_CRESTLINE(dev_priv))
15297                 dev_priv->display.get_display_clock_speed =
15298                         i965gm_get_display_clock_speed;
15299         else if (IS_PINEVIEW(dev_priv))
15300                 dev_priv->display.get_display_clock_speed =
15301                         pnv_get_display_clock_speed;
15302         else if (IS_G33(dev_priv) || IS_G4X(dev_priv))
15303                 dev_priv->display.get_display_clock_speed =
15304                         g33_get_display_clock_speed;
15305         else if (IS_I915G(dev_priv))
15306                 dev_priv->display.get_display_clock_speed =
15307                         i915_get_display_clock_speed;
15308         else if (IS_I945GM(dev_priv) || IS_845G(dev_priv))
15309                 dev_priv->display.get_display_clock_speed =
15310                         i9xx_misc_get_display_clock_speed;
15311         else if (IS_I915GM(dev_priv))
15312                 dev_priv->display.get_display_clock_speed =
15313                         i915gm_get_display_clock_speed;
15314         else if (IS_I865G(dev_priv))
15315                 dev_priv->display.get_display_clock_speed =
15316                         i865_get_display_clock_speed;
15317         else if (IS_I85X(dev_priv))
15318                 dev_priv->display.get_display_clock_speed =
15319                         i85x_get_display_clock_speed;
15320         else { /* 830 */
15321                 WARN(!IS_I830(dev_priv), "Unknown platform. Assuming 133 MHz CDCLK\n");
15322                 dev_priv->display.get_display_clock_speed =
15323                         i830_get_display_clock_speed;
15324         }
15325
15326         if (IS_GEN5(dev_priv)) {
15327                 dev_priv->display.fdi_link_train = ironlake_fdi_link_train;
15328         } else if (IS_GEN6(dev_priv)) {
15329                 dev_priv->display.fdi_link_train = gen6_fdi_link_train;
15330         } else if (IS_IVYBRIDGE(dev_priv)) {
15331                 /* FIXME: detect B0+ stepping and use auto training */
15332                 dev_priv->display.fdi_link_train = ivb_manual_fdi_link_train;
15333         } else if (IS_HASWELL(dev_priv) || IS_BROADWELL(dev_priv)) {
15334                 dev_priv->display.fdi_link_train = hsw_fdi_link_train;
15335         }
15336
15337         if (IS_BROADWELL(dev_priv)) {
15338                 dev_priv->display.modeset_commit_cdclk =
15339                         broadwell_modeset_commit_cdclk;
15340                 dev_priv->display.modeset_calc_cdclk =
15341                         broadwell_modeset_calc_cdclk;
15342         } else if (IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv)) {
15343                 dev_priv->display.modeset_commit_cdclk =
15344                         valleyview_modeset_commit_cdclk;
15345                 dev_priv->display.modeset_calc_cdclk =
15346                         valleyview_modeset_calc_cdclk;
15347         } else if (IS_BROXTON(dev_priv)) {
15348                 dev_priv->display.modeset_commit_cdclk =
15349                         bxt_modeset_commit_cdclk;
15350                 dev_priv->display.modeset_calc_cdclk =
15351                         bxt_modeset_calc_cdclk;
15352         } else if (IS_SKYLAKE(dev_priv) || IS_KABYLAKE(dev_priv)) {
15353                 dev_priv->display.modeset_commit_cdclk =
15354                         skl_modeset_commit_cdclk;
15355                 dev_priv->display.modeset_calc_cdclk =
15356                         skl_modeset_calc_cdclk;
15357         }
15358
15359         switch (INTEL_INFO(dev_priv)->gen) {
15360         case 2:
15361                 dev_priv->display.queue_flip = intel_gen2_queue_flip;
15362                 break;
15363
15364         case 3:
15365                 dev_priv->display.queue_flip = intel_gen3_queue_flip;
15366                 break;
15367
15368         case 4:
15369         case 5:
15370                 dev_priv->display.queue_flip = intel_gen4_queue_flip;
15371                 break;
15372
15373         case 6:
15374                 dev_priv->display.queue_flip = intel_gen6_queue_flip;
15375                 break;
15376         case 7:
15377         case 8: /* FIXME(BDW): Check that the gen8 RCS flip works. */
15378                 dev_priv->display.queue_flip = intel_gen7_queue_flip;
15379                 break;
15380         case 9:
15381                 /* Drop through - unsupported since execlist only. */
15382         default:
15383                 /* Default just returns -ENODEV to indicate unsupported */
15384                 dev_priv->display.queue_flip = intel_default_queue_flip;
15385         }
15386 }
15387
15388 /*
15389  * Some BIOSes insist on assuming the GPU's pipe A is enabled at suspend,
15390  * resume, or other times.  This quirk makes sure that's the case for
15391  * affected systems.
15392  */
15393 static void quirk_pipea_force(struct drm_device *dev)
15394 {
15395         struct drm_i915_private *dev_priv = to_i915(dev);
15396
15397         dev_priv->quirks |= QUIRK_PIPEA_FORCE;
15398         DRM_INFO("applying pipe a force quirk\n");
15399 }
15400
15401 static void quirk_pipeb_force(struct drm_device *dev)
15402 {
15403         struct drm_i915_private *dev_priv = to_i915(dev);
15404
15405         dev_priv->quirks |= QUIRK_PIPEB_FORCE;
15406         DRM_INFO("applying pipe b force quirk\n");
15407 }
15408
15409 /*
15410  * Some machines (Lenovo U160) do not work with SSC on LVDS for some reason
15411  */
15412 static void quirk_ssc_force_disable(struct drm_device *dev)
15413 {
15414         struct drm_i915_private *dev_priv = to_i915(dev);
15415         dev_priv->quirks |= QUIRK_LVDS_SSC_DISABLE;
15416         DRM_INFO("applying lvds SSC disable quirk\n");
15417 }
15418
15419 /*
15420  * A machine (e.g. Acer Aspire 5734Z) may need to invert the panel backlight
15421  * brightness value
15422  */
15423 static void quirk_invert_brightness(struct drm_device *dev)
15424 {
15425         struct drm_i915_private *dev_priv = to_i915(dev);
15426         dev_priv->quirks |= QUIRK_INVERT_BRIGHTNESS;
15427         DRM_INFO("applying inverted panel brightness quirk\n");
15428 }
15429
15430 /* Some VBT's incorrectly indicate no backlight is present */
15431 static void quirk_backlight_present(struct drm_device *dev)
15432 {
15433         struct drm_i915_private *dev_priv = to_i915(dev);
15434         dev_priv->quirks |= QUIRK_BACKLIGHT_PRESENT;
15435         DRM_INFO("applying backlight present quirk\n");
15436 }
15437
15438 struct intel_quirk {
15439         int device;
15440         int subsystem_vendor;
15441         int subsystem_device;
15442         void (*hook)(struct drm_device *dev);
15443 };
15444
15445 /* For systems that don't have a meaningful PCI subdevice/subvendor ID */
15446 struct intel_dmi_quirk {
15447         void (*hook)(struct drm_device *dev);
15448         const struct dmi_system_id (*dmi_id_list)[];
15449 };
15450
15451 static int intel_dmi_reverse_brightness(const struct dmi_system_id *id)
15452 {
15453         DRM_INFO("Backlight polarity reversed on %s\n", id->ident);
15454         return 1;
15455 }
15456
15457 static const struct intel_dmi_quirk intel_dmi_quirks[] = {
15458         {
15459                 .dmi_id_list = &(const struct dmi_system_id[]) {
15460                         {
15461                                 .callback = intel_dmi_reverse_brightness,
15462                                 .ident = "NCR Corporation",
15463                                 .matches = {DMI_MATCH(DMI_SYS_VENDOR, "NCR Corporation"),
15464                                             DMI_MATCH(DMI_PRODUCT_NAME, ""),
15465                                 },
15466                         },
15467                         { }  /* terminating entry */
15468                 },
15469                 .hook = quirk_invert_brightness,
15470         },
15471 };
15472
15473 static struct intel_quirk intel_quirks[] = {
15474         /* Toshiba Protege R-205, S-209 needs pipe A force quirk */
15475         { 0x2592, 0x1179, 0x0001, quirk_pipea_force },
15476
15477         /* ThinkPad T60 needs pipe A force quirk (bug #16494) */
15478         { 0x2782, 0x17aa, 0x201a, quirk_pipea_force },
15479
15480         /* 830 needs to leave pipe A & dpll A up */
15481         { 0x3577, PCI_ANY_ID, PCI_ANY_ID, quirk_pipea_force },
15482
15483         /* 830 needs to leave pipe B & dpll B up */
15484         { 0x3577, PCI_ANY_ID, PCI_ANY_ID, quirk_pipeb_force },
15485
15486         /* Lenovo U160 cannot use SSC on LVDS */
15487         { 0x0046, 0x17aa, 0x3920, quirk_ssc_force_disable },
15488
15489         /* Sony Vaio Y cannot use SSC on LVDS */
15490         { 0x0046, 0x104d, 0x9076, quirk_ssc_force_disable },
15491
15492         /* Acer Aspire 5734Z must invert backlight brightness */
15493         { 0x2a42, 0x1025, 0x0459, quirk_invert_brightness },
15494
15495         /* Acer/eMachines G725 */
15496         { 0x2a42, 0x1025, 0x0210, quirk_invert_brightness },
15497
15498         /* Acer/eMachines e725 */
15499         { 0x2a42, 0x1025, 0x0212, quirk_invert_brightness },
15500
15501         /* Acer/Packard Bell NCL20 */
15502         { 0x2a42, 0x1025, 0x034b, quirk_invert_brightness },
15503
15504         /* Acer Aspire 4736Z */
15505         { 0x2a42, 0x1025, 0x0260, quirk_invert_brightness },
15506
15507         /* Acer Aspire 5336 */
15508         { 0x2a42, 0x1025, 0x048a, quirk_invert_brightness },
15509
15510         /* Acer C720 and C720P Chromebooks (Celeron 2955U) have backlights */
15511         { 0x0a06, 0x1025, 0x0a11, quirk_backlight_present },
15512
15513         /* Acer C720 Chromebook (Core i3 4005U) */
15514         { 0x0a16, 0x1025, 0x0a11, quirk_backlight_present },
15515
15516         /* Apple Macbook 2,1 (Core 2 T7400) */
15517         { 0x27a2, 0x8086, 0x7270, quirk_backlight_present },
15518
15519         /* Apple Macbook 4,1 */
15520         { 0x2a02, 0x106b, 0x00a1, quirk_backlight_present },
15521
15522         /* Toshiba CB35 Chromebook (Celeron 2955U) */
15523         { 0x0a06, 0x1179, 0x0a88, quirk_backlight_present },
15524
15525         /* HP Chromebook 14 (Celeron 2955U) */
15526         { 0x0a06, 0x103c, 0x21ed, quirk_backlight_present },
15527
15528         /* Dell Chromebook 11 */
15529         { 0x0a06, 0x1028, 0x0a35, quirk_backlight_present },
15530
15531         /* Dell Chromebook 11 (2015 version) */
15532         { 0x0a16, 0x1028, 0x0a35, quirk_backlight_present },
15533 };
15534
15535 static void intel_init_quirks(struct drm_device *dev)
15536 {
15537         struct pci_dev *d = dev->pdev;
15538         int i;
15539
15540         for (i = 0; i < ARRAY_SIZE(intel_quirks); i++) {
15541                 struct intel_quirk *q = &intel_quirks[i];
15542
15543                 if (d->device == q->device &&
15544                     (d->subsystem_vendor == q->subsystem_vendor ||
15545                      q->subsystem_vendor == PCI_ANY_ID) &&
15546                     (d->subsystem_device == q->subsystem_device ||
15547                      q->subsystem_device == PCI_ANY_ID))
15548                         q->hook(dev);
15549         }
15550         for (i = 0; i < ARRAY_SIZE(intel_dmi_quirks); i++) {
15551                 if (dmi_check_system(*intel_dmi_quirks[i].dmi_id_list) != 0)
15552                         intel_dmi_quirks[i].hook(dev);
15553         }
15554 }
15555
15556 /* Disable the VGA plane that we never use */
15557 static void i915_disable_vga(struct drm_device *dev)
15558 {
15559         struct drm_i915_private *dev_priv = to_i915(dev);
15560         u8 sr1;
15561         i915_reg_t vga_reg = i915_vgacntrl_reg(dev);
15562
15563         /* WaEnableVGAAccessThroughIOPort:ctg,elk,ilk,snb,ivb,vlv,hsw */
15564         vga_get_uninterruptible(dev->pdev, VGA_RSRC_LEGACY_IO);
15565         outb(SR01, VGA_SR_INDEX);
15566         sr1 = inb(VGA_SR_DATA);
15567         outb(sr1 | 1<<5, VGA_SR_DATA);
15568         vga_put(dev->pdev, VGA_RSRC_LEGACY_IO);
15569         udelay(300);
15570
15571         I915_WRITE(vga_reg, VGA_DISP_DISABLE);
15572         POSTING_READ(vga_reg);
15573 }
15574
15575 void intel_modeset_init_hw(struct drm_device *dev)
15576 {
15577         struct drm_i915_private *dev_priv = to_i915(dev);
15578
15579         intel_update_cdclk(dev);
15580
15581         dev_priv->atomic_cdclk_freq = dev_priv->cdclk_freq;
15582
15583         intel_init_clock_gating(dev);
15584 }
15585
15586 /*
15587  * Calculate what we think the watermarks should be for the state we've read
15588  * out of the hardware and then immediately program those watermarks so that
15589  * we ensure the hardware settings match our internal state.
15590  *
15591  * We can calculate what we think WM's should be by creating a duplicate of the
15592  * current state (which was constructed during hardware readout) and running it
15593  * through the atomic check code to calculate new watermark values in the
15594  * state object.
15595  */
15596 static void sanitize_watermarks(struct drm_device *dev)
15597 {
15598         struct drm_i915_private *dev_priv = to_i915(dev);
15599         struct drm_atomic_state *state;
15600         struct drm_crtc *crtc;
15601         struct drm_crtc_state *cstate;
15602         struct drm_modeset_acquire_ctx ctx;
15603         int ret;
15604         int i;
15605
15606         /* Only supported on platforms that use atomic watermark design */
15607         if (!dev_priv->display.optimize_watermarks)
15608                 return;
15609
15610         /*
15611          * We need to hold connection_mutex before calling duplicate_state so
15612          * that the connector loop is protected.
15613          */
15614         drm_modeset_acquire_init(&ctx, 0);
15615 retry:
15616         ret = drm_modeset_lock_all_ctx(dev, &ctx);
15617         if (ret == -EDEADLK) {
15618                 drm_modeset_backoff(&ctx);
15619                 goto retry;
15620         } else if (WARN_ON(ret)) {
15621                 goto fail;
15622         }
15623
15624         state = drm_atomic_helper_duplicate_state(dev, &ctx);
15625         if (WARN_ON(IS_ERR(state)))
15626                 goto fail;
15627
15628         /*
15629          * Hardware readout is the only time we don't want to calculate
15630          * intermediate watermarks (since we don't trust the current
15631          * watermarks).
15632          */
15633         to_intel_atomic_state(state)->skip_intermediate_wm = true;
15634
15635         ret = intel_atomic_check(dev, state);
15636         if (ret) {
15637                 /*
15638                  * If we fail here, it means that the hardware appears to be
15639                  * programmed in a way that shouldn't be possible, given our
15640                  * understanding of watermark requirements.  This might mean a
15641                  * mistake in the hardware readout code or a mistake in the
15642                  * watermark calculations for a given platform.  Raise a WARN
15643                  * so that this is noticeable.
15644                  *
15645                  * If this actually happens, we'll have to just leave the
15646                  * BIOS-programmed watermarks untouched and hope for the best.
15647                  */
15648                 WARN(true, "Could not determine valid watermarks for inherited state\n");
15649                 goto fail;
15650         }
15651
15652         /* Write calculated watermark values back */
15653         for_each_crtc_in_state(state, crtc, cstate, i) {
15654                 struct intel_crtc_state *cs = to_intel_crtc_state(cstate);
15655
15656                 cs->wm.need_postvbl_update = true;
15657                 dev_priv->display.optimize_watermarks(cs);
15658         }
15659
15660         drm_atomic_state_free(state);
15661 fail:
15662         drm_modeset_drop_locks(&ctx);
15663         drm_modeset_acquire_fini(&ctx);
15664 }
15665
15666 void intel_modeset_init(struct drm_device *dev)
15667 {
15668         struct drm_i915_private *dev_priv = to_i915(dev);
15669         struct i915_ggtt *ggtt = &dev_priv->ggtt;
15670         int sprite, ret;
15671         enum pipe pipe;
15672         struct intel_crtc *crtc;
15673
15674         drm_mode_config_init(dev);
15675
15676         dev->mode_config.min_width = 0;
15677         dev->mode_config.min_height = 0;
15678
15679         dev->mode_config.preferred_depth = 24;
15680         dev->mode_config.prefer_shadow = 1;
15681
15682         dev->mode_config.allow_fb_modifiers = true;
15683
15684         dev->mode_config.funcs = &intel_mode_funcs;
15685
15686         intel_init_quirks(dev);
15687
15688         intel_init_pm(dev);
15689
15690         if (INTEL_INFO(dev)->num_pipes == 0)
15691                 return;
15692
15693         /*
15694          * There may be no VBT; and if the BIOS enabled SSC we can
15695          * just keep using it to avoid unnecessary flicker.  Whereas if the
15696          * BIOS isn't using it, don't assume it will work even if the VBT
15697          * indicates as much.
15698          */
15699         if (HAS_PCH_IBX(dev) || HAS_PCH_CPT(dev)) {
15700                 bool bios_lvds_use_ssc = !!(I915_READ(PCH_DREF_CONTROL) &
15701                                             DREF_SSC1_ENABLE);
15702
15703                 if (dev_priv->vbt.lvds_use_ssc != bios_lvds_use_ssc) {
15704                         DRM_DEBUG_KMS("SSC %sabled by BIOS, overriding VBT which says %sabled\n",
15705                                      bios_lvds_use_ssc ? "en" : "dis",
15706                                      dev_priv->vbt.lvds_use_ssc ? "en" : "dis");
15707                         dev_priv->vbt.lvds_use_ssc = bios_lvds_use_ssc;
15708                 }
15709         }
15710
15711         if (IS_GEN2(dev)) {
15712                 dev->mode_config.max_width = 2048;
15713                 dev->mode_config.max_height = 2048;
15714         } else if (IS_GEN3(dev)) {
15715                 dev->mode_config.max_width = 4096;
15716                 dev->mode_config.max_height = 4096;
15717         } else {
15718                 dev->mode_config.max_width = 8192;
15719                 dev->mode_config.max_height = 8192;
15720         }
15721
15722         if (IS_845G(dev) || IS_I865G(dev)) {
15723                 dev->mode_config.cursor_width = IS_845G(dev) ? 64 : 512;
15724                 dev->mode_config.cursor_height = 1023;
15725         } else if (IS_GEN2(dev)) {
15726                 dev->mode_config.cursor_width = GEN2_CURSOR_WIDTH;
15727                 dev->mode_config.cursor_height = GEN2_CURSOR_HEIGHT;
15728         } else {
15729                 dev->mode_config.cursor_width = MAX_CURSOR_WIDTH;
15730                 dev->mode_config.cursor_height = MAX_CURSOR_HEIGHT;
15731         }
15732
15733         dev->mode_config.fb_base = ggtt->mappable_base;
15734
15735         DRM_DEBUG_KMS("%d display pipe%s available.\n",
15736                       INTEL_INFO(dev)->num_pipes,
15737                       INTEL_INFO(dev)->num_pipes > 1 ? "s" : "");
15738
15739         for_each_pipe(dev_priv, pipe) {
15740                 intel_crtc_init(dev, pipe);
15741                 for_each_sprite(dev_priv, pipe, sprite) {
15742                         ret = intel_plane_init(dev, pipe, sprite);
15743                         if (ret)
15744                                 DRM_DEBUG_KMS("pipe %c sprite %c init failed: %d\n",
15745                                               pipe_name(pipe), sprite_name(pipe, sprite), ret);
15746                 }
15747         }
15748
15749         intel_update_czclk(dev_priv);
15750         intel_update_cdclk(dev);
15751
15752         intel_shared_dpll_init(dev);
15753
15754         if (dev_priv->max_cdclk_freq == 0)
15755                 intel_update_max_cdclk(dev);
15756
15757         /* Just disable it once at startup */
15758         i915_disable_vga(dev);
15759         intel_setup_outputs(dev);
15760
15761         drm_modeset_lock_all(dev);
15762         intel_modeset_setup_hw_state(dev);
15763         drm_modeset_unlock_all(dev);
15764
15765         for_each_intel_crtc(dev, crtc) {
15766                 struct intel_initial_plane_config plane_config = {};
15767
15768                 if (!crtc->active)
15769                         continue;
15770
15771                 /*
15772                  * Note that reserving the BIOS fb up front prevents us
15773                  * from stuffing other stolen allocations like the ring
15774                  * on top.  This prevents some ugliness at boot time, and
15775                  * can even allow for smooth boot transitions if the BIOS
15776                  * fb is large enough for the active pipe configuration.
15777                  */
15778                 dev_priv->display.get_initial_plane_config(crtc,
15779                                                            &plane_config);
15780
15781                 /*
15782                  * If the fb is shared between multiple heads, we'll
15783                  * just get the first one.
15784                  */
15785                 intel_find_initial_plane_obj(crtc, &plane_config);
15786         }
15787
15788         /*
15789          * Make sure hardware watermarks really match the state we read out.
15790          * Note that we need to do this after reconstructing the BIOS fb's
15791          * since the watermark calculation done here will use pstate->fb.
15792          */
15793         sanitize_watermarks(dev);
15794 }
15795
15796 static void intel_enable_pipe_a(struct drm_device *dev)
15797 {
15798         struct intel_connector *connector;
15799         struct drm_connector *crt = NULL;
15800         struct intel_load_detect_pipe load_detect_temp;
15801         struct drm_modeset_acquire_ctx *ctx = dev->mode_config.acquire_ctx;
15802
15803         /* We can't just switch on the pipe A, we need to set things up with a
15804          * proper mode and output configuration. As a gross hack, enable pipe A
15805          * by enabling the load detect pipe once. */
15806         for_each_intel_connector(dev, connector) {
15807                 if (connector->encoder->type == INTEL_OUTPUT_ANALOG) {
15808                         crt = &connector->base;
15809                         break;
15810                 }
15811         }
15812
15813         if (!crt)
15814                 return;
15815
15816         if (intel_get_load_detect_pipe(crt, NULL, &load_detect_temp, ctx))
15817                 intel_release_load_detect_pipe(crt, &load_detect_temp, ctx);
15818 }
15819
15820 static bool
15821 intel_check_plane_mapping(struct intel_crtc *crtc)
15822 {
15823         struct drm_device *dev = crtc->base.dev;
15824         struct drm_i915_private *dev_priv = to_i915(dev);
15825         u32 val;
15826
15827         if (INTEL_INFO(dev)->num_pipes == 1)
15828                 return true;
15829
15830         val = I915_READ(DSPCNTR(!crtc->plane));
15831
15832         if ((val & DISPLAY_PLANE_ENABLE) &&
15833             (!!(val & DISPPLANE_SEL_PIPE_MASK) == crtc->pipe))
15834                 return false;
15835
15836         return true;
15837 }
15838
15839 static bool intel_crtc_has_encoders(struct intel_crtc *crtc)
15840 {
15841         struct drm_device *dev = crtc->base.dev;
15842         struct intel_encoder *encoder;
15843
15844         for_each_encoder_on_crtc(dev, &crtc->base, encoder)
15845                 return true;
15846
15847         return false;
15848 }
15849
15850 static bool intel_encoder_has_connectors(struct intel_encoder *encoder)
15851 {
15852         struct drm_device *dev = encoder->base.dev;
15853         struct intel_connector *connector;
15854
15855         for_each_connector_on_encoder(dev, &encoder->base, connector)
15856                 return true;
15857
15858         return false;
15859 }
15860
15861 static bool has_pch_trancoder(struct drm_i915_private *dev_priv,
15862                               enum transcoder pch_transcoder)
15863 {
15864         return HAS_PCH_IBX(dev_priv) || HAS_PCH_CPT(dev_priv) ||
15865                 (HAS_PCH_LPT_H(dev_priv) && pch_transcoder == TRANSCODER_A);
15866 }
15867
15868 static void intel_sanitize_crtc(struct intel_crtc *crtc)
15869 {
15870         struct drm_device *dev = crtc->base.dev;
15871         struct drm_i915_private *dev_priv = to_i915(dev);
15872         enum transcoder cpu_transcoder = crtc->config->cpu_transcoder;
15873
15874         /* Clear any frame start delays used for debugging left by the BIOS */
15875         if (!transcoder_is_dsi(cpu_transcoder)) {
15876                 i915_reg_t reg = PIPECONF(cpu_transcoder);
15877
15878                 I915_WRITE(reg,
15879                            I915_READ(reg) & ~PIPECONF_FRAME_START_DELAY_MASK);
15880         }
15881
15882         /* restore vblank interrupts to correct state */
15883         drm_crtc_vblank_reset(&crtc->base);
15884         if (crtc->active) {
15885                 struct intel_plane *plane;
15886
15887                 drm_crtc_vblank_on(&crtc->base);
15888
15889                 /* Disable everything but the primary plane */
15890                 for_each_intel_plane_on_crtc(dev, crtc, plane) {
15891                         if (plane->base.type == DRM_PLANE_TYPE_PRIMARY)
15892                                 continue;
15893
15894                         plane->disable_plane(&plane->base, &crtc->base);
15895                 }
15896         }
15897
15898         /* We need to sanitize the plane -> pipe mapping first because this will
15899          * disable the crtc (and hence change the state) if it is wrong. Note
15900          * that gen4+ has a fixed plane -> pipe mapping.  */
15901         if (INTEL_INFO(dev)->gen < 4 && !intel_check_plane_mapping(crtc)) {
15902                 bool plane;
15903
15904                 DRM_DEBUG_KMS("[CRTC:%d:%s] wrong plane connection detected!\n",
15905                               crtc->base.base.id, crtc->base.name);
15906
15907                 /* Pipe has the wrong plane attached and the plane is active.
15908                  * Temporarily change the plane mapping and disable everything
15909                  * ...  */
15910                 plane = crtc->plane;
15911                 to_intel_plane_state(crtc->base.primary->state)->visible = true;
15912                 crtc->plane = !plane;
15913                 intel_crtc_disable_noatomic(&crtc->base);
15914                 crtc->plane = plane;
15915         }
15916
15917         if (dev_priv->quirks & QUIRK_PIPEA_FORCE &&
15918             crtc->pipe == PIPE_A && !crtc->active) {
15919                 /* BIOS forgot to enable pipe A, this mostly happens after
15920                  * resume. Force-enable the pipe to fix this, the update_dpms
15921                  * call below we restore the pipe to the right state, but leave
15922                  * the required bits on. */
15923                 intel_enable_pipe_a(dev);
15924         }
15925
15926         /* Adjust the state of the output pipe according to whether we
15927          * have active connectors/encoders. */
15928         if (crtc->active && !intel_crtc_has_encoders(crtc))
15929                 intel_crtc_disable_noatomic(&crtc->base);
15930
15931         if (crtc->active || HAS_GMCH_DISPLAY(dev)) {
15932                 /*
15933                  * We start out with underrun reporting disabled to avoid races.
15934                  * For correct bookkeeping mark this on active crtcs.
15935                  *
15936                  * Also on gmch platforms we dont have any hardware bits to
15937                  * disable the underrun reporting. Which means we need to start
15938                  * out with underrun reporting disabled also on inactive pipes,
15939                  * since otherwise we'll complain about the garbage we read when
15940                  * e.g. coming up after runtime pm.
15941                  *
15942                  * No protection against concurrent access is required - at
15943                  * worst a fifo underrun happens which also sets this to false.
15944                  */
15945                 crtc->cpu_fifo_underrun_disabled = true;
15946                 /*
15947                  * We track the PCH trancoder underrun reporting state
15948                  * within the crtc. With crtc for pipe A housing the underrun
15949                  * reporting state for PCH transcoder A, crtc for pipe B housing
15950                  * it for PCH transcoder B, etc. LPT-H has only PCH transcoder A,
15951                  * and marking underrun reporting as disabled for the non-existing
15952                  * PCH transcoders B and C would prevent enabling the south
15953                  * error interrupt (see cpt_can_enable_serr_int()).
15954                  */
15955                 if (has_pch_trancoder(dev_priv, (enum transcoder)crtc->pipe))
15956                         crtc->pch_fifo_underrun_disabled = true;
15957         }
15958 }
15959
15960 static void intel_sanitize_encoder(struct intel_encoder *encoder)
15961 {
15962         struct intel_connector *connector;
15963         struct drm_device *dev = encoder->base.dev;
15964
15965         /* We need to check both for a crtc link (meaning that the
15966          * encoder is active and trying to read from a pipe) and the
15967          * pipe itself being active. */
15968         bool has_active_crtc = encoder->base.crtc &&
15969                 to_intel_crtc(encoder->base.crtc)->active;
15970
15971         if (intel_encoder_has_connectors(encoder) && !has_active_crtc) {
15972                 DRM_DEBUG_KMS("[ENCODER:%d:%s] has active connectors but no active pipe!\n",
15973                               encoder->base.base.id,
15974                               encoder->base.name);
15975
15976                 /* Connector is active, but has no active pipe. This is
15977                  * fallout from our resume register restoring. Disable
15978                  * the encoder manually again. */
15979                 if (encoder->base.crtc) {
15980                         DRM_DEBUG_KMS("[ENCODER:%d:%s] manually disabled\n",
15981                                       encoder->base.base.id,
15982                                       encoder->base.name);
15983                         encoder->disable(encoder);
15984                         if (encoder->post_disable)
15985                                 encoder->post_disable(encoder);
15986                 }
15987                 encoder->base.crtc = NULL;
15988
15989                 /* Inconsistent output/port/pipe state happens presumably due to
15990                  * a bug in one of the get_hw_state functions. Or someplace else
15991                  * in our code, like the register restore mess on resume. Clamp
15992                  * things to off as a safer default. */
15993                 for_each_intel_connector(dev, connector) {
15994                         if (connector->encoder != encoder)
15995                                 continue;
15996                         connector->base.dpms = DRM_MODE_DPMS_OFF;
15997                         connector->base.encoder = NULL;
15998                 }
15999         }
16000         /* Enabled encoders without active connectors will be fixed in
16001          * the crtc fixup. */
16002 }
16003
16004 void i915_redisable_vga_power_on(struct drm_device *dev)
16005 {
16006         struct drm_i915_private *dev_priv = to_i915(dev);
16007         i915_reg_t vga_reg = i915_vgacntrl_reg(dev);
16008
16009         if (!(I915_READ(vga_reg) & VGA_DISP_DISABLE)) {
16010                 DRM_DEBUG_KMS("Something enabled VGA plane, disabling it\n");
16011                 i915_disable_vga(dev);
16012         }
16013 }
16014
16015 void i915_redisable_vga(struct drm_device *dev)
16016 {
16017         struct drm_i915_private *dev_priv = to_i915(dev);
16018
16019         /* This function can be called both from intel_modeset_setup_hw_state or
16020          * at a very early point in our resume sequence, where the power well
16021          * structures are not yet restored. Since this function is at a very
16022          * paranoid "someone might have enabled VGA while we were not looking"
16023          * level, just check if the power well is enabled instead of trying to
16024          * follow the "don't touch the power well if we don't need it" policy
16025          * the rest of the driver uses. */
16026         if (!intel_display_power_get_if_enabled(dev_priv, POWER_DOMAIN_VGA))
16027                 return;
16028
16029         i915_redisable_vga_power_on(dev);
16030
16031         intel_display_power_put(dev_priv, POWER_DOMAIN_VGA);
16032 }
16033
16034 static bool primary_get_hw_state(struct intel_plane *plane)
16035 {
16036         struct drm_i915_private *dev_priv = to_i915(plane->base.dev);
16037
16038         return I915_READ(DSPCNTR(plane->plane)) & DISPLAY_PLANE_ENABLE;
16039 }
16040
16041 /* FIXME read out full plane state for all planes */
16042 static void readout_plane_state(struct intel_crtc *crtc)
16043 {
16044         struct drm_plane *primary = crtc->base.primary;
16045         struct intel_plane_state *plane_state =
16046                 to_intel_plane_state(primary->state);
16047
16048         plane_state->visible = crtc->active &&
16049                 primary_get_hw_state(to_intel_plane(primary));
16050
16051         if (plane_state->visible)
16052                 crtc->base.state->plane_mask |= 1 << drm_plane_index(primary);
16053 }
16054
16055 static void intel_modeset_readout_hw_state(struct drm_device *dev)
16056 {
16057         struct drm_i915_private *dev_priv = to_i915(dev);
16058         enum pipe pipe;
16059         struct intel_crtc *crtc;
16060         struct intel_encoder *encoder;
16061         struct intel_connector *connector;
16062         int i;
16063
16064         dev_priv->active_crtcs = 0;
16065
16066         for_each_intel_crtc(dev, crtc) {
16067                 struct intel_crtc_state *crtc_state = crtc->config;
16068                 int pixclk = 0;
16069
16070                 __drm_atomic_helper_crtc_destroy_state(&crtc_state->base);
16071                 memset(crtc_state, 0, sizeof(*crtc_state));
16072                 crtc_state->base.crtc = &crtc->base;
16073
16074                 crtc_state->base.active = crtc_state->base.enable =
16075                         dev_priv->display.get_pipe_config(crtc, crtc_state);
16076
16077                 crtc->base.enabled = crtc_state->base.enable;
16078                 crtc->active = crtc_state->base.active;
16079
16080                 if (crtc_state->base.active) {
16081                         dev_priv->active_crtcs |= 1 << crtc->pipe;
16082
16083                         if (INTEL_GEN(dev_priv) >= 9 || IS_BROADWELL(dev_priv))
16084                                 pixclk = ilk_pipe_pixel_rate(crtc_state);
16085                         else if (IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv))
16086                                 pixclk = crtc_state->base.adjusted_mode.crtc_clock;
16087                         else
16088                                 WARN_ON(dev_priv->display.modeset_calc_cdclk);
16089
16090                         /* pixel rate mustn't exceed 95% of cdclk with IPS on BDW */
16091                         if (IS_BROADWELL(dev_priv) && crtc_state->ips_enabled)
16092                                 pixclk = DIV_ROUND_UP(pixclk * 100, 95);
16093                 }
16094
16095                 dev_priv->min_pixclk[crtc->pipe] = pixclk;
16096
16097                 readout_plane_state(crtc);
16098
16099                 DRM_DEBUG_KMS("[CRTC:%d:%s] hw state readout: %s\n",
16100                               crtc->base.base.id, crtc->base.name,
16101                               crtc->active ? "enabled" : "disabled");
16102         }
16103
16104         for (i = 0; i < dev_priv->num_shared_dpll; i++) {
16105                 struct intel_shared_dpll *pll = &dev_priv->shared_dplls[i];
16106
16107                 pll->on = pll->funcs.get_hw_state(dev_priv, pll,
16108                                                   &pll->config.hw_state);
16109                 pll->config.crtc_mask = 0;
16110                 for_each_intel_crtc(dev, crtc) {
16111                         if (crtc->active && crtc->config->shared_dpll == pll)
16112                                 pll->config.crtc_mask |= 1 << crtc->pipe;
16113                 }
16114                 pll->active_mask = pll->config.crtc_mask;
16115
16116                 DRM_DEBUG_KMS("%s hw state readout: crtc_mask 0x%08x, on %i\n",
16117                               pll->name, pll->config.crtc_mask, pll->on);
16118         }
16119
16120         for_each_intel_encoder(dev, encoder) {
16121                 pipe = 0;
16122
16123                 if (encoder->get_hw_state(encoder, &pipe)) {
16124                         crtc = to_intel_crtc(dev_priv->pipe_to_crtc_mapping[pipe]);
16125                         encoder->base.crtc = &crtc->base;
16126                         crtc->config->output_types |= 1 << encoder->type;
16127                         encoder->get_config(encoder, crtc->config);
16128                 } else {
16129                         encoder->base.crtc = NULL;
16130                 }
16131
16132                 DRM_DEBUG_KMS("[ENCODER:%d:%s] hw state readout: %s, pipe %c\n",
16133                               encoder->base.base.id,
16134                               encoder->base.name,
16135                               encoder->base.crtc ? "enabled" : "disabled",
16136                               pipe_name(pipe));
16137         }
16138
16139         for_each_intel_connector(dev, connector) {
16140                 if (connector->get_hw_state(connector)) {
16141                         connector->base.dpms = DRM_MODE_DPMS_ON;
16142
16143                         encoder = connector->encoder;
16144                         connector->base.encoder = &encoder->base;
16145
16146                         if (encoder->base.crtc &&
16147                             encoder->base.crtc->state->active) {
16148                                 /*
16149                                  * This has to be done during hardware readout
16150                                  * because anything calling .crtc_disable may
16151                                  * rely on the connector_mask being accurate.
16152                                  */
16153                                 encoder->base.crtc->state->connector_mask |=
16154                                         1 << drm_connector_index(&connector->base);
16155                                 encoder->base.crtc->state->encoder_mask |=
16156                                         1 << drm_encoder_index(&encoder->base);
16157                         }
16158
16159                 } else {
16160                         connector->base.dpms = DRM_MODE_DPMS_OFF;
16161                         connector->base.encoder = NULL;
16162                 }
16163                 DRM_DEBUG_KMS("[CONNECTOR:%d:%s] hw state readout: %s\n",
16164                               connector->base.base.id,
16165                               connector->base.name,
16166                               connector->base.encoder ? "enabled" : "disabled");
16167         }
16168
16169         for_each_intel_crtc(dev, crtc) {
16170                 crtc->base.hwmode = crtc->config->base.adjusted_mode;
16171
16172                 memset(&crtc->base.mode, 0, sizeof(crtc->base.mode));
16173                 if (crtc->base.state->active) {
16174                         intel_mode_from_pipe_config(&crtc->base.mode, crtc->config);
16175                         intel_mode_from_pipe_config(&crtc->base.state->adjusted_mode, crtc->config);
16176                         WARN_ON(drm_atomic_set_mode_for_crtc(crtc->base.state, &crtc->base.mode));
16177
16178                         /*
16179                          * The initial mode needs to be set in order to keep
16180                          * the atomic core happy. It wants a valid mode if the
16181                          * crtc's enabled, so we do the above call.
16182                          *
16183                          * At this point some state updated by the connectors
16184                          * in their ->detect() callback has not run yet, so
16185                          * no recalculation can be done yet.
16186                          *
16187                          * Even if we could do a recalculation and modeset
16188                          * right now it would cause a double modeset if
16189                          * fbdev or userspace chooses a different initial mode.
16190                          *
16191                          * If that happens, someone indicated they wanted a
16192                          * mode change, which means it's safe to do a full
16193                          * recalculation.
16194                          */
16195                         crtc->base.state->mode.private_flags = I915_MODE_FLAG_INHERITED;
16196
16197                         drm_calc_timestamping_constants(&crtc->base, &crtc->base.hwmode);
16198                         update_scanline_offset(crtc);
16199                 }
16200
16201                 intel_pipe_config_sanity_check(dev_priv, crtc->config);
16202         }
16203 }
16204
16205 /* Scan out the current hw modeset state,
16206  * and sanitizes it to the current state
16207  */
16208 static void
16209 intel_modeset_setup_hw_state(struct drm_device *dev)
16210 {
16211         struct drm_i915_private *dev_priv = to_i915(dev);
16212         enum pipe pipe;
16213         struct intel_crtc *crtc;
16214         struct intel_encoder *encoder;
16215         int i;
16216
16217         intel_modeset_readout_hw_state(dev);
16218
16219         /* HW state is read out, now we need to sanitize this mess. */
16220         for_each_intel_encoder(dev, encoder) {
16221                 intel_sanitize_encoder(encoder);
16222         }
16223
16224         for_each_pipe(dev_priv, pipe) {
16225                 crtc = to_intel_crtc(dev_priv->pipe_to_crtc_mapping[pipe]);
16226                 intel_sanitize_crtc(crtc);
16227                 intel_dump_pipe_config(crtc, crtc->config,
16228                                        "[setup_hw_state]");
16229         }
16230
16231         intel_modeset_update_connector_atomic_state(dev);
16232
16233         for (i = 0; i < dev_priv->num_shared_dpll; i++) {
16234                 struct intel_shared_dpll *pll = &dev_priv->shared_dplls[i];
16235
16236                 if (!pll->on || pll->active_mask)
16237                         continue;
16238
16239                 DRM_DEBUG_KMS("%s enabled but not in use, disabling\n", pll->name);
16240
16241                 pll->funcs.disable(dev_priv, pll);
16242                 pll->on = false;
16243         }
16244
16245         if (IS_VALLEYVIEW(dev) || IS_CHERRYVIEW(dev))
16246                 vlv_wm_get_hw_state(dev);
16247         else if (IS_GEN9(dev))
16248                 skl_wm_get_hw_state(dev);
16249         else if (HAS_PCH_SPLIT(dev))
16250                 ilk_wm_get_hw_state(dev);
16251
16252         for_each_intel_crtc(dev, crtc) {
16253                 unsigned long put_domains;
16254
16255                 put_domains = modeset_get_crtc_power_domains(&crtc->base, crtc->config);
16256                 if (WARN_ON(put_domains))
16257                         modeset_put_power_domains(dev_priv, put_domains);
16258         }
16259         intel_display_set_init_power(dev_priv, false);
16260
16261         intel_fbc_init_pipe_state(dev_priv);
16262 }
16263
16264 void intel_display_resume(struct drm_device *dev)
16265 {
16266         struct drm_i915_private *dev_priv = to_i915(dev);
16267         struct drm_atomic_state *state = dev_priv->modeset_restore_state;
16268         struct drm_modeset_acquire_ctx ctx;
16269         int ret;
16270
16271         dev_priv->modeset_restore_state = NULL;
16272         if (state)
16273                 state->acquire_ctx = &ctx;
16274
16275         /*
16276          * This is a cludge because with real atomic modeset mode_config.mutex
16277          * won't be taken. Unfortunately some probed state like
16278          * audio_codec_enable is still protected by mode_config.mutex, so lock
16279          * it here for now.
16280          */
16281         mutex_lock(&dev->mode_config.mutex);
16282         drm_modeset_acquire_init(&ctx, 0);
16283
16284         while (1) {
16285                 ret = drm_modeset_lock_all_ctx(dev, &ctx);
16286                 if (ret != -EDEADLK)
16287                         break;
16288
16289                 drm_modeset_backoff(&ctx);
16290         }
16291
16292         if (!ret)
16293                 ret = __intel_display_resume(dev, state);
16294
16295         drm_modeset_drop_locks(&ctx);
16296         drm_modeset_acquire_fini(&ctx);
16297         mutex_unlock(&dev->mode_config.mutex);
16298
16299         if (ret) {
16300                 DRM_ERROR("Restoring old state failed with %i\n", ret);
16301                 drm_atomic_state_free(state);
16302         }
16303 }
16304
16305 void intel_modeset_gem_init(struct drm_device *dev)
16306 {
16307         struct drm_i915_private *dev_priv = to_i915(dev);
16308         struct drm_crtc *c;
16309         struct drm_i915_gem_object *obj;
16310         int ret;
16311
16312         intel_init_gt_powersave(dev_priv);
16313
16314         intel_modeset_init_hw(dev);
16315
16316         intel_setup_overlay(dev_priv);
16317
16318         /*
16319          * Make sure any fbs we allocated at startup are properly
16320          * pinned & fenced.  When we do the allocation it's too early
16321          * for this.
16322          */
16323         for_each_crtc(dev, c) {
16324                 obj = intel_fb_obj(c->primary->fb);
16325                 if (obj == NULL)
16326                         continue;
16327
16328                 mutex_lock(&dev->struct_mutex);
16329                 ret = intel_pin_and_fence_fb_obj(c->primary->fb,
16330                                                  c->primary->state->rotation);
16331                 mutex_unlock(&dev->struct_mutex);
16332                 if (ret) {
16333                         DRM_ERROR("failed to pin boot fb on pipe %d\n",
16334                                   to_intel_crtc(c)->pipe);
16335                         drm_framebuffer_unreference(c->primary->fb);
16336                         c->primary->fb = NULL;
16337                         c->primary->crtc = c->primary->state->crtc = NULL;
16338                         update_state_fb(c->primary);
16339                         c->state->plane_mask &= ~(1 << drm_plane_index(c->primary));
16340                 }
16341         }
16342 }
16343
16344 int intel_connector_register(struct drm_connector *connector)
16345 {
16346         struct intel_connector *intel_connector = to_intel_connector(connector);
16347         int ret;
16348
16349         ret = intel_backlight_device_register(intel_connector);
16350         if (ret)
16351                 goto err;
16352
16353         return 0;
16354
16355 err:
16356         return ret;
16357 }
16358
16359 void intel_connector_unregister(struct drm_connector *connector)
16360 {
16361         struct intel_connector *intel_connector = to_intel_connector(connector);
16362
16363         intel_backlight_device_unregister(intel_connector);
16364         intel_panel_destroy_backlight(connector);
16365 }
16366
16367 void intel_modeset_cleanup(struct drm_device *dev)
16368 {
16369         struct drm_i915_private *dev_priv = to_i915(dev);
16370
16371         intel_disable_gt_powersave(dev_priv);
16372
16373         /*
16374          * Interrupts and polling as the first thing to avoid creating havoc.
16375          * Too much stuff here (turning of connectors, ...) would
16376          * experience fancy races otherwise.
16377          */
16378         intel_irq_uninstall(dev_priv);
16379
16380         /*
16381          * Due to the hpd irq storm handling the hotplug work can re-arm the
16382          * poll handlers. Hence disable polling after hpd handling is shut down.
16383          */
16384         drm_kms_helper_poll_fini(dev);
16385
16386         intel_unregister_dsm_handler();
16387
16388         intel_fbc_global_disable(dev_priv);
16389
16390         /* flush any delayed tasks or pending work */
16391         flush_scheduled_work();
16392
16393         drm_mode_config_cleanup(dev);
16394
16395         intel_cleanup_overlay(dev_priv);
16396
16397         intel_cleanup_gt_powersave(dev_priv);
16398
16399         intel_teardown_gmbus(dev);
16400 }
16401
16402 void intel_connector_attach_encoder(struct intel_connector *connector,
16403                                     struct intel_encoder *encoder)
16404 {
16405         connector->encoder = encoder;
16406         drm_mode_connector_attach_encoder(&connector->base,
16407                                           &encoder->base);
16408 }
16409
16410 /*
16411  * set vga decode state - true == enable VGA decode
16412  */
16413 int intel_modeset_vga_set_state(struct drm_device *dev, bool state)
16414 {
16415         struct drm_i915_private *dev_priv = to_i915(dev);
16416         unsigned reg = INTEL_INFO(dev)->gen >= 6 ? SNB_GMCH_CTRL : INTEL_GMCH_CTRL;
16417         u16 gmch_ctrl;
16418
16419         if (pci_read_config_word(dev_priv->bridge_dev, reg, &gmch_ctrl)) {
16420                 DRM_ERROR("failed to read control word\n");
16421                 return -EIO;
16422         }
16423
16424         if (!!(gmch_ctrl & INTEL_GMCH_VGA_DISABLE) == !state)
16425                 return 0;
16426
16427         if (state)
16428                 gmch_ctrl &= ~INTEL_GMCH_VGA_DISABLE;
16429         else
16430                 gmch_ctrl |= INTEL_GMCH_VGA_DISABLE;
16431
16432         if (pci_write_config_word(dev_priv->bridge_dev, reg, gmch_ctrl)) {
16433                 DRM_ERROR("failed to write control word\n");
16434                 return -EIO;
16435         }
16436
16437         return 0;
16438 }
16439
16440 struct intel_display_error_state {
16441
16442         u32 power_well_driver;
16443
16444         int num_transcoders;
16445
16446         struct intel_cursor_error_state {
16447                 u32 control;
16448                 u32 position;
16449                 u32 base;
16450                 u32 size;
16451         } cursor[I915_MAX_PIPES];
16452
16453         struct intel_pipe_error_state {
16454                 bool power_domain_on;
16455                 u32 source;
16456                 u32 stat;
16457         } pipe[I915_MAX_PIPES];
16458
16459         struct intel_plane_error_state {
16460                 u32 control;
16461                 u32 stride;
16462                 u32 size;
16463                 u32 pos;
16464                 u32 addr;
16465                 u32 surface;
16466                 u32 tile_offset;
16467         } plane[I915_MAX_PIPES];
16468
16469         struct intel_transcoder_error_state {
16470                 bool power_domain_on;
16471                 enum transcoder cpu_transcoder;
16472
16473                 u32 conf;
16474
16475                 u32 htotal;
16476                 u32 hblank;
16477                 u32 hsync;
16478                 u32 vtotal;
16479                 u32 vblank;
16480                 u32 vsync;
16481         } transcoder[4];
16482 };
16483
16484 struct intel_display_error_state *
16485 intel_display_capture_error_state(struct drm_i915_private *dev_priv)
16486 {
16487         struct intel_display_error_state *error;
16488         int transcoders[] = {
16489                 TRANSCODER_A,
16490                 TRANSCODER_B,
16491                 TRANSCODER_C,
16492                 TRANSCODER_EDP,
16493         };
16494         int i;
16495
16496         if (INTEL_INFO(dev_priv)->num_pipes == 0)
16497                 return NULL;
16498
16499         error = kzalloc(sizeof(*error), GFP_ATOMIC);
16500         if (error == NULL)
16501                 return NULL;
16502
16503         if (IS_HASWELL(dev_priv) || IS_BROADWELL(dev_priv))
16504                 error->power_well_driver = I915_READ(HSW_PWR_WELL_DRIVER);
16505
16506         for_each_pipe(dev_priv, i) {
16507                 error->pipe[i].power_domain_on =
16508                         __intel_display_power_is_enabled(dev_priv,
16509                                                          POWER_DOMAIN_PIPE(i));
16510                 if (!error->pipe[i].power_domain_on)
16511                         continue;
16512
16513                 error->cursor[i].control = I915_READ(CURCNTR(i));
16514                 error->cursor[i].position = I915_READ(CURPOS(i));
16515                 error->cursor[i].base = I915_READ(CURBASE(i));
16516
16517                 error->plane[i].control = I915_READ(DSPCNTR(i));
16518                 error->plane[i].stride = I915_READ(DSPSTRIDE(i));
16519                 if (INTEL_GEN(dev_priv) <= 3) {
16520                         error->plane[i].size = I915_READ(DSPSIZE(i));
16521                         error->plane[i].pos = I915_READ(DSPPOS(i));
16522                 }
16523                 if (INTEL_GEN(dev_priv) <= 7 && !IS_HASWELL(dev_priv))
16524                         error->plane[i].addr = I915_READ(DSPADDR(i));
16525                 if (INTEL_GEN(dev_priv) >= 4) {
16526                         error->plane[i].surface = I915_READ(DSPSURF(i));
16527                         error->plane[i].tile_offset = I915_READ(DSPTILEOFF(i));
16528                 }
16529
16530                 error->pipe[i].source = I915_READ(PIPESRC(i));
16531
16532                 if (HAS_GMCH_DISPLAY(dev_priv))
16533                         error->pipe[i].stat = I915_READ(PIPESTAT(i));
16534         }
16535
16536         /* Note: this does not include DSI transcoders. */
16537         error->num_transcoders = INTEL_INFO(dev_priv)->num_pipes;
16538         if (HAS_DDI(dev_priv))
16539                 error->num_transcoders++; /* Account for eDP. */
16540
16541         for (i = 0; i < error->num_transcoders; i++) {
16542                 enum transcoder cpu_transcoder = transcoders[i];
16543
16544                 error->transcoder[i].power_domain_on =
16545                         __intel_display_power_is_enabled(dev_priv,
16546                                 POWER_DOMAIN_TRANSCODER(cpu_transcoder));
16547                 if (!error->transcoder[i].power_domain_on)
16548                         continue;
16549
16550                 error->transcoder[i].cpu_transcoder = cpu_transcoder;
16551
16552                 error->transcoder[i].conf = I915_READ(PIPECONF(cpu_transcoder));
16553                 error->transcoder[i].htotal = I915_READ(HTOTAL(cpu_transcoder));
16554                 error->transcoder[i].hblank = I915_READ(HBLANK(cpu_transcoder));
16555                 error->transcoder[i].hsync = I915_READ(HSYNC(cpu_transcoder));
16556                 error->transcoder[i].vtotal = I915_READ(VTOTAL(cpu_transcoder));
16557                 error->transcoder[i].vblank = I915_READ(VBLANK(cpu_transcoder));
16558                 error->transcoder[i].vsync = I915_READ(VSYNC(cpu_transcoder));
16559         }
16560
16561         return error;
16562 }
16563
16564 #define err_printf(e, ...) i915_error_printf(e, __VA_ARGS__)
16565
16566 void
16567 intel_display_print_error_state(struct drm_i915_error_state_buf *m,
16568                                 struct drm_device *dev,
16569                                 struct intel_display_error_state *error)
16570 {
16571         struct drm_i915_private *dev_priv = to_i915(dev);
16572         int i;
16573
16574         if (!error)
16575                 return;
16576
16577         err_printf(m, "Num Pipes: %d\n", INTEL_INFO(dev)->num_pipes);
16578         if (IS_HASWELL(dev) || IS_BROADWELL(dev))
16579                 err_printf(m, "PWR_WELL_CTL2: %08x\n",
16580                            error->power_well_driver);
16581         for_each_pipe(dev_priv, i) {
16582                 err_printf(m, "Pipe [%d]:\n", i);
16583                 err_printf(m, "  Power: %s\n",
16584                            onoff(error->pipe[i].power_domain_on));
16585                 err_printf(m, "  SRC: %08x\n", error->pipe[i].source);
16586                 err_printf(m, "  STAT: %08x\n", error->pipe[i].stat);
16587
16588                 err_printf(m, "Plane [%d]:\n", i);
16589                 err_printf(m, "  CNTR: %08x\n", error->plane[i].control);
16590                 err_printf(m, "  STRIDE: %08x\n", error->plane[i].stride);
16591                 if (INTEL_INFO(dev)->gen <= 3) {
16592                         err_printf(m, "  SIZE: %08x\n", error->plane[i].size);
16593                         err_printf(m, "  POS: %08x\n", error->plane[i].pos);
16594                 }
16595                 if (INTEL_INFO(dev)->gen <= 7 && !IS_HASWELL(dev))
16596                         err_printf(m, "  ADDR: %08x\n", error->plane[i].addr);
16597                 if (INTEL_INFO(dev)->gen >= 4) {
16598                         err_printf(m, "  SURF: %08x\n", error->plane[i].surface);
16599                         err_printf(m, "  TILEOFF: %08x\n", error->plane[i].tile_offset);
16600                 }
16601
16602                 err_printf(m, "Cursor [%d]:\n", i);
16603                 err_printf(m, "  CNTR: %08x\n", error->cursor[i].control);
16604                 err_printf(m, "  POS: %08x\n", error->cursor[i].position);
16605                 err_printf(m, "  BASE: %08x\n", error->cursor[i].base);
16606         }
16607
16608         for (i = 0; i < error->num_transcoders; i++) {
16609                 err_printf(m, "CPU transcoder: %s\n",
16610                            transcoder_name(error->transcoder[i].cpu_transcoder));
16611                 err_printf(m, "  Power: %s\n",
16612                            onoff(error->transcoder[i].power_domain_on));
16613                 err_printf(m, "  CONF: %08x\n", error->transcoder[i].conf);
16614                 err_printf(m, "  HTOTAL: %08x\n", error->transcoder[i].htotal);
16615                 err_printf(m, "  HBLANK: %08x\n", error->transcoder[i].hblank);
16616                 err_printf(m, "  HSYNC: %08x\n", error->transcoder[i].hsync);
16617                 err_printf(m, "  VTOTAL: %08x\n", error->transcoder[i].vtotal);
16618                 err_printf(m, "  VBLANK: %08x\n", error->transcoder[i].vblank);
16619                 err_printf(m, "  VSYNC: %08x\n", error->transcoder[i].vsync);
16620         }
16621 }