drm/i915: Make IS_IVYBRIDGE only take dev_priv
[sfrench/cifs-2.6.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, enum pipe pipe)
1191 {
1192         i915_reg_t pp_reg;
1193         u32 val;
1194         enum pipe panel_pipe = PIPE_A;
1195         bool locked = true;
1196
1197         if (WARN_ON(HAS_DDI(dev_priv)))
1198                 return;
1199
1200         if (HAS_PCH_SPLIT(dev_priv)) {
1201                 u32 port_sel;
1202
1203                 pp_reg = PP_CONTROL(0);
1204                 port_sel = I915_READ(PP_ON_DELAYS(0)) & PANEL_PORT_SELECT_MASK;
1205
1206                 if (port_sel == PANEL_PORT_SELECT_LVDS &&
1207                     I915_READ(PCH_LVDS) & LVDS_PIPEB_SELECT)
1208                         panel_pipe = PIPE_B;
1209                 /* XXX: else fix for eDP */
1210         } else if (IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv)) {
1211                 /* presumably write lock depends on pipe, not port select */
1212                 pp_reg = PP_CONTROL(pipe);
1213                 panel_pipe = pipe;
1214         } else {
1215                 pp_reg = PP_CONTROL(0);
1216                 if (I915_READ(LVDS) & LVDS_PIPEB_SELECT)
1217                         panel_pipe = PIPE_B;
1218         }
1219
1220         val = I915_READ(pp_reg);
1221         if (!(val & PANEL_POWER_ON) ||
1222             ((val & PANEL_UNLOCK_MASK) == PANEL_UNLOCK_REGS))
1223                 locked = false;
1224
1225         I915_STATE_WARN(panel_pipe == pipe && locked,
1226              "panel assertion failure, pipe %c regs locked\n",
1227              pipe_name(pipe));
1228 }
1229
1230 static void assert_cursor(struct drm_i915_private *dev_priv,
1231                           enum pipe pipe, bool state)
1232 {
1233         bool cur_state;
1234
1235         if (IS_845G(dev_priv) || IS_I865G(dev_priv))
1236                 cur_state = I915_READ(CURCNTR(PIPE_A)) & CURSOR_ENABLE;
1237         else
1238                 cur_state = I915_READ(CURCNTR(pipe)) & CURSOR_MODE;
1239
1240         I915_STATE_WARN(cur_state != state,
1241              "cursor on pipe %c assertion failure (expected %s, current %s)\n",
1242                         pipe_name(pipe), onoff(state), onoff(cur_state));
1243 }
1244 #define assert_cursor_enabled(d, p) assert_cursor(d, p, true)
1245 #define assert_cursor_disabled(d, p) assert_cursor(d, p, false)
1246
1247 void assert_pipe(struct drm_i915_private *dev_priv,
1248                  enum pipe pipe, bool state)
1249 {
1250         bool cur_state;
1251         enum transcoder cpu_transcoder = intel_pipe_to_cpu_transcoder(dev_priv,
1252                                                                       pipe);
1253         enum intel_display_power_domain power_domain;
1254
1255         /* if we need the pipe quirk it must be always on */
1256         if ((pipe == PIPE_A && dev_priv->quirks & QUIRK_PIPEA_FORCE) ||
1257             (pipe == PIPE_B && dev_priv->quirks & QUIRK_PIPEB_FORCE))
1258                 state = true;
1259
1260         power_domain = POWER_DOMAIN_TRANSCODER(cpu_transcoder);
1261         if (intel_display_power_get_if_enabled(dev_priv, power_domain)) {
1262                 u32 val = I915_READ(PIPECONF(cpu_transcoder));
1263                 cur_state = !!(val & PIPECONF_ENABLE);
1264
1265                 intel_display_power_put(dev_priv, power_domain);
1266         } else {
1267                 cur_state = false;
1268         }
1269
1270         I915_STATE_WARN(cur_state != state,
1271              "pipe %c assertion failure (expected %s, current %s)\n",
1272                         pipe_name(pipe), onoff(state), onoff(cur_state));
1273 }
1274
1275 static void assert_plane(struct drm_i915_private *dev_priv,
1276                          enum plane plane, bool state)
1277 {
1278         u32 val;
1279         bool cur_state;
1280
1281         val = I915_READ(DSPCNTR(plane));
1282         cur_state = !!(val & DISPLAY_PLANE_ENABLE);
1283         I915_STATE_WARN(cur_state != state,
1284              "plane %c assertion failure (expected %s, current %s)\n",
1285                         plane_name(plane), onoff(state), onoff(cur_state));
1286 }
1287
1288 #define assert_plane_enabled(d, p) assert_plane(d, p, true)
1289 #define assert_plane_disabled(d, p) assert_plane(d, p, false)
1290
1291 static void assert_planes_disabled(struct drm_i915_private *dev_priv,
1292                                    enum pipe pipe)
1293 {
1294         struct drm_device *dev = &dev_priv->drm;
1295         int i;
1296
1297         /* Primary planes are fixed to pipes on gen4+ */
1298         if (INTEL_INFO(dev)->gen >= 4) {
1299                 u32 val = I915_READ(DSPCNTR(pipe));
1300                 I915_STATE_WARN(val & DISPLAY_PLANE_ENABLE,
1301                      "plane %c assertion failure, should be disabled but not\n",
1302                      plane_name(pipe));
1303                 return;
1304         }
1305
1306         /* Need to check both planes against the pipe */
1307         for_each_pipe(dev_priv, i) {
1308                 u32 val = I915_READ(DSPCNTR(i));
1309                 enum pipe cur_pipe = (val & DISPPLANE_SEL_PIPE_MASK) >>
1310                         DISPPLANE_SEL_PIPE_SHIFT;
1311                 I915_STATE_WARN((val & DISPLAY_PLANE_ENABLE) && pipe == cur_pipe,
1312                      "plane %c assertion failure, should be off on pipe %c but is still active\n",
1313                      plane_name(i), pipe_name(pipe));
1314         }
1315 }
1316
1317 static void assert_sprites_disabled(struct drm_i915_private *dev_priv,
1318                                     enum pipe pipe)
1319 {
1320         struct drm_device *dev = &dev_priv->drm;
1321         int sprite;
1322
1323         if (INTEL_INFO(dev)->gen >= 9) {
1324                 for_each_sprite(dev_priv, pipe, sprite) {
1325                         u32 val = I915_READ(PLANE_CTL(pipe, sprite));
1326                         I915_STATE_WARN(val & PLANE_CTL_ENABLE,
1327                              "plane %d assertion failure, should be off on pipe %c but is still active\n",
1328                              sprite, pipe_name(pipe));
1329                 }
1330         } else if (IS_VALLEYVIEW(dev) || IS_CHERRYVIEW(dev)) {
1331                 for_each_sprite(dev_priv, pipe, sprite) {
1332                         u32 val = I915_READ(SPCNTR(pipe, sprite));
1333                         I915_STATE_WARN(val & SP_ENABLE,
1334                              "sprite %c assertion failure, should be off on pipe %c but is still active\n",
1335                              sprite_name(pipe, sprite), pipe_name(pipe));
1336                 }
1337         } else if (INTEL_INFO(dev)->gen >= 7) {
1338                 u32 val = I915_READ(SPRCTL(pipe));
1339                 I915_STATE_WARN(val & SPRITE_ENABLE,
1340                      "sprite %c assertion failure, should be off on pipe %c but is still active\n",
1341                      plane_name(pipe), pipe_name(pipe));
1342         } else if (INTEL_INFO(dev)->gen >= 5) {
1343                 u32 val = I915_READ(DVSCNTR(pipe));
1344                 I915_STATE_WARN(val & DVS_ENABLE,
1345                      "sprite %c assertion failure, should be off on pipe %c but is still active\n",
1346                      plane_name(pipe), pipe_name(pipe));
1347         }
1348 }
1349
1350 static void assert_vblank_disabled(struct drm_crtc *crtc)
1351 {
1352         if (I915_STATE_WARN_ON(drm_crtc_vblank_get(crtc) == 0))
1353                 drm_crtc_vblank_put(crtc);
1354 }
1355
1356 void assert_pch_transcoder_disabled(struct drm_i915_private *dev_priv,
1357                                     enum pipe pipe)
1358 {
1359         u32 val;
1360         bool enabled;
1361
1362         val = I915_READ(PCH_TRANSCONF(pipe));
1363         enabled = !!(val & TRANS_ENABLE);
1364         I915_STATE_WARN(enabled,
1365              "transcoder assertion failed, should be off on pipe %c but is still active\n",
1366              pipe_name(pipe));
1367 }
1368
1369 static bool dp_pipe_enabled(struct drm_i915_private *dev_priv,
1370                             enum pipe pipe, u32 port_sel, u32 val)
1371 {
1372         if ((val & DP_PORT_EN) == 0)
1373                 return false;
1374
1375         if (HAS_PCH_CPT(dev_priv)) {
1376                 u32 trans_dp_ctl = I915_READ(TRANS_DP_CTL(pipe));
1377                 if ((trans_dp_ctl & TRANS_DP_PORT_SEL_MASK) != port_sel)
1378                         return false;
1379         } else if (IS_CHERRYVIEW(dev_priv)) {
1380                 if ((val & DP_PIPE_MASK_CHV) != DP_PIPE_SELECT_CHV(pipe))
1381                         return false;
1382         } else {
1383                 if ((val & DP_PIPE_MASK) != (pipe << 30))
1384                         return false;
1385         }
1386         return true;
1387 }
1388
1389 static bool hdmi_pipe_enabled(struct drm_i915_private *dev_priv,
1390                               enum pipe pipe, u32 val)
1391 {
1392         if ((val & SDVO_ENABLE) == 0)
1393                 return false;
1394
1395         if (HAS_PCH_CPT(dev_priv)) {
1396                 if ((val & SDVO_PIPE_SEL_MASK_CPT) != SDVO_PIPE_SEL_CPT(pipe))
1397                         return false;
1398         } else if (IS_CHERRYVIEW(dev_priv)) {
1399                 if ((val & SDVO_PIPE_SEL_MASK_CHV) != SDVO_PIPE_SEL_CHV(pipe))
1400                         return false;
1401         } else {
1402                 if ((val & SDVO_PIPE_SEL_MASK) != SDVO_PIPE_SEL(pipe))
1403                         return false;
1404         }
1405         return true;
1406 }
1407
1408 static bool lvds_pipe_enabled(struct drm_i915_private *dev_priv,
1409                               enum pipe pipe, u32 val)
1410 {
1411         if ((val & LVDS_PORT_EN) == 0)
1412                 return false;
1413
1414         if (HAS_PCH_CPT(dev_priv)) {
1415                 if ((val & PORT_TRANS_SEL_MASK) != PORT_TRANS_SEL_CPT(pipe))
1416                         return false;
1417         } else {
1418                 if ((val & LVDS_PIPE_MASK) != LVDS_PIPE(pipe))
1419                         return false;
1420         }
1421         return true;
1422 }
1423
1424 static bool adpa_pipe_enabled(struct drm_i915_private *dev_priv,
1425                               enum pipe pipe, u32 val)
1426 {
1427         if ((val & ADPA_DAC_ENABLE) == 0)
1428                 return false;
1429         if (HAS_PCH_CPT(dev_priv)) {
1430                 if ((val & PORT_TRANS_SEL_MASK) != PORT_TRANS_SEL_CPT(pipe))
1431                         return false;
1432         } else {
1433                 if ((val & ADPA_PIPE_SELECT_MASK) != ADPA_PIPE_SELECT(pipe))
1434                         return false;
1435         }
1436         return true;
1437 }
1438
1439 static void assert_pch_dp_disabled(struct drm_i915_private *dev_priv,
1440                                    enum pipe pipe, i915_reg_t reg,
1441                                    u32 port_sel)
1442 {
1443         u32 val = I915_READ(reg);
1444         I915_STATE_WARN(dp_pipe_enabled(dev_priv, pipe, port_sel, val),
1445              "PCH DP (0x%08x) enabled on transcoder %c, should be disabled\n",
1446              i915_mmio_reg_offset(reg), pipe_name(pipe));
1447
1448         I915_STATE_WARN(HAS_PCH_IBX(dev_priv) && (val & DP_PORT_EN) == 0
1449              && (val & DP_PIPEB_SELECT),
1450              "IBX PCH dp port still using transcoder B\n");
1451 }
1452
1453 static void assert_pch_hdmi_disabled(struct drm_i915_private *dev_priv,
1454                                      enum pipe pipe, i915_reg_t reg)
1455 {
1456         u32 val = I915_READ(reg);
1457         I915_STATE_WARN(hdmi_pipe_enabled(dev_priv, pipe, val),
1458              "PCH HDMI (0x%08x) enabled on transcoder %c, should be disabled\n",
1459              i915_mmio_reg_offset(reg), pipe_name(pipe));
1460
1461         I915_STATE_WARN(HAS_PCH_IBX(dev_priv) && (val & SDVO_ENABLE) == 0
1462              && (val & SDVO_PIPE_B_SELECT),
1463              "IBX PCH hdmi port still using transcoder B\n");
1464 }
1465
1466 static void assert_pch_ports_disabled(struct drm_i915_private *dev_priv,
1467                                       enum pipe pipe)
1468 {
1469         u32 val;
1470
1471         assert_pch_dp_disabled(dev_priv, pipe, PCH_DP_B, TRANS_DP_PORT_SEL_B);
1472         assert_pch_dp_disabled(dev_priv, pipe, PCH_DP_C, TRANS_DP_PORT_SEL_C);
1473         assert_pch_dp_disabled(dev_priv, pipe, PCH_DP_D, TRANS_DP_PORT_SEL_D);
1474
1475         val = I915_READ(PCH_ADPA);
1476         I915_STATE_WARN(adpa_pipe_enabled(dev_priv, pipe, val),
1477              "PCH VGA enabled on transcoder %c, should be disabled\n",
1478              pipe_name(pipe));
1479
1480         val = I915_READ(PCH_LVDS);
1481         I915_STATE_WARN(lvds_pipe_enabled(dev_priv, pipe, val),
1482              "PCH LVDS enabled on transcoder %c, should be disabled\n",
1483              pipe_name(pipe));
1484
1485         assert_pch_hdmi_disabled(dev_priv, pipe, PCH_HDMIB);
1486         assert_pch_hdmi_disabled(dev_priv, pipe, PCH_HDMIC);
1487         assert_pch_hdmi_disabled(dev_priv, pipe, PCH_HDMID);
1488 }
1489
1490 static void _vlv_enable_pll(struct intel_crtc *crtc,
1491                             const struct intel_crtc_state *pipe_config)
1492 {
1493         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
1494         enum pipe pipe = crtc->pipe;
1495
1496         I915_WRITE(DPLL(pipe), pipe_config->dpll_hw_state.dpll);
1497         POSTING_READ(DPLL(pipe));
1498         udelay(150);
1499
1500         if (intel_wait_for_register(dev_priv,
1501                                     DPLL(pipe),
1502                                     DPLL_LOCK_VLV,
1503                                     DPLL_LOCK_VLV,
1504                                     1))
1505                 DRM_ERROR("DPLL %d failed to lock\n", pipe);
1506 }
1507
1508 static void vlv_enable_pll(struct intel_crtc *crtc,
1509                            const struct intel_crtc_state *pipe_config)
1510 {
1511         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
1512         enum pipe pipe = crtc->pipe;
1513
1514         assert_pipe_disabled(dev_priv, pipe);
1515
1516         /* PLL is protected by panel, make sure we can write it */
1517         assert_panel_unlocked(dev_priv, pipe);
1518
1519         if (pipe_config->dpll_hw_state.dpll & DPLL_VCO_ENABLE)
1520                 _vlv_enable_pll(crtc, pipe_config);
1521
1522         I915_WRITE(DPLL_MD(pipe), pipe_config->dpll_hw_state.dpll_md);
1523         POSTING_READ(DPLL_MD(pipe));
1524 }
1525
1526
1527 static void _chv_enable_pll(struct intel_crtc *crtc,
1528                             const struct intel_crtc_state *pipe_config)
1529 {
1530         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
1531         enum pipe pipe = crtc->pipe;
1532         enum dpio_channel port = vlv_pipe_to_channel(pipe);
1533         u32 tmp;
1534
1535         mutex_lock(&dev_priv->sb_lock);
1536
1537         /* Enable back the 10bit clock to display controller */
1538         tmp = vlv_dpio_read(dev_priv, pipe, CHV_CMN_DW14(port));
1539         tmp |= DPIO_DCLKP_EN;
1540         vlv_dpio_write(dev_priv, pipe, CHV_CMN_DW14(port), tmp);
1541
1542         mutex_unlock(&dev_priv->sb_lock);
1543
1544         /*
1545          * Need to wait > 100ns between dclkp clock enable bit and PLL enable.
1546          */
1547         udelay(1);
1548
1549         /* Enable PLL */
1550         I915_WRITE(DPLL(pipe), pipe_config->dpll_hw_state.dpll);
1551
1552         /* Check PLL is locked */
1553         if (intel_wait_for_register(dev_priv,
1554                                     DPLL(pipe), DPLL_LOCK_VLV, DPLL_LOCK_VLV,
1555                                     1))
1556                 DRM_ERROR("PLL %d failed to lock\n", pipe);
1557 }
1558
1559 static void chv_enable_pll(struct intel_crtc *crtc,
1560                            const struct intel_crtc_state *pipe_config)
1561 {
1562         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
1563         enum pipe pipe = crtc->pipe;
1564
1565         assert_pipe_disabled(dev_priv, pipe);
1566
1567         /* PLL is protected by panel, make sure we can write it */
1568         assert_panel_unlocked(dev_priv, pipe);
1569
1570         if (pipe_config->dpll_hw_state.dpll & DPLL_VCO_ENABLE)
1571                 _chv_enable_pll(crtc, pipe_config);
1572
1573         if (pipe != PIPE_A) {
1574                 /*
1575                  * WaPixelRepeatModeFixForC0:chv
1576                  *
1577                  * DPLLCMD is AWOL. Use chicken bits to propagate
1578                  * the value from DPLLBMD to either pipe B or C.
1579                  */
1580                 I915_WRITE(CBR4_VLV, pipe == PIPE_B ? CBR_DPLLBMD_PIPE_B : CBR_DPLLBMD_PIPE_C);
1581                 I915_WRITE(DPLL_MD(PIPE_B), pipe_config->dpll_hw_state.dpll_md);
1582                 I915_WRITE(CBR4_VLV, 0);
1583                 dev_priv->chv_dpll_md[pipe] = pipe_config->dpll_hw_state.dpll_md;
1584
1585                 /*
1586                  * DPLLB VGA mode also seems to cause problems.
1587                  * We should always have it disabled.
1588                  */
1589                 WARN_ON((I915_READ(DPLL(PIPE_B)) & DPLL_VGA_MODE_DIS) == 0);
1590         } else {
1591                 I915_WRITE(DPLL_MD(pipe), pipe_config->dpll_hw_state.dpll_md);
1592                 POSTING_READ(DPLL_MD(pipe));
1593         }
1594 }
1595
1596 static int intel_num_dvo_pipes(struct drm_device *dev)
1597 {
1598         struct intel_crtc *crtc;
1599         int count = 0;
1600
1601         for_each_intel_crtc(dev, crtc) {
1602                 count += crtc->base.state->active &&
1603                         intel_crtc_has_type(crtc->config, INTEL_OUTPUT_DVO);
1604         }
1605
1606         return count;
1607 }
1608
1609 static void i9xx_enable_pll(struct intel_crtc *crtc)
1610 {
1611         struct drm_device *dev = crtc->base.dev;
1612         struct drm_i915_private *dev_priv = to_i915(dev);
1613         i915_reg_t reg = DPLL(crtc->pipe);
1614         u32 dpll = crtc->config->dpll_hw_state.dpll;
1615
1616         assert_pipe_disabled(dev_priv, crtc->pipe);
1617
1618         /* PLL is protected by panel, make sure we can write it */
1619         if (IS_MOBILE(dev_priv) && !IS_I830(dev_priv))
1620                 assert_panel_unlocked(dev_priv, crtc->pipe);
1621
1622         /* Enable DVO 2x clock on both PLLs if necessary */
1623         if (IS_I830(dev_priv) && intel_num_dvo_pipes(dev) > 0) {
1624                 /*
1625                  * It appears to be important that we don't enable this
1626                  * for the current pipe before otherwise configuring the
1627                  * PLL. No idea how this should be handled if multiple
1628                  * DVO outputs are enabled simultaneosly.
1629                  */
1630                 dpll |= DPLL_DVO_2X_MODE;
1631                 I915_WRITE(DPLL(!crtc->pipe),
1632                            I915_READ(DPLL(!crtc->pipe)) | DPLL_DVO_2X_MODE);
1633         }
1634
1635         /*
1636          * Apparently we need to have VGA mode enabled prior to changing
1637          * the P1/P2 dividers. Otherwise the DPLL will keep using the old
1638          * dividers, even though the register value does change.
1639          */
1640         I915_WRITE(reg, 0);
1641
1642         I915_WRITE(reg, dpll);
1643
1644         /* Wait for the clocks to stabilize. */
1645         POSTING_READ(reg);
1646         udelay(150);
1647
1648         if (INTEL_INFO(dev)->gen >= 4) {
1649                 I915_WRITE(DPLL_MD(crtc->pipe),
1650                            crtc->config->dpll_hw_state.dpll_md);
1651         } else {
1652                 /* The pixel multiplier can only be updated once the
1653                  * DPLL is enabled and the clocks are stable.
1654                  *
1655                  * So write it again.
1656                  */
1657                 I915_WRITE(reg, dpll);
1658         }
1659
1660         /* We do this three times for luck */
1661         I915_WRITE(reg, dpll);
1662         POSTING_READ(reg);
1663         udelay(150); /* wait for warmup */
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 }
1671
1672 /**
1673  * i9xx_disable_pll - disable a PLL
1674  * @dev_priv: i915 private structure
1675  * @pipe: pipe PLL to disable
1676  *
1677  * Disable the PLL for @pipe, making sure the pipe is off first.
1678  *
1679  * Note!  This is for pre-ILK only.
1680  */
1681 static void i9xx_disable_pll(struct intel_crtc *crtc)
1682 {
1683         struct drm_device *dev = crtc->base.dev;
1684         struct drm_i915_private *dev_priv = to_i915(dev);
1685         enum pipe pipe = crtc->pipe;
1686
1687         /* Disable DVO 2x clock on both PLLs if necessary */
1688         if (IS_I830(dev_priv) &&
1689             intel_crtc_has_type(crtc->config, INTEL_OUTPUT_DVO) &&
1690             !intel_num_dvo_pipes(dev)) {
1691                 I915_WRITE(DPLL(PIPE_B),
1692                            I915_READ(DPLL(PIPE_B)) & ~DPLL_DVO_2X_MODE);
1693                 I915_WRITE(DPLL(PIPE_A),
1694                            I915_READ(DPLL(PIPE_A)) & ~DPLL_DVO_2X_MODE);
1695         }
1696
1697         /* Don't disable pipe or pipe PLLs if needed */
1698         if ((pipe == PIPE_A && dev_priv->quirks & QUIRK_PIPEA_FORCE) ||
1699             (pipe == PIPE_B && dev_priv->quirks & QUIRK_PIPEB_FORCE))
1700                 return;
1701
1702         /* Make sure the pipe isn't still relying on us */
1703         assert_pipe_disabled(dev_priv, pipe);
1704
1705         I915_WRITE(DPLL(pipe), DPLL_VGA_MODE_DIS);
1706         POSTING_READ(DPLL(pipe));
1707 }
1708
1709 static void vlv_disable_pll(struct drm_i915_private *dev_priv, enum pipe pipe)
1710 {
1711         u32 val;
1712
1713         /* Make sure the pipe isn't still relying on us */
1714         assert_pipe_disabled(dev_priv, pipe);
1715
1716         val = DPLL_INTEGRATED_REF_CLK_VLV |
1717                 DPLL_REF_CLK_ENABLE_VLV | DPLL_VGA_MODE_DIS;
1718         if (pipe != PIPE_A)
1719                 val |= DPLL_INTEGRATED_CRI_CLK_VLV;
1720
1721         I915_WRITE(DPLL(pipe), val);
1722         POSTING_READ(DPLL(pipe));
1723 }
1724
1725 static void chv_disable_pll(struct drm_i915_private *dev_priv, enum pipe pipe)
1726 {
1727         enum dpio_channel port = vlv_pipe_to_channel(pipe);
1728         u32 val;
1729
1730         /* Make sure the pipe isn't still relying on us */
1731         assert_pipe_disabled(dev_priv, pipe);
1732
1733         val = DPLL_SSC_REF_CLK_CHV |
1734                 DPLL_REF_CLK_ENABLE_VLV | DPLL_VGA_MODE_DIS;
1735         if (pipe != PIPE_A)
1736                 val |= DPLL_INTEGRATED_CRI_CLK_VLV;
1737
1738         I915_WRITE(DPLL(pipe), val);
1739         POSTING_READ(DPLL(pipe));
1740
1741         mutex_lock(&dev_priv->sb_lock);
1742
1743         /* Disable 10bit clock to display controller */
1744         val = vlv_dpio_read(dev_priv, pipe, CHV_CMN_DW14(port));
1745         val &= ~DPIO_DCLKP_EN;
1746         vlv_dpio_write(dev_priv, pipe, CHV_CMN_DW14(port), val);
1747
1748         mutex_unlock(&dev_priv->sb_lock);
1749 }
1750
1751 void vlv_wait_port_ready(struct drm_i915_private *dev_priv,
1752                          struct intel_digital_port *dport,
1753                          unsigned int expected_mask)
1754 {
1755         u32 port_mask;
1756         i915_reg_t dpll_reg;
1757
1758         switch (dport->port) {
1759         case PORT_B:
1760                 port_mask = DPLL_PORTB_READY_MASK;
1761                 dpll_reg = DPLL(0);
1762                 break;
1763         case PORT_C:
1764                 port_mask = DPLL_PORTC_READY_MASK;
1765                 dpll_reg = DPLL(0);
1766                 expected_mask <<= 4;
1767                 break;
1768         case PORT_D:
1769                 port_mask = DPLL_PORTD_READY_MASK;
1770                 dpll_reg = DPIO_PHY_STATUS;
1771                 break;
1772         default:
1773                 BUG();
1774         }
1775
1776         if (intel_wait_for_register(dev_priv,
1777                                     dpll_reg, port_mask, expected_mask,
1778                                     1000))
1779                 WARN(1, "timed out waiting for port %c ready: got 0x%x, expected 0x%x\n",
1780                      port_name(dport->port), I915_READ(dpll_reg) & port_mask, expected_mask);
1781 }
1782
1783 static void ironlake_enable_pch_transcoder(struct drm_i915_private *dev_priv,
1784                                            enum pipe pipe)
1785 {
1786         struct drm_crtc *crtc = dev_priv->pipe_to_crtc_mapping[pipe];
1787         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
1788         i915_reg_t reg;
1789         uint32_t val, pipeconf_val;
1790
1791         /* Make sure PCH DPLL is enabled */
1792         assert_shared_dpll_enabled(dev_priv, intel_crtc->config->shared_dpll);
1793
1794         /* FDI must be feeding us bits for PCH ports */
1795         assert_fdi_tx_enabled(dev_priv, pipe);
1796         assert_fdi_rx_enabled(dev_priv, pipe);
1797
1798         if (HAS_PCH_CPT(dev_priv)) {
1799                 /* Workaround: Set the timing override bit before enabling the
1800                  * pch transcoder. */
1801                 reg = TRANS_CHICKEN2(pipe);
1802                 val = I915_READ(reg);
1803                 val |= TRANS_CHICKEN2_TIMING_OVERRIDE;
1804                 I915_WRITE(reg, val);
1805         }
1806
1807         reg = PCH_TRANSCONF(pipe);
1808         val = I915_READ(reg);
1809         pipeconf_val = I915_READ(PIPECONF(pipe));
1810
1811         if (HAS_PCH_IBX(dev_priv)) {
1812                 /*
1813                  * Make the BPC in transcoder be consistent with
1814                  * that in pipeconf reg. For HDMI we must use 8bpc
1815                  * here for both 8bpc and 12bpc.
1816                  */
1817                 val &= ~PIPECONF_BPC_MASK;
1818                 if (intel_crtc_has_type(intel_crtc->config, INTEL_OUTPUT_HDMI))
1819                         val |= PIPECONF_8BPC;
1820                 else
1821                         val |= pipeconf_val & PIPECONF_BPC_MASK;
1822         }
1823
1824         val &= ~TRANS_INTERLACE_MASK;
1825         if ((pipeconf_val & PIPECONF_INTERLACE_MASK) == PIPECONF_INTERLACED_ILK)
1826                 if (HAS_PCH_IBX(dev_priv) &&
1827                     intel_crtc_has_type(intel_crtc->config, INTEL_OUTPUT_SDVO))
1828                         val |= TRANS_LEGACY_INTERLACED_ILK;
1829                 else
1830                         val |= TRANS_INTERLACED;
1831         else
1832                 val |= TRANS_PROGRESSIVE;
1833
1834         I915_WRITE(reg, val | TRANS_ENABLE);
1835         if (intel_wait_for_register(dev_priv,
1836                                     reg, TRANS_STATE_ENABLE, TRANS_STATE_ENABLE,
1837                                     100))
1838                 DRM_ERROR("failed to enable transcoder %c\n", pipe_name(pipe));
1839 }
1840
1841 static void lpt_enable_pch_transcoder(struct drm_i915_private *dev_priv,
1842                                       enum transcoder cpu_transcoder)
1843 {
1844         u32 val, pipeconf_val;
1845
1846         /* FDI must be feeding us bits for PCH ports */
1847         assert_fdi_tx_enabled(dev_priv, (enum pipe) cpu_transcoder);
1848         assert_fdi_rx_enabled(dev_priv, TRANSCODER_A);
1849
1850         /* Workaround: set timing override bit. */
1851         val = I915_READ(TRANS_CHICKEN2(PIPE_A));
1852         val |= TRANS_CHICKEN2_TIMING_OVERRIDE;
1853         I915_WRITE(TRANS_CHICKEN2(PIPE_A), val);
1854
1855         val = TRANS_ENABLE;
1856         pipeconf_val = I915_READ(PIPECONF(cpu_transcoder));
1857
1858         if ((pipeconf_val & PIPECONF_INTERLACE_MASK_HSW) ==
1859             PIPECONF_INTERLACED_ILK)
1860                 val |= TRANS_INTERLACED;
1861         else
1862                 val |= TRANS_PROGRESSIVE;
1863
1864         I915_WRITE(LPT_TRANSCONF, val);
1865         if (intel_wait_for_register(dev_priv,
1866                                     LPT_TRANSCONF,
1867                                     TRANS_STATE_ENABLE,
1868                                     TRANS_STATE_ENABLE,
1869                                     100))
1870                 DRM_ERROR("Failed to enable PCH transcoder\n");
1871 }
1872
1873 static void ironlake_disable_pch_transcoder(struct drm_i915_private *dev_priv,
1874                                             enum pipe pipe)
1875 {
1876         i915_reg_t reg;
1877         uint32_t val;
1878
1879         /* FDI relies on the transcoder */
1880         assert_fdi_tx_disabled(dev_priv, pipe);
1881         assert_fdi_rx_disabled(dev_priv, pipe);
1882
1883         /* Ports must be off as well */
1884         assert_pch_ports_disabled(dev_priv, pipe);
1885
1886         reg = PCH_TRANSCONF(pipe);
1887         val = I915_READ(reg);
1888         val &= ~TRANS_ENABLE;
1889         I915_WRITE(reg, val);
1890         /* wait for PCH transcoder off, transcoder state */
1891         if (intel_wait_for_register(dev_priv,
1892                                     reg, TRANS_STATE_ENABLE, 0,
1893                                     50))
1894                 DRM_ERROR("failed to disable transcoder %c\n", pipe_name(pipe));
1895
1896         if (HAS_PCH_CPT(dev_priv)) {
1897                 /* Workaround: Clear the timing override chicken bit again. */
1898                 reg = TRANS_CHICKEN2(pipe);
1899                 val = I915_READ(reg);
1900                 val &= ~TRANS_CHICKEN2_TIMING_OVERRIDE;
1901                 I915_WRITE(reg, val);
1902         }
1903 }
1904
1905 void lpt_disable_pch_transcoder(struct drm_i915_private *dev_priv)
1906 {
1907         u32 val;
1908
1909         val = I915_READ(LPT_TRANSCONF);
1910         val &= ~TRANS_ENABLE;
1911         I915_WRITE(LPT_TRANSCONF, val);
1912         /* wait for PCH transcoder off, transcoder state */
1913         if (intel_wait_for_register(dev_priv,
1914                                     LPT_TRANSCONF, TRANS_STATE_ENABLE, 0,
1915                                     50))
1916                 DRM_ERROR("Failed to disable PCH transcoder\n");
1917
1918         /* Workaround: clear timing override bit. */
1919         val = I915_READ(TRANS_CHICKEN2(PIPE_A));
1920         val &= ~TRANS_CHICKEN2_TIMING_OVERRIDE;
1921         I915_WRITE(TRANS_CHICKEN2(PIPE_A), val);
1922 }
1923
1924 /**
1925  * intel_enable_pipe - enable a pipe, asserting requirements
1926  * @crtc: crtc responsible for the pipe
1927  *
1928  * Enable @crtc's pipe, making sure that various hardware specific requirements
1929  * are met, if applicable, e.g. PLL enabled, LVDS pairs enabled, etc.
1930  */
1931 static void intel_enable_pipe(struct intel_crtc *crtc)
1932 {
1933         struct drm_device *dev = crtc->base.dev;
1934         struct drm_i915_private *dev_priv = to_i915(dev);
1935         enum pipe pipe = crtc->pipe;
1936         enum transcoder cpu_transcoder = crtc->config->cpu_transcoder;
1937         enum pipe pch_transcoder;
1938         i915_reg_t reg;
1939         u32 val;
1940
1941         DRM_DEBUG_KMS("enabling pipe %c\n", pipe_name(pipe));
1942
1943         assert_planes_disabled(dev_priv, pipe);
1944         assert_cursor_disabled(dev_priv, pipe);
1945         assert_sprites_disabled(dev_priv, pipe);
1946
1947         if (HAS_PCH_LPT(dev_priv))
1948                 pch_transcoder = TRANSCODER_A;
1949         else
1950                 pch_transcoder = pipe;
1951
1952         /*
1953          * A pipe without a PLL won't actually be able to drive bits from
1954          * a plane.  On ILK+ the pipe PLLs are integrated, so we don't
1955          * need the check.
1956          */
1957         if (HAS_GMCH_DISPLAY(dev_priv)) {
1958                 if (intel_crtc_has_type(crtc->config, INTEL_OUTPUT_DSI))
1959                         assert_dsi_pll_enabled(dev_priv);
1960                 else
1961                         assert_pll_enabled(dev_priv, pipe);
1962         } else {
1963                 if (crtc->config->has_pch_encoder) {
1964                         /* if driving the PCH, we need FDI enabled */
1965                         assert_fdi_rx_pll_enabled(dev_priv, pch_transcoder);
1966                         assert_fdi_tx_pll_enabled(dev_priv,
1967                                                   (enum pipe) cpu_transcoder);
1968                 }
1969                 /* FIXME: assert CPU port conditions for SNB+ */
1970         }
1971
1972         reg = PIPECONF(cpu_transcoder);
1973         val = I915_READ(reg);
1974         if (val & PIPECONF_ENABLE) {
1975                 WARN_ON(!((pipe == PIPE_A && dev_priv->quirks & QUIRK_PIPEA_FORCE) ||
1976                           (pipe == PIPE_B && dev_priv->quirks & QUIRK_PIPEB_FORCE)));
1977                 return;
1978         }
1979
1980         I915_WRITE(reg, val | PIPECONF_ENABLE);
1981         POSTING_READ(reg);
1982
1983         /*
1984          * Until the pipe starts DSL will read as 0, which would cause
1985          * an apparent vblank timestamp jump, which messes up also the
1986          * frame count when it's derived from the timestamps. So let's
1987          * wait for the pipe to start properly before we call
1988          * drm_crtc_vblank_on()
1989          */
1990         if (dev->max_vblank_count == 0 &&
1991             wait_for(intel_get_crtc_scanline(crtc) != crtc->scanline_offset, 50))
1992                 DRM_ERROR("pipe %c didn't start\n", pipe_name(pipe));
1993 }
1994
1995 /**
1996  * intel_disable_pipe - disable a pipe, asserting requirements
1997  * @crtc: crtc whose pipes is to be disabled
1998  *
1999  * Disable the pipe of @crtc, making sure that various hardware
2000  * specific requirements are met, if applicable, e.g. plane
2001  * disabled, panel fitter off, etc.
2002  *
2003  * Will wait until the pipe has shut down before returning.
2004  */
2005 static void intel_disable_pipe(struct intel_crtc *crtc)
2006 {
2007         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
2008         enum transcoder cpu_transcoder = crtc->config->cpu_transcoder;
2009         enum pipe pipe = crtc->pipe;
2010         i915_reg_t reg;
2011         u32 val;
2012
2013         DRM_DEBUG_KMS("disabling pipe %c\n", pipe_name(pipe));
2014
2015         /*
2016          * Make sure planes won't keep trying to pump pixels to us,
2017          * or we might hang the display.
2018          */
2019         assert_planes_disabled(dev_priv, pipe);
2020         assert_cursor_disabled(dev_priv, pipe);
2021         assert_sprites_disabled(dev_priv, pipe);
2022
2023         reg = PIPECONF(cpu_transcoder);
2024         val = I915_READ(reg);
2025         if ((val & PIPECONF_ENABLE) == 0)
2026                 return;
2027
2028         /*
2029          * Double wide has implications for planes
2030          * so best keep it disabled when not needed.
2031          */
2032         if (crtc->config->double_wide)
2033                 val &= ~PIPECONF_DOUBLE_WIDE;
2034
2035         /* Don't disable pipe or pipe PLLs if needed */
2036         if (!(pipe == PIPE_A && dev_priv->quirks & QUIRK_PIPEA_FORCE) &&
2037             !(pipe == PIPE_B && dev_priv->quirks & QUIRK_PIPEB_FORCE))
2038                 val &= ~PIPECONF_ENABLE;
2039
2040         I915_WRITE(reg, val);
2041         if ((val & PIPECONF_ENABLE) == 0)
2042                 intel_wait_for_pipe_off(crtc);
2043 }
2044
2045 static unsigned int intel_tile_size(const struct drm_i915_private *dev_priv)
2046 {
2047         return IS_GEN2(dev_priv) ? 2048 : 4096;
2048 }
2049
2050 static unsigned int intel_tile_width_bytes(const struct drm_i915_private *dev_priv,
2051                                            uint64_t fb_modifier, unsigned int cpp)
2052 {
2053         switch (fb_modifier) {
2054         case DRM_FORMAT_MOD_NONE:
2055                 return cpp;
2056         case I915_FORMAT_MOD_X_TILED:
2057                 if (IS_GEN2(dev_priv))
2058                         return 128;
2059                 else
2060                         return 512;
2061         case I915_FORMAT_MOD_Y_TILED:
2062                 if (IS_GEN2(dev_priv) || HAS_128_BYTE_Y_TILING(dev_priv))
2063                         return 128;
2064                 else
2065                         return 512;
2066         case I915_FORMAT_MOD_Yf_TILED:
2067                 switch (cpp) {
2068                 case 1:
2069                         return 64;
2070                 case 2:
2071                 case 4:
2072                         return 128;
2073                 case 8:
2074                 case 16:
2075                         return 256;
2076                 default:
2077                         MISSING_CASE(cpp);
2078                         return cpp;
2079                 }
2080                 break;
2081         default:
2082                 MISSING_CASE(fb_modifier);
2083                 return cpp;
2084         }
2085 }
2086
2087 unsigned int intel_tile_height(const struct drm_i915_private *dev_priv,
2088                                uint64_t fb_modifier, unsigned int cpp)
2089 {
2090         if (fb_modifier == DRM_FORMAT_MOD_NONE)
2091                 return 1;
2092         else
2093                 return intel_tile_size(dev_priv) /
2094                         intel_tile_width_bytes(dev_priv, fb_modifier, cpp);
2095 }
2096
2097 /* Return the tile dimensions in pixel units */
2098 static void intel_tile_dims(const struct drm_i915_private *dev_priv,
2099                             unsigned int *tile_width,
2100                             unsigned int *tile_height,
2101                             uint64_t fb_modifier,
2102                             unsigned int cpp)
2103 {
2104         unsigned int tile_width_bytes =
2105                 intel_tile_width_bytes(dev_priv, fb_modifier, cpp);
2106
2107         *tile_width = tile_width_bytes / cpp;
2108         *tile_height = intel_tile_size(dev_priv) / tile_width_bytes;
2109 }
2110
2111 unsigned int
2112 intel_fb_align_height(struct drm_device *dev, unsigned int height,
2113                       uint32_t pixel_format, uint64_t fb_modifier)
2114 {
2115         unsigned int cpp = drm_format_plane_cpp(pixel_format, 0);
2116         unsigned int tile_height = intel_tile_height(to_i915(dev), fb_modifier, cpp);
2117
2118         return ALIGN(height, tile_height);
2119 }
2120
2121 unsigned int intel_rotation_info_size(const struct intel_rotation_info *rot_info)
2122 {
2123         unsigned int size = 0;
2124         int i;
2125
2126         for (i = 0 ; i < ARRAY_SIZE(rot_info->plane); i++)
2127                 size += rot_info->plane[i].width * rot_info->plane[i].height;
2128
2129         return size;
2130 }
2131
2132 static void
2133 intel_fill_fb_ggtt_view(struct i915_ggtt_view *view,
2134                         const struct drm_framebuffer *fb,
2135                         unsigned int rotation)
2136 {
2137         if (intel_rotation_90_or_270(rotation)) {
2138                 *view = i915_ggtt_view_rotated;
2139                 view->params.rotated = to_intel_framebuffer(fb)->rot_info;
2140         } else {
2141                 *view = i915_ggtt_view_normal;
2142         }
2143 }
2144
2145 static unsigned int intel_linear_alignment(const struct drm_i915_private *dev_priv)
2146 {
2147         if (INTEL_INFO(dev_priv)->gen >= 9)
2148                 return 256 * 1024;
2149         else if (IS_BROADWATER(dev_priv) || IS_CRESTLINE(dev_priv) ||
2150                  IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv))
2151                 return 128 * 1024;
2152         else if (INTEL_INFO(dev_priv)->gen >= 4)
2153                 return 4 * 1024;
2154         else
2155                 return 0;
2156 }
2157
2158 static unsigned int intel_surf_alignment(const struct drm_i915_private *dev_priv,
2159                                          uint64_t fb_modifier)
2160 {
2161         switch (fb_modifier) {
2162         case DRM_FORMAT_MOD_NONE:
2163                 return intel_linear_alignment(dev_priv);
2164         case I915_FORMAT_MOD_X_TILED:
2165                 if (INTEL_INFO(dev_priv)->gen >= 9)
2166                         return 256 * 1024;
2167                 return 0;
2168         case I915_FORMAT_MOD_Y_TILED:
2169         case I915_FORMAT_MOD_Yf_TILED:
2170                 return 1 * 1024 * 1024;
2171         default:
2172                 MISSING_CASE(fb_modifier);
2173                 return 0;
2174         }
2175 }
2176
2177 struct i915_vma *
2178 intel_pin_and_fence_fb_obj(struct drm_framebuffer *fb, unsigned int rotation)
2179 {
2180         struct drm_device *dev = fb->dev;
2181         struct drm_i915_private *dev_priv = to_i915(dev);
2182         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
2183         struct i915_ggtt_view view;
2184         struct i915_vma *vma;
2185         u32 alignment;
2186
2187         WARN_ON(!mutex_is_locked(&dev->struct_mutex));
2188
2189         alignment = intel_surf_alignment(dev_priv, fb->modifier[0]);
2190
2191         intel_fill_fb_ggtt_view(&view, fb, rotation);
2192
2193         /* Note that the w/a also requires 64 PTE of padding following the
2194          * bo. We currently fill all unused PTE with the shadow page and so
2195          * we should always have valid PTE following the scanout preventing
2196          * the VT-d warning.
2197          */
2198         if (intel_scanout_needs_vtd_wa(dev_priv) && alignment < 256 * 1024)
2199                 alignment = 256 * 1024;
2200
2201         /*
2202          * Global gtt pte registers are special registers which actually forward
2203          * writes to a chunk of system memory. Which means that there is no risk
2204          * that the register values disappear as soon as we call
2205          * intel_runtime_pm_put(), so it is correct to wrap only the
2206          * pin/unpin/fence and not more.
2207          */
2208         intel_runtime_pm_get(dev_priv);
2209
2210         vma = i915_gem_object_pin_to_display_plane(obj, alignment, &view);
2211         if (IS_ERR(vma))
2212                 goto err;
2213
2214         if (i915_vma_is_map_and_fenceable(vma)) {
2215                 /* Install a fence for tiled scan-out. Pre-i965 always needs a
2216                  * fence, whereas 965+ only requires a fence if using
2217                  * framebuffer compression.  For simplicity, we always, when
2218                  * possible, install a fence as the cost is not that onerous.
2219                  *
2220                  * If we fail to fence the tiled scanout, then either the
2221                  * modeset will reject the change (which is highly unlikely as
2222                  * the affected systems, all but one, do not have unmappable
2223                  * space) or we will not be able to enable full powersaving
2224                  * techniques (also likely not to apply due to various limits
2225                  * FBC and the like impose on the size of the buffer, which
2226                  * presumably we violated anyway with this unmappable buffer).
2227                  * Anyway, it is presumably better to stumble onwards with
2228                  * something and try to run the system in a "less than optimal"
2229                  * mode that matches the user configuration.
2230                  */
2231                 if (i915_vma_get_fence(vma) == 0)
2232                         i915_vma_pin_fence(vma);
2233         }
2234
2235 err:
2236         intel_runtime_pm_put(dev_priv);
2237         return vma;
2238 }
2239
2240 void intel_unpin_fb_obj(struct drm_framebuffer *fb, unsigned int rotation)
2241 {
2242         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
2243         struct i915_ggtt_view view;
2244         struct i915_vma *vma;
2245
2246         WARN_ON(!mutex_is_locked(&obj->base.dev->struct_mutex));
2247
2248         intel_fill_fb_ggtt_view(&view, fb, rotation);
2249         vma = i915_gem_object_to_ggtt(obj, &view);
2250
2251         i915_vma_unpin_fence(vma);
2252         i915_gem_object_unpin_from_display_plane(vma);
2253 }
2254
2255 static int intel_fb_pitch(const struct drm_framebuffer *fb, int plane,
2256                           unsigned int rotation)
2257 {
2258         if (intel_rotation_90_or_270(rotation))
2259                 return to_intel_framebuffer(fb)->rotated[plane].pitch;
2260         else
2261                 return fb->pitches[plane];
2262 }
2263
2264 /*
2265  * Convert the x/y offsets into a linear offset.
2266  * Only valid with 0/180 degree rotation, which is fine since linear
2267  * offset is only used with linear buffers on pre-hsw and tiled buffers
2268  * with gen2/3, and 90/270 degree rotations isn't supported on any of them.
2269  */
2270 u32 intel_fb_xy_to_linear(int x, int y,
2271                           const struct intel_plane_state *state,
2272                           int plane)
2273 {
2274         const struct drm_framebuffer *fb = state->base.fb;
2275         unsigned int cpp = drm_format_plane_cpp(fb->pixel_format, plane);
2276         unsigned int pitch = fb->pitches[plane];
2277
2278         return y * pitch + x * cpp;
2279 }
2280
2281 /*
2282  * Add the x/y offsets derived from fb->offsets[] to the user
2283  * specified plane src x/y offsets. The resulting x/y offsets
2284  * specify the start of scanout from the beginning of the gtt mapping.
2285  */
2286 void intel_add_fb_offsets(int *x, int *y,
2287                           const struct intel_plane_state *state,
2288                           int plane)
2289
2290 {
2291         const struct intel_framebuffer *intel_fb = to_intel_framebuffer(state->base.fb);
2292         unsigned int rotation = state->base.rotation;
2293
2294         if (intel_rotation_90_or_270(rotation)) {
2295                 *x += intel_fb->rotated[plane].x;
2296                 *y += intel_fb->rotated[plane].y;
2297         } else {
2298                 *x += intel_fb->normal[plane].x;
2299                 *y += intel_fb->normal[plane].y;
2300         }
2301 }
2302
2303 /*
2304  * Input tile dimensions and pitch must already be
2305  * rotated to match x and y, and in pixel units.
2306  */
2307 static u32 _intel_adjust_tile_offset(int *x, int *y,
2308                                      unsigned int tile_width,
2309                                      unsigned int tile_height,
2310                                      unsigned int tile_size,
2311                                      unsigned int pitch_tiles,
2312                                      u32 old_offset,
2313                                      u32 new_offset)
2314 {
2315         unsigned int pitch_pixels = pitch_tiles * tile_width;
2316         unsigned int tiles;
2317
2318         WARN_ON(old_offset & (tile_size - 1));
2319         WARN_ON(new_offset & (tile_size - 1));
2320         WARN_ON(new_offset > old_offset);
2321
2322         tiles = (old_offset - new_offset) / tile_size;
2323
2324         *y += tiles / pitch_tiles * tile_height;
2325         *x += tiles % pitch_tiles * tile_width;
2326
2327         /* minimize x in case it got needlessly big */
2328         *y += *x / pitch_pixels * tile_height;
2329         *x %= pitch_pixels;
2330
2331         return new_offset;
2332 }
2333
2334 /*
2335  * Adjust the tile offset by moving the difference into
2336  * the x/y offsets.
2337  */
2338 static u32 intel_adjust_tile_offset(int *x, int *y,
2339                                     const struct intel_plane_state *state, int plane,
2340                                     u32 old_offset, u32 new_offset)
2341 {
2342         const struct drm_i915_private *dev_priv = to_i915(state->base.plane->dev);
2343         const struct drm_framebuffer *fb = state->base.fb;
2344         unsigned int cpp = drm_format_plane_cpp(fb->pixel_format, plane);
2345         unsigned int rotation = state->base.rotation;
2346         unsigned int pitch = intel_fb_pitch(fb, plane, rotation);
2347
2348         WARN_ON(new_offset > old_offset);
2349
2350         if (fb->modifier[plane] != DRM_FORMAT_MOD_NONE) {
2351                 unsigned int tile_size, tile_width, tile_height;
2352                 unsigned int pitch_tiles;
2353
2354                 tile_size = intel_tile_size(dev_priv);
2355                 intel_tile_dims(dev_priv, &tile_width, &tile_height,
2356                                 fb->modifier[plane], cpp);
2357
2358                 if (intel_rotation_90_or_270(rotation)) {
2359                         pitch_tiles = pitch / tile_height;
2360                         swap(tile_width, tile_height);
2361                 } else {
2362                         pitch_tiles = pitch / (tile_width * cpp);
2363                 }
2364
2365                 _intel_adjust_tile_offset(x, y, tile_width, tile_height,
2366                                           tile_size, pitch_tiles,
2367                                           old_offset, new_offset);
2368         } else {
2369                 old_offset += *y * pitch + *x * cpp;
2370
2371                 *y = (old_offset - new_offset) / pitch;
2372                 *x = ((old_offset - new_offset) - *y * pitch) / cpp;
2373         }
2374
2375         return new_offset;
2376 }
2377
2378 /*
2379  * Computes the linear offset to the base tile and adjusts
2380  * x, y. bytes per pixel is assumed to be a power-of-two.
2381  *
2382  * In the 90/270 rotated case, x and y are assumed
2383  * to be already rotated to match the rotated GTT view, and
2384  * pitch is the tile_height aligned framebuffer height.
2385  *
2386  * This function is used when computing the derived information
2387  * under intel_framebuffer, so using any of that information
2388  * here is not allowed. Anything under drm_framebuffer can be
2389  * used. This is why the user has to pass in the pitch since it
2390  * is specified in the rotated orientation.
2391  */
2392 static u32 _intel_compute_tile_offset(const struct drm_i915_private *dev_priv,
2393                                       int *x, int *y,
2394                                       const struct drm_framebuffer *fb, int plane,
2395                                       unsigned int pitch,
2396                                       unsigned int rotation,
2397                                       u32 alignment)
2398 {
2399         uint64_t fb_modifier = fb->modifier[plane];
2400         unsigned int cpp = drm_format_plane_cpp(fb->pixel_format, plane);
2401         u32 offset, offset_aligned;
2402
2403         if (alignment)
2404                 alignment--;
2405
2406         if (fb_modifier != DRM_FORMAT_MOD_NONE) {
2407                 unsigned int tile_size, tile_width, tile_height;
2408                 unsigned int tile_rows, tiles, pitch_tiles;
2409
2410                 tile_size = intel_tile_size(dev_priv);
2411                 intel_tile_dims(dev_priv, &tile_width, &tile_height,
2412                                 fb_modifier, cpp);
2413
2414                 if (intel_rotation_90_or_270(rotation)) {
2415                         pitch_tiles = pitch / tile_height;
2416                         swap(tile_width, tile_height);
2417                 } else {
2418                         pitch_tiles = pitch / (tile_width * cpp);
2419                 }
2420
2421                 tile_rows = *y / tile_height;
2422                 *y %= tile_height;
2423
2424                 tiles = *x / tile_width;
2425                 *x %= tile_width;
2426
2427                 offset = (tile_rows * pitch_tiles + tiles) * tile_size;
2428                 offset_aligned = offset & ~alignment;
2429
2430                 _intel_adjust_tile_offset(x, y, tile_width, tile_height,
2431                                           tile_size, pitch_tiles,
2432                                           offset, offset_aligned);
2433         } else {
2434                 offset = *y * pitch + *x * cpp;
2435                 offset_aligned = offset & ~alignment;
2436
2437                 *y = (offset & alignment) / pitch;
2438                 *x = ((offset & alignment) - *y * pitch) / cpp;
2439         }
2440
2441         return offset_aligned;
2442 }
2443
2444 u32 intel_compute_tile_offset(int *x, int *y,
2445                               const struct intel_plane_state *state,
2446                               int plane)
2447 {
2448         const struct drm_i915_private *dev_priv = to_i915(state->base.plane->dev);
2449         const struct drm_framebuffer *fb = state->base.fb;
2450         unsigned int rotation = state->base.rotation;
2451         int pitch = intel_fb_pitch(fb, plane, rotation);
2452         u32 alignment;
2453
2454         /* AUX_DIST needs only 4K alignment */
2455         if (fb->pixel_format == DRM_FORMAT_NV12 && plane == 1)
2456                 alignment = 4096;
2457         else
2458                 alignment = intel_surf_alignment(dev_priv, fb->modifier[plane]);
2459
2460         return _intel_compute_tile_offset(dev_priv, x, y, fb, plane, pitch,
2461                                           rotation, alignment);
2462 }
2463
2464 /* Convert the fb->offset[] linear offset into x/y offsets */
2465 static void intel_fb_offset_to_xy(int *x, int *y,
2466                                   const struct drm_framebuffer *fb, int plane)
2467 {
2468         unsigned int cpp = drm_format_plane_cpp(fb->pixel_format, plane);
2469         unsigned int pitch = fb->pitches[plane];
2470         u32 linear_offset = fb->offsets[plane];
2471
2472         *y = linear_offset / pitch;
2473         *x = linear_offset % pitch / cpp;
2474 }
2475
2476 static unsigned int intel_fb_modifier_to_tiling(uint64_t fb_modifier)
2477 {
2478         switch (fb_modifier) {
2479         case I915_FORMAT_MOD_X_TILED:
2480                 return I915_TILING_X;
2481         case I915_FORMAT_MOD_Y_TILED:
2482                 return I915_TILING_Y;
2483         default:
2484                 return I915_TILING_NONE;
2485         }
2486 }
2487
2488 static int
2489 intel_fill_fb_info(struct drm_i915_private *dev_priv,
2490                    struct drm_framebuffer *fb)
2491 {
2492         struct intel_framebuffer *intel_fb = to_intel_framebuffer(fb);
2493         struct intel_rotation_info *rot_info = &intel_fb->rot_info;
2494         u32 gtt_offset_rotated = 0;
2495         unsigned int max_size = 0;
2496         uint32_t format = fb->pixel_format;
2497         int i, num_planes = drm_format_num_planes(format);
2498         unsigned int tile_size = intel_tile_size(dev_priv);
2499
2500         for (i = 0; i < num_planes; i++) {
2501                 unsigned int width, height;
2502                 unsigned int cpp, size;
2503                 u32 offset;
2504                 int x, y;
2505
2506                 cpp = drm_format_plane_cpp(format, i);
2507                 width = drm_format_plane_width(fb->width, format, i);
2508                 height = drm_format_plane_height(fb->height, format, i);
2509
2510                 intel_fb_offset_to_xy(&x, &y, fb, i);
2511
2512                 /*
2513                  * The fence (if used) is aligned to the start of the object
2514                  * so having the framebuffer wrap around across the edge of the
2515                  * fenced region doesn't really work. We have no API to configure
2516                  * the fence start offset within the object (nor could we probably
2517                  * on gen2/3). So it's just easier if we just require that the
2518                  * fb layout agrees with the fence layout. We already check that the
2519                  * fb stride matches the fence stride elsewhere.
2520                  */
2521                 if (i915_gem_object_is_tiled(intel_fb->obj) &&
2522                     (x + width) * cpp > fb->pitches[i]) {
2523                         DRM_DEBUG("bad fb plane %d offset: 0x%x\n",
2524                                   i, fb->offsets[i]);
2525                         return -EINVAL;
2526                 }
2527
2528                 /*
2529                  * First pixel of the framebuffer from
2530                  * the start of the normal gtt mapping.
2531                  */
2532                 intel_fb->normal[i].x = x;
2533                 intel_fb->normal[i].y = y;
2534
2535                 offset = _intel_compute_tile_offset(dev_priv, &x, &y,
2536                                                     fb, 0, fb->pitches[i],
2537                                                     DRM_ROTATE_0, tile_size);
2538                 offset /= tile_size;
2539
2540                 if (fb->modifier[i] != DRM_FORMAT_MOD_NONE) {
2541                         unsigned int tile_width, tile_height;
2542                         unsigned int pitch_tiles;
2543                         struct drm_rect r;
2544
2545                         intel_tile_dims(dev_priv, &tile_width, &tile_height,
2546                                         fb->modifier[i], cpp);
2547
2548                         rot_info->plane[i].offset = offset;
2549                         rot_info->plane[i].stride = DIV_ROUND_UP(fb->pitches[i], tile_width * cpp);
2550                         rot_info->plane[i].width = DIV_ROUND_UP(x + width, tile_width);
2551                         rot_info->plane[i].height = DIV_ROUND_UP(y + height, tile_height);
2552
2553                         intel_fb->rotated[i].pitch =
2554                                 rot_info->plane[i].height * tile_height;
2555
2556                         /* how many tiles does this plane need */
2557                         size = rot_info->plane[i].stride * rot_info->plane[i].height;
2558                         /*
2559                          * If the plane isn't horizontally tile aligned,
2560                          * we need one more tile.
2561                          */
2562                         if (x != 0)
2563                                 size++;
2564
2565                         /* rotate the x/y offsets to match the GTT view */
2566                         r.x1 = x;
2567                         r.y1 = y;
2568                         r.x2 = x + width;
2569                         r.y2 = y + height;
2570                         drm_rect_rotate(&r,
2571                                         rot_info->plane[i].width * tile_width,
2572                                         rot_info->plane[i].height * tile_height,
2573                                         DRM_ROTATE_270);
2574                         x = r.x1;
2575                         y = r.y1;
2576
2577                         /* rotate the tile dimensions to match the GTT view */
2578                         pitch_tiles = intel_fb->rotated[i].pitch / tile_height;
2579                         swap(tile_width, tile_height);
2580
2581                         /*
2582                          * We only keep the x/y offsets, so push all of the
2583                          * gtt offset into the x/y offsets.
2584                          */
2585                         _intel_adjust_tile_offset(&x, &y, tile_size,
2586                                                   tile_width, tile_height, pitch_tiles,
2587                                                   gtt_offset_rotated * tile_size, 0);
2588
2589                         gtt_offset_rotated += rot_info->plane[i].width * rot_info->plane[i].height;
2590
2591                         /*
2592                          * First pixel of the framebuffer from
2593                          * the start of the rotated gtt mapping.
2594                          */
2595                         intel_fb->rotated[i].x = x;
2596                         intel_fb->rotated[i].y = y;
2597                 } else {
2598                         size = DIV_ROUND_UP((y + height) * fb->pitches[i] +
2599                                             x * cpp, tile_size);
2600                 }
2601
2602                 /* how many tiles in total needed in the bo */
2603                 max_size = max(max_size, offset + size);
2604         }
2605
2606         if (max_size * tile_size > to_intel_framebuffer(fb)->obj->base.size) {
2607                 DRM_DEBUG("fb too big for bo (need %u bytes, have %zu bytes)\n",
2608                           max_size * tile_size, to_intel_framebuffer(fb)->obj->base.size);
2609                 return -EINVAL;
2610         }
2611
2612         return 0;
2613 }
2614
2615 static int i9xx_format_to_fourcc(int format)
2616 {
2617         switch (format) {
2618         case DISPPLANE_8BPP:
2619                 return DRM_FORMAT_C8;
2620         case DISPPLANE_BGRX555:
2621                 return DRM_FORMAT_XRGB1555;
2622         case DISPPLANE_BGRX565:
2623                 return DRM_FORMAT_RGB565;
2624         default:
2625         case DISPPLANE_BGRX888:
2626                 return DRM_FORMAT_XRGB8888;
2627         case DISPPLANE_RGBX888:
2628                 return DRM_FORMAT_XBGR8888;
2629         case DISPPLANE_BGRX101010:
2630                 return DRM_FORMAT_XRGB2101010;
2631         case DISPPLANE_RGBX101010:
2632                 return DRM_FORMAT_XBGR2101010;
2633         }
2634 }
2635
2636 static int skl_format_to_fourcc(int format, bool rgb_order, bool alpha)
2637 {
2638         switch (format) {
2639         case PLANE_CTL_FORMAT_RGB_565:
2640                 return DRM_FORMAT_RGB565;
2641         default:
2642         case PLANE_CTL_FORMAT_XRGB_8888:
2643                 if (rgb_order) {
2644                         if (alpha)
2645                                 return DRM_FORMAT_ABGR8888;
2646                         else
2647                                 return DRM_FORMAT_XBGR8888;
2648                 } else {
2649                         if (alpha)
2650                                 return DRM_FORMAT_ARGB8888;
2651                         else
2652                                 return DRM_FORMAT_XRGB8888;
2653                 }
2654         case PLANE_CTL_FORMAT_XRGB_2101010:
2655                 if (rgb_order)
2656                         return DRM_FORMAT_XBGR2101010;
2657                 else
2658                         return DRM_FORMAT_XRGB2101010;
2659         }
2660 }
2661
2662 static bool
2663 intel_alloc_initial_plane_obj(struct intel_crtc *crtc,
2664                               struct intel_initial_plane_config *plane_config)
2665 {
2666         struct drm_device *dev = crtc->base.dev;
2667         struct drm_i915_private *dev_priv = to_i915(dev);
2668         struct i915_ggtt *ggtt = &dev_priv->ggtt;
2669         struct drm_i915_gem_object *obj = NULL;
2670         struct drm_mode_fb_cmd2 mode_cmd = { 0 };
2671         struct drm_framebuffer *fb = &plane_config->fb->base;
2672         u32 base_aligned = round_down(plane_config->base, PAGE_SIZE);
2673         u32 size_aligned = round_up(plane_config->base + plane_config->size,
2674                                     PAGE_SIZE);
2675
2676         size_aligned -= base_aligned;
2677
2678         if (plane_config->size == 0)
2679                 return false;
2680
2681         /* If the FB is too big, just don't use it since fbdev is not very
2682          * important and we should probably use that space with FBC or other
2683          * features. */
2684         if (size_aligned * 2 > ggtt->stolen_usable_size)
2685                 return false;
2686
2687         mutex_lock(&dev->struct_mutex);
2688
2689         obj = i915_gem_object_create_stolen_for_preallocated(dev,
2690                                                              base_aligned,
2691                                                              base_aligned,
2692                                                              size_aligned);
2693         if (!obj) {
2694                 mutex_unlock(&dev->struct_mutex);
2695                 return false;
2696         }
2697
2698         if (plane_config->tiling == I915_TILING_X)
2699                 obj->tiling_and_stride = fb->pitches[0] | I915_TILING_X;
2700
2701         mode_cmd.pixel_format = fb->pixel_format;
2702         mode_cmd.width = fb->width;
2703         mode_cmd.height = fb->height;
2704         mode_cmd.pitches[0] = fb->pitches[0];
2705         mode_cmd.modifier[0] = fb->modifier[0];
2706         mode_cmd.flags = DRM_MODE_FB_MODIFIERS;
2707
2708         if (intel_framebuffer_init(dev, to_intel_framebuffer(fb),
2709                                    &mode_cmd, obj)) {
2710                 DRM_DEBUG_KMS("intel fb init failed\n");
2711                 goto out_unref_obj;
2712         }
2713
2714         mutex_unlock(&dev->struct_mutex);
2715
2716         DRM_DEBUG_KMS("initial plane fb obj %p\n", obj);
2717         return true;
2718
2719 out_unref_obj:
2720         i915_gem_object_put(obj);
2721         mutex_unlock(&dev->struct_mutex);
2722         return false;
2723 }
2724
2725 /* Update plane->state->fb to match plane->fb after driver-internal updates */
2726 static void
2727 update_state_fb(struct drm_plane *plane)
2728 {
2729         if (plane->fb == plane->state->fb)
2730                 return;
2731
2732         if (plane->state->fb)
2733                 drm_framebuffer_unreference(plane->state->fb);
2734         plane->state->fb = plane->fb;
2735         if (plane->state->fb)
2736                 drm_framebuffer_reference(plane->state->fb);
2737 }
2738
2739 static void
2740 intel_find_initial_plane_obj(struct intel_crtc *intel_crtc,
2741                              struct intel_initial_plane_config *plane_config)
2742 {
2743         struct drm_device *dev = intel_crtc->base.dev;
2744         struct drm_i915_private *dev_priv = to_i915(dev);
2745         struct drm_crtc *c;
2746         struct intel_crtc *i;
2747         struct drm_i915_gem_object *obj;
2748         struct drm_plane *primary = intel_crtc->base.primary;
2749         struct drm_plane_state *plane_state = primary->state;
2750         struct drm_crtc_state *crtc_state = intel_crtc->base.state;
2751         struct intel_plane *intel_plane = to_intel_plane(primary);
2752         struct intel_plane_state *intel_state =
2753                 to_intel_plane_state(plane_state);
2754         struct drm_framebuffer *fb;
2755
2756         if (!plane_config->fb)
2757                 return;
2758
2759         if (intel_alloc_initial_plane_obj(intel_crtc, plane_config)) {
2760                 fb = &plane_config->fb->base;
2761                 goto valid_fb;
2762         }
2763
2764         kfree(plane_config->fb);
2765
2766         /*
2767          * Failed to alloc the obj, check to see if we should share
2768          * an fb with another CRTC instead
2769          */
2770         for_each_crtc(dev, c) {
2771                 i = to_intel_crtc(c);
2772
2773                 if (c == &intel_crtc->base)
2774                         continue;
2775
2776                 if (!i->active)
2777                         continue;
2778
2779                 fb = c->primary->fb;
2780                 if (!fb)
2781                         continue;
2782
2783                 obj = intel_fb_obj(fb);
2784                 if (i915_gem_object_ggtt_offset(obj, NULL) == plane_config->base) {
2785                         drm_framebuffer_reference(fb);
2786                         goto valid_fb;
2787                 }
2788         }
2789
2790         /*
2791          * We've failed to reconstruct the BIOS FB.  Current display state
2792          * indicates that the primary plane is visible, but has a NULL FB,
2793          * which will lead to problems later if we don't fix it up.  The
2794          * simplest solution is to just disable the primary plane now and
2795          * pretend the BIOS never had it enabled.
2796          */
2797         to_intel_plane_state(plane_state)->base.visible = false;
2798         crtc_state->plane_mask &= ~(1 << drm_plane_index(primary));
2799         intel_pre_disable_primary_noatomic(&intel_crtc->base);
2800         intel_plane->disable_plane(primary, &intel_crtc->base);
2801
2802         return;
2803
2804 valid_fb:
2805         plane_state->src_x = 0;
2806         plane_state->src_y = 0;
2807         plane_state->src_w = fb->width << 16;
2808         plane_state->src_h = fb->height << 16;
2809
2810         plane_state->crtc_x = 0;
2811         plane_state->crtc_y = 0;
2812         plane_state->crtc_w = fb->width;
2813         plane_state->crtc_h = fb->height;
2814
2815         intel_state->base.src.x1 = plane_state->src_x;
2816         intel_state->base.src.y1 = plane_state->src_y;
2817         intel_state->base.src.x2 = plane_state->src_x + plane_state->src_w;
2818         intel_state->base.src.y2 = plane_state->src_y + plane_state->src_h;
2819         intel_state->base.dst.x1 = plane_state->crtc_x;
2820         intel_state->base.dst.y1 = plane_state->crtc_y;
2821         intel_state->base.dst.x2 = plane_state->crtc_x + plane_state->crtc_w;
2822         intel_state->base.dst.y2 = plane_state->crtc_y + plane_state->crtc_h;
2823
2824         obj = intel_fb_obj(fb);
2825         if (i915_gem_object_is_tiled(obj))
2826                 dev_priv->preserve_bios_swizzle = true;
2827
2828         drm_framebuffer_reference(fb);
2829         primary->fb = primary->state->fb = fb;
2830         primary->crtc = primary->state->crtc = &intel_crtc->base;
2831         intel_crtc->base.state->plane_mask |= (1 << drm_plane_index(primary));
2832         atomic_or(to_intel_plane(primary)->frontbuffer_bit,
2833                   &obj->frontbuffer_bits);
2834 }
2835
2836 static int skl_max_plane_width(const struct drm_framebuffer *fb, int plane,
2837                                unsigned int rotation)
2838 {
2839         int cpp = drm_format_plane_cpp(fb->pixel_format, plane);
2840
2841         switch (fb->modifier[plane]) {
2842         case DRM_FORMAT_MOD_NONE:
2843         case I915_FORMAT_MOD_X_TILED:
2844                 switch (cpp) {
2845                 case 8:
2846                         return 4096;
2847                 case 4:
2848                 case 2:
2849                 case 1:
2850                         return 8192;
2851                 default:
2852                         MISSING_CASE(cpp);
2853                         break;
2854                 }
2855                 break;
2856         case I915_FORMAT_MOD_Y_TILED:
2857         case I915_FORMAT_MOD_Yf_TILED:
2858                 switch (cpp) {
2859                 case 8:
2860                         return 2048;
2861                 case 4:
2862                         return 4096;
2863                 case 2:
2864                 case 1:
2865                         return 8192;
2866                 default:
2867                         MISSING_CASE(cpp);
2868                         break;
2869                 }
2870                 break;
2871         default:
2872                 MISSING_CASE(fb->modifier[plane]);
2873         }
2874
2875         return 2048;
2876 }
2877
2878 static int skl_check_main_surface(struct intel_plane_state *plane_state)
2879 {
2880         const struct drm_i915_private *dev_priv = to_i915(plane_state->base.plane->dev);
2881         const struct drm_framebuffer *fb = plane_state->base.fb;
2882         unsigned int rotation = plane_state->base.rotation;
2883         int x = plane_state->base.src.x1 >> 16;
2884         int y = plane_state->base.src.y1 >> 16;
2885         int w = drm_rect_width(&plane_state->base.src) >> 16;
2886         int h = drm_rect_height(&plane_state->base.src) >> 16;
2887         int max_width = skl_max_plane_width(fb, 0, rotation);
2888         int max_height = 4096;
2889         u32 alignment, offset, aux_offset = plane_state->aux.offset;
2890
2891         if (w > max_width || h > max_height) {
2892                 DRM_DEBUG_KMS("requested Y/RGB source size %dx%d too big (limit %dx%d)\n",
2893                               w, h, max_width, max_height);
2894                 return -EINVAL;
2895         }
2896
2897         intel_add_fb_offsets(&x, &y, plane_state, 0);
2898         offset = intel_compute_tile_offset(&x, &y, plane_state, 0);
2899
2900         alignment = intel_surf_alignment(dev_priv, fb->modifier[0]);
2901
2902         /*
2903          * AUX surface offset is specified as the distance from the
2904          * main surface offset, and it must be non-negative. Make
2905          * sure that is what we will get.
2906          */
2907         if (offset > aux_offset)
2908                 offset = intel_adjust_tile_offset(&x, &y, plane_state, 0,
2909                                                   offset, aux_offset & ~(alignment - 1));
2910
2911         /*
2912          * When using an X-tiled surface, the plane blows up
2913          * if the x offset + width exceed the stride.
2914          *
2915          * TODO: linear and Y-tiled seem fine, Yf untested,
2916          */
2917         if (fb->modifier[0] == I915_FORMAT_MOD_X_TILED) {
2918                 int cpp = drm_format_plane_cpp(fb->pixel_format, 0);
2919
2920                 while ((x + w) * cpp > fb->pitches[0]) {
2921                         if (offset == 0) {
2922                                 DRM_DEBUG_KMS("Unable to find suitable display surface offset\n");
2923                                 return -EINVAL;
2924                         }
2925
2926                         offset = intel_adjust_tile_offset(&x, &y, plane_state, 0,
2927                                                           offset, offset - alignment);
2928                 }
2929         }
2930
2931         plane_state->main.offset = offset;
2932         plane_state->main.x = x;
2933         plane_state->main.y = y;
2934
2935         return 0;
2936 }
2937
2938 static int skl_check_nv12_aux_surface(struct intel_plane_state *plane_state)
2939 {
2940         const struct drm_framebuffer *fb = plane_state->base.fb;
2941         unsigned int rotation = plane_state->base.rotation;
2942         int max_width = skl_max_plane_width(fb, 1, rotation);
2943         int max_height = 4096;
2944         int x = plane_state->base.src.x1 >> 17;
2945         int y = plane_state->base.src.y1 >> 17;
2946         int w = drm_rect_width(&plane_state->base.src) >> 17;
2947         int h = drm_rect_height(&plane_state->base.src) >> 17;
2948         u32 offset;
2949
2950         intel_add_fb_offsets(&x, &y, plane_state, 1);
2951         offset = intel_compute_tile_offset(&x, &y, plane_state, 1);
2952
2953         /* FIXME not quite sure how/if these apply to the chroma plane */
2954         if (w > max_width || h > max_height) {
2955                 DRM_DEBUG_KMS("CbCr source size %dx%d too big (limit %dx%d)\n",
2956                               w, h, max_width, max_height);
2957                 return -EINVAL;
2958         }
2959
2960         plane_state->aux.offset = offset;
2961         plane_state->aux.x = x;
2962         plane_state->aux.y = y;
2963
2964         return 0;
2965 }
2966
2967 int skl_check_plane_surface(struct intel_plane_state *plane_state)
2968 {
2969         const struct drm_framebuffer *fb = plane_state->base.fb;
2970         unsigned int rotation = plane_state->base.rotation;
2971         int ret;
2972
2973         /* Rotate src coordinates to match rotated GTT view */
2974         if (intel_rotation_90_or_270(rotation))
2975                 drm_rect_rotate(&plane_state->base.src,
2976                                 fb->width, fb->height, DRM_ROTATE_270);
2977
2978         /*
2979          * Handle the AUX surface first since
2980          * the main surface setup depends on it.
2981          */
2982         if (fb->pixel_format == DRM_FORMAT_NV12) {
2983                 ret = skl_check_nv12_aux_surface(plane_state);
2984                 if (ret)
2985                         return ret;
2986         } else {
2987                 plane_state->aux.offset = ~0xfff;
2988                 plane_state->aux.x = 0;
2989                 plane_state->aux.y = 0;
2990         }
2991
2992         ret = skl_check_main_surface(plane_state);
2993         if (ret)
2994                 return ret;
2995
2996         return 0;
2997 }
2998
2999 static void i9xx_update_primary_plane(struct drm_plane *primary,
3000                                       const struct intel_crtc_state *crtc_state,
3001                                       const struct intel_plane_state *plane_state)
3002 {
3003         struct drm_device *dev = primary->dev;
3004         struct drm_i915_private *dev_priv = to_i915(dev);
3005         struct intel_crtc *intel_crtc = to_intel_crtc(crtc_state->base.crtc);
3006         struct drm_framebuffer *fb = plane_state->base.fb;
3007         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
3008         int plane = intel_crtc->plane;
3009         u32 linear_offset;
3010         u32 dspcntr;
3011         i915_reg_t reg = DSPCNTR(plane);
3012         unsigned int rotation = plane_state->base.rotation;
3013         int x = plane_state->base.src.x1 >> 16;
3014         int y = plane_state->base.src.y1 >> 16;
3015
3016         dspcntr = DISPPLANE_GAMMA_ENABLE;
3017
3018         dspcntr |= DISPLAY_PLANE_ENABLE;
3019
3020         if (INTEL_INFO(dev)->gen < 4) {
3021                 if (intel_crtc->pipe == PIPE_B)
3022                         dspcntr |= DISPPLANE_SEL_PIPE_B;
3023
3024                 /* pipesrc and dspsize control the size that is scaled from,
3025                  * which should always be the user's requested size.
3026                  */
3027                 I915_WRITE(DSPSIZE(plane),
3028                            ((crtc_state->pipe_src_h - 1) << 16) |
3029                            (crtc_state->pipe_src_w - 1));
3030                 I915_WRITE(DSPPOS(plane), 0);
3031         } else if (IS_CHERRYVIEW(dev) && plane == PLANE_B) {
3032                 I915_WRITE(PRIMSIZE(plane),
3033                            ((crtc_state->pipe_src_h - 1) << 16) |
3034                            (crtc_state->pipe_src_w - 1));
3035                 I915_WRITE(PRIMPOS(plane), 0);
3036                 I915_WRITE(PRIMCNSTALPHA(plane), 0);
3037         }
3038
3039         switch (fb->pixel_format) {
3040         case DRM_FORMAT_C8:
3041                 dspcntr |= DISPPLANE_8BPP;
3042                 break;
3043         case DRM_FORMAT_XRGB1555:
3044                 dspcntr |= DISPPLANE_BGRX555;
3045                 break;
3046         case DRM_FORMAT_RGB565:
3047                 dspcntr |= DISPPLANE_BGRX565;
3048                 break;
3049         case DRM_FORMAT_XRGB8888:
3050                 dspcntr |= DISPPLANE_BGRX888;
3051                 break;
3052         case DRM_FORMAT_XBGR8888:
3053                 dspcntr |= DISPPLANE_RGBX888;
3054                 break;
3055         case DRM_FORMAT_XRGB2101010:
3056                 dspcntr |= DISPPLANE_BGRX101010;
3057                 break;
3058         case DRM_FORMAT_XBGR2101010:
3059                 dspcntr |= DISPPLANE_RGBX101010;
3060                 break;
3061         default:
3062                 BUG();
3063         }
3064
3065         if (INTEL_GEN(dev_priv) >= 4 &&
3066             fb->modifier[0] == I915_FORMAT_MOD_X_TILED)
3067                 dspcntr |= DISPPLANE_TILED;
3068
3069         if (IS_G4X(dev))
3070                 dspcntr |= DISPPLANE_TRICKLE_FEED_DISABLE;
3071
3072         intel_add_fb_offsets(&x, &y, plane_state, 0);
3073
3074         if (INTEL_INFO(dev)->gen >= 4)
3075                 intel_crtc->dspaddr_offset =
3076                         intel_compute_tile_offset(&x, &y, plane_state, 0);
3077
3078         if (rotation == DRM_ROTATE_180) {
3079                 dspcntr |= DISPPLANE_ROTATE_180;
3080
3081                 x += (crtc_state->pipe_src_w - 1);
3082                 y += (crtc_state->pipe_src_h - 1);
3083         }
3084
3085         linear_offset = intel_fb_xy_to_linear(x, y, plane_state, 0);
3086
3087         if (INTEL_INFO(dev)->gen < 4)
3088                 intel_crtc->dspaddr_offset = linear_offset;
3089
3090         intel_crtc->adjusted_x = x;
3091         intel_crtc->adjusted_y = y;
3092
3093         I915_WRITE(reg, dspcntr);
3094
3095         I915_WRITE(DSPSTRIDE(plane), fb->pitches[0]);
3096         if (INTEL_INFO(dev)->gen >= 4) {
3097                 I915_WRITE(DSPSURF(plane),
3098                            intel_fb_gtt_offset(fb, rotation) +
3099                            intel_crtc->dspaddr_offset);
3100                 I915_WRITE(DSPTILEOFF(plane), (y << 16) | x);
3101                 I915_WRITE(DSPLINOFF(plane), linear_offset);
3102         } else
3103                 I915_WRITE(DSPADDR(plane), i915_gem_object_ggtt_offset(obj, NULL) + linear_offset);
3104         POSTING_READ(reg);
3105 }
3106
3107 static void i9xx_disable_primary_plane(struct drm_plane *primary,
3108                                        struct drm_crtc *crtc)
3109 {
3110         struct drm_device *dev = crtc->dev;
3111         struct drm_i915_private *dev_priv = to_i915(dev);
3112         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
3113         int plane = intel_crtc->plane;
3114
3115         I915_WRITE(DSPCNTR(plane), 0);
3116         if (INTEL_INFO(dev_priv)->gen >= 4)
3117                 I915_WRITE(DSPSURF(plane), 0);
3118         else
3119                 I915_WRITE(DSPADDR(plane), 0);
3120         POSTING_READ(DSPCNTR(plane));
3121 }
3122
3123 static void ironlake_update_primary_plane(struct drm_plane *primary,
3124                                           const struct intel_crtc_state *crtc_state,
3125                                           const struct intel_plane_state *plane_state)
3126 {
3127         struct drm_device *dev = primary->dev;
3128         struct drm_i915_private *dev_priv = to_i915(dev);
3129         struct intel_crtc *intel_crtc = to_intel_crtc(crtc_state->base.crtc);
3130         struct drm_framebuffer *fb = plane_state->base.fb;
3131         int plane = intel_crtc->plane;
3132         u32 linear_offset;
3133         u32 dspcntr;
3134         i915_reg_t reg = DSPCNTR(plane);
3135         unsigned int rotation = plane_state->base.rotation;
3136         int x = plane_state->base.src.x1 >> 16;
3137         int y = plane_state->base.src.y1 >> 16;
3138
3139         dspcntr = DISPPLANE_GAMMA_ENABLE;
3140         dspcntr |= DISPLAY_PLANE_ENABLE;
3141
3142         if (IS_HASWELL(dev) || IS_BROADWELL(dev))
3143                 dspcntr |= DISPPLANE_PIPE_CSC_ENABLE;
3144
3145         switch (fb->pixel_format) {
3146         case DRM_FORMAT_C8:
3147                 dspcntr |= DISPPLANE_8BPP;
3148                 break;
3149         case DRM_FORMAT_RGB565:
3150                 dspcntr |= DISPPLANE_BGRX565;
3151                 break;
3152         case DRM_FORMAT_XRGB8888:
3153                 dspcntr |= DISPPLANE_BGRX888;
3154                 break;
3155         case DRM_FORMAT_XBGR8888:
3156                 dspcntr |= DISPPLANE_RGBX888;
3157                 break;
3158         case DRM_FORMAT_XRGB2101010:
3159                 dspcntr |= DISPPLANE_BGRX101010;
3160                 break;
3161         case DRM_FORMAT_XBGR2101010:
3162                 dspcntr |= DISPPLANE_RGBX101010;
3163                 break;
3164         default:
3165                 BUG();
3166         }
3167
3168         if (fb->modifier[0] == I915_FORMAT_MOD_X_TILED)
3169                 dspcntr |= DISPPLANE_TILED;
3170
3171         if (!IS_HASWELL(dev) && !IS_BROADWELL(dev))
3172                 dspcntr |= DISPPLANE_TRICKLE_FEED_DISABLE;
3173
3174         intel_add_fb_offsets(&x, &y, plane_state, 0);
3175
3176         intel_crtc->dspaddr_offset =
3177                 intel_compute_tile_offset(&x, &y, plane_state, 0);
3178
3179         if (rotation == DRM_ROTATE_180) {
3180                 dspcntr |= DISPPLANE_ROTATE_180;
3181
3182                 if (!IS_HASWELL(dev) && !IS_BROADWELL(dev)) {
3183                         x += (crtc_state->pipe_src_w - 1);
3184                         y += (crtc_state->pipe_src_h - 1);
3185                 }
3186         }
3187
3188         linear_offset = intel_fb_xy_to_linear(x, y, plane_state, 0);
3189
3190         intel_crtc->adjusted_x = x;
3191         intel_crtc->adjusted_y = y;
3192
3193         I915_WRITE(reg, dspcntr);
3194
3195         I915_WRITE(DSPSTRIDE(plane), fb->pitches[0]);
3196         I915_WRITE(DSPSURF(plane),
3197                    intel_fb_gtt_offset(fb, rotation) +
3198                    intel_crtc->dspaddr_offset);
3199         if (IS_HASWELL(dev) || IS_BROADWELL(dev)) {
3200                 I915_WRITE(DSPOFFSET(plane), (y << 16) | x);
3201         } else {
3202                 I915_WRITE(DSPTILEOFF(plane), (y << 16) | x);
3203                 I915_WRITE(DSPLINOFF(plane), linear_offset);
3204         }
3205         POSTING_READ(reg);
3206 }
3207
3208 u32 intel_fb_stride_alignment(const struct drm_i915_private *dev_priv,
3209                               uint64_t fb_modifier, uint32_t pixel_format)
3210 {
3211         if (fb_modifier == DRM_FORMAT_MOD_NONE) {
3212                 return 64;
3213         } else {
3214                 int cpp = drm_format_plane_cpp(pixel_format, 0);
3215
3216                 return intel_tile_width_bytes(dev_priv, fb_modifier, cpp);
3217         }
3218 }
3219
3220 u32 intel_fb_gtt_offset(struct drm_framebuffer *fb,
3221                         unsigned int rotation)
3222 {
3223         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
3224         struct i915_ggtt_view view;
3225         struct i915_vma *vma;
3226
3227         intel_fill_fb_ggtt_view(&view, fb, rotation);
3228
3229         vma = i915_gem_object_to_ggtt(obj, &view);
3230         if (WARN(!vma, "ggtt vma for display object not found! (view=%u)\n",
3231                  view.type))
3232                 return -1;
3233
3234         return i915_ggtt_offset(vma);
3235 }
3236
3237 static void skl_detach_scaler(struct intel_crtc *intel_crtc, int id)
3238 {
3239         struct drm_device *dev = intel_crtc->base.dev;
3240         struct drm_i915_private *dev_priv = to_i915(dev);
3241
3242         I915_WRITE(SKL_PS_CTRL(intel_crtc->pipe, id), 0);
3243         I915_WRITE(SKL_PS_WIN_POS(intel_crtc->pipe, id), 0);
3244         I915_WRITE(SKL_PS_WIN_SZ(intel_crtc->pipe, id), 0);
3245 }
3246
3247 /*
3248  * This function detaches (aka. unbinds) unused scalers in hardware
3249  */
3250 static void skl_detach_scalers(struct intel_crtc *intel_crtc)
3251 {
3252         struct intel_crtc_scaler_state *scaler_state;
3253         int i;
3254
3255         scaler_state = &intel_crtc->config->scaler_state;
3256
3257         /* loop through and disable scalers that aren't in use */
3258         for (i = 0; i < intel_crtc->num_scalers; i++) {
3259                 if (!scaler_state->scalers[i].in_use)
3260                         skl_detach_scaler(intel_crtc, i);
3261         }
3262 }
3263
3264 u32 skl_plane_stride(const struct drm_framebuffer *fb, int plane,
3265                      unsigned int rotation)
3266 {
3267         const struct drm_i915_private *dev_priv = to_i915(fb->dev);
3268         u32 stride = intel_fb_pitch(fb, plane, rotation);
3269
3270         /*
3271          * The stride is either expressed as a multiple of 64 bytes chunks for
3272          * linear buffers or in number of tiles for tiled buffers.
3273          */
3274         if (intel_rotation_90_or_270(rotation)) {
3275                 int cpp = drm_format_plane_cpp(fb->pixel_format, plane);
3276
3277                 stride /= intel_tile_height(dev_priv, fb->modifier[0], cpp);
3278         } else {
3279                 stride /= intel_fb_stride_alignment(dev_priv, fb->modifier[0],
3280                                                     fb->pixel_format);
3281         }
3282
3283         return stride;
3284 }
3285
3286 u32 skl_plane_ctl_format(uint32_t pixel_format)
3287 {
3288         switch (pixel_format) {
3289         case DRM_FORMAT_C8:
3290                 return PLANE_CTL_FORMAT_INDEXED;
3291         case DRM_FORMAT_RGB565:
3292                 return PLANE_CTL_FORMAT_RGB_565;
3293         case DRM_FORMAT_XBGR8888:
3294                 return PLANE_CTL_FORMAT_XRGB_8888 | PLANE_CTL_ORDER_RGBX;
3295         case DRM_FORMAT_XRGB8888:
3296                 return PLANE_CTL_FORMAT_XRGB_8888;
3297         /*
3298          * XXX: For ARBG/ABGR formats we default to expecting scanout buffers
3299          * to be already pre-multiplied. We need to add a knob (or a different
3300          * DRM_FORMAT) for user-space to configure that.
3301          */
3302         case DRM_FORMAT_ABGR8888:
3303                 return PLANE_CTL_FORMAT_XRGB_8888 | PLANE_CTL_ORDER_RGBX |
3304                         PLANE_CTL_ALPHA_SW_PREMULTIPLY;
3305         case DRM_FORMAT_ARGB8888:
3306                 return PLANE_CTL_FORMAT_XRGB_8888 |
3307                         PLANE_CTL_ALPHA_SW_PREMULTIPLY;
3308         case DRM_FORMAT_XRGB2101010:
3309                 return PLANE_CTL_FORMAT_XRGB_2101010;
3310         case DRM_FORMAT_XBGR2101010:
3311                 return PLANE_CTL_ORDER_RGBX | PLANE_CTL_FORMAT_XRGB_2101010;
3312         case DRM_FORMAT_YUYV:
3313                 return PLANE_CTL_FORMAT_YUV422 | PLANE_CTL_YUV422_YUYV;
3314         case DRM_FORMAT_YVYU:
3315                 return PLANE_CTL_FORMAT_YUV422 | PLANE_CTL_YUV422_YVYU;
3316         case DRM_FORMAT_UYVY:
3317                 return PLANE_CTL_FORMAT_YUV422 | PLANE_CTL_YUV422_UYVY;
3318         case DRM_FORMAT_VYUY:
3319                 return PLANE_CTL_FORMAT_YUV422 | PLANE_CTL_YUV422_VYUY;
3320         default:
3321                 MISSING_CASE(pixel_format);
3322         }
3323
3324         return 0;
3325 }
3326
3327 u32 skl_plane_ctl_tiling(uint64_t fb_modifier)
3328 {
3329         switch (fb_modifier) {
3330         case DRM_FORMAT_MOD_NONE:
3331                 break;
3332         case I915_FORMAT_MOD_X_TILED:
3333                 return PLANE_CTL_TILED_X;
3334         case I915_FORMAT_MOD_Y_TILED:
3335                 return PLANE_CTL_TILED_Y;
3336         case I915_FORMAT_MOD_Yf_TILED:
3337                 return PLANE_CTL_TILED_YF;
3338         default:
3339                 MISSING_CASE(fb_modifier);
3340         }
3341
3342         return 0;
3343 }
3344
3345 u32 skl_plane_ctl_rotation(unsigned int rotation)
3346 {
3347         switch (rotation) {
3348         case DRM_ROTATE_0:
3349                 break;
3350         /*
3351          * DRM_ROTATE_ is counter clockwise to stay compatible with Xrandr
3352          * while i915 HW rotation is clockwise, thats why this swapping.
3353          */
3354         case DRM_ROTATE_90:
3355                 return PLANE_CTL_ROTATE_270;
3356         case DRM_ROTATE_180:
3357                 return PLANE_CTL_ROTATE_180;
3358         case DRM_ROTATE_270:
3359                 return PLANE_CTL_ROTATE_90;
3360         default:
3361                 MISSING_CASE(rotation);
3362         }
3363
3364         return 0;
3365 }
3366
3367 static void skylake_update_primary_plane(struct drm_plane *plane,
3368                                          const struct intel_crtc_state *crtc_state,
3369                                          const struct intel_plane_state *plane_state)
3370 {
3371         struct drm_device *dev = plane->dev;
3372         struct drm_i915_private *dev_priv = to_i915(dev);
3373         struct intel_crtc *intel_crtc = to_intel_crtc(crtc_state->base.crtc);
3374         struct drm_framebuffer *fb = plane_state->base.fb;
3375         const struct skl_wm_values *wm = &dev_priv->wm.skl_results;
3376         int pipe = intel_crtc->pipe;
3377         u32 plane_ctl;
3378         unsigned int rotation = plane_state->base.rotation;
3379         u32 stride = skl_plane_stride(fb, 0, rotation);
3380         u32 surf_addr = plane_state->main.offset;
3381         int scaler_id = plane_state->scaler_id;
3382         int src_x = plane_state->main.x;
3383         int src_y = plane_state->main.y;
3384         int src_w = drm_rect_width(&plane_state->base.src) >> 16;
3385         int src_h = drm_rect_height(&plane_state->base.src) >> 16;
3386         int dst_x = plane_state->base.dst.x1;
3387         int dst_y = plane_state->base.dst.y1;
3388         int dst_w = drm_rect_width(&plane_state->base.dst);
3389         int dst_h = drm_rect_height(&plane_state->base.dst);
3390
3391         plane_ctl = PLANE_CTL_ENABLE |
3392                     PLANE_CTL_PIPE_GAMMA_ENABLE |
3393                     PLANE_CTL_PIPE_CSC_ENABLE;
3394
3395         plane_ctl |= skl_plane_ctl_format(fb->pixel_format);
3396         plane_ctl |= skl_plane_ctl_tiling(fb->modifier[0]);
3397         plane_ctl |= PLANE_CTL_PLANE_GAMMA_DISABLE;
3398         plane_ctl |= skl_plane_ctl_rotation(rotation);
3399
3400         /* Sizes are 0 based */
3401         src_w--;
3402         src_h--;
3403         dst_w--;
3404         dst_h--;
3405
3406         intel_crtc->dspaddr_offset = surf_addr;
3407
3408         intel_crtc->adjusted_x = src_x;
3409         intel_crtc->adjusted_y = src_y;
3410
3411         if (wm->dirty_pipes & drm_crtc_mask(&intel_crtc->base))
3412                 skl_write_plane_wm(intel_crtc, wm, 0);
3413
3414         I915_WRITE(PLANE_CTL(pipe, 0), plane_ctl);
3415         I915_WRITE(PLANE_OFFSET(pipe, 0), (src_y << 16) | src_x);
3416         I915_WRITE(PLANE_STRIDE(pipe, 0), stride);
3417         I915_WRITE(PLANE_SIZE(pipe, 0), (src_h << 16) | src_w);
3418
3419         if (scaler_id >= 0) {
3420                 uint32_t ps_ctrl = 0;
3421
3422                 WARN_ON(!dst_w || !dst_h);
3423                 ps_ctrl = PS_SCALER_EN | PS_PLANE_SEL(0) |
3424                         crtc_state->scaler_state.scalers[scaler_id].mode;
3425                 I915_WRITE(SKL_PS_CTRL(pipe, scaler_id), ps_ctrl);
3426                 I915_WRITE(SKL_PS_PWR_GATE(pipe, scaler_id), 0);
3427                 I915_WRITE(SKL_PS_WIN_POS(pipe, scaler_id), (dst_x << 16) | dst_y);
3428                 I915_WRITE(SKL_PS_WIN_SZ(pipe, scaler_id), (dst_w << 16) | dst_h);
3429                 I915_WRITE(PLANE_POS(pipe, 0), 0);
3430         } else {
3431                 I915_WRITE(PLANE_POS(pipe, 0), (dst_y << 16) | dst_x);
3432         }
3433
3434         I915_WRITE(PLANE_SURF(pipe, 0),
3435                    intel_fb_gtt_offset(fb, rotation) + surf_addr);
3436
3437         POSTING_READ(PLANE_SURF(pipe, 0));
3438 }
3439
3440 static void skylake_disable_primary_plane(struct drm_plane *primary,
3441                                           struct drm_crtc *crtc)
3442 {
3443         struct drm_device *dev = crtc->dev;
3444         struct drm_i915_private *dev_priv = to_i915(dev);
3445         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
3446         int pipe = intel_crtc->pipe;
3447
3448         /*
3449          * We only populate skl_results on watermark updates, and if the
3450          * plane's visiblity isn't actually changing neither is its watermarks.
3451          */
3452         if (!crtc->primary->state->visible)
3453                 skl_write_plane_wm(intel_crtc, &dev_priv->wm.skl_results, 0);
3454
3455         I915_WRITE(PLANE_CTL(pipe, 0), 0);
3456         I915_WRITE(PLANE_SURF(pipe, 0), 0);
3457         POSTING_READ(PLANE_SURF(pipe, 0));
3458 }
3459
3460 /* Assume fb object is pinned & idle & fenced and just update base pointers */
3461 static int
3462 intel_pipe_set_base_atomic(struct drm_crtc *crtc, struct drm_framebuffer *fb,
3463                            int x, int y, enum mode_set_atomic state)
3464 {
3465         /* Support for kgdboc is disabled, this needs a major rework. */
3466         DRM_ERROR("legacy panic handler not supported any more.\n");
3467
3468         return -ENODEV;
3469 }
3470
3471 static void intel_complete_page_flips(struct drm_i915_private *dev_priv)
3472 {
3473         struct intel_crtc *crtc;
3474
3475         for_each_intel_crtc(&dev_priv->drm, crtc)
3476                 intel_finish_page_flip_cs(dev_priv, crtc->pipe);
3477 }
3478
3479 static void intel_update_primary_planes(struct drm_device *dev)
3480 {
3481         struct drm_crtc *crtc;
3482
3483         for_each_crtc(dev, crtc) {
3484                 struct intel_plane *plane = to_intel_plane(crtc->primary);
3485                 struct intel_plane_state *plane_state =
3486                         to_intel_plane_state(plane->base.state);
3487
3488                 if (plane_state->base.visible)
3489                         plane->update_plane(&plane->base,
3490                                             to_intel_crtc_state(crtc->state),
3491                                             plane_state);
3492         }
3493 }
3494
3495 static int
3496 __intel_display_resume(struct drm_device *dev,
3497                        struct drm_atomic_state *state)
3498 {
3499         struct drm_crtc_state *crtc_state;
3500         struct drm_crtc *crtc;
3501         int i, ret;
3502
3503         intel_modeset_setup_hw_state(dev);
3504         i915_redisable_vga(dev);
3505
3506         if (!state)
3507                 return 0;
3508
3509         for_each_crtc_in_state(state, crtc, crtc_state, i) {
3510                 /*
3511                  * Force recalculation even if we restore
3512                  * current state. With fast modeset this may not result
3513                  * in a modeset when the state is compatible.
3514                  */
3515                 crtc_state->mode_changed = true;
3516         }
3517
3518         /* ignore any reset values/BIOS leftovers in the WM registers */
3519         to_intel_atomic_state(state)->skip_intermediate_wm = true;
3520
3521         ret = drm_atomic_commit(state);
3522
3523         WARN_ON(ret == -EDEADLK);
3524         return ret;
3525 }
3526
3527 static bool gpu_reset_clobbers_display(struct drm_i915_private *dev_priv)
3528 {
3529         return intel_has_gpu_reset(dev_priv) &&
3530                 INTEL_GEN(dev_priv) < 5 && !IS_G4X(dev_priv);
3531 }
3532
3533 void intel_prepare_reset(struct drm_i915_private *dev_priv)
3534 {
3535         struct drm_device *dev = &dev_priv->drm;
3536         struct drm_modeset_acquire_ctx *ctx = &dev_priv->reset_ctx;
3537         struct drm_atomic_state *state;
3538         int ret;
3539
3540         /*
3541          * Need mode_config.mutex so that we don't
3542          * trample ongoing ->detect() and whatnot.
3543          */
3544         mutex_lock(&dev->mode_config.mutex);
3545         drm_modeset_acquire_init(ctx, 0);
3546         while (1) {
3547                 ret = drm_modeset_lock_all_ctx(dev, ctx);
3548                 if (ret != -EDEADLK)
3549                         break;
3550
3551                 drm_modeset_backoff(ctx);
3552         }
3553
3554         /* reset doesn't touch the display, but flips might get nuked anyway, */
3555         if (!i915.force_reset_modeset_test &&
3556             !gpu_reset_clobbers_display(dev_priv))
3557                 return;
3558
3559         /*
3560          * Disabling the crtcs gracefully seems nicer. Also the
3561          * g33 docs say we should at least disable all the planes.
3562          */
3563         state = drm_atomic_helper_duplicate_state(dev, ctx);
3564         if (IS_ERR(state)) {
3565                 ret = PTR_ERR(state);
3566                 state = NULL;
3567                 DRM_ERROR("Duplicating state failed with %i\n", ret);
3568                 goto err;
3569         }
3570
3571         ret = drm_atomic_helper_disable_all(dev, ctx);
3572         if (ret) {
3573                 DRM_ERROR("Suspending crtc's failed with %i\n", ret);
3574                 goto err;
3575         }
3576
3577         dev_priv->modeset_restore_state = state;
3578         state->acquire_ctx = ctx;
3579         return;
3580
3581 err:
3582         drm_atomic_state_free(state);
3583 }
3584
3585 void intel_finish_reset(struct drm_i915_private *dev_priv)
3586 {
3587         struct drm_device *dev = &dev_priv->drm;
3588         struct drm_modeset_acquire_ctx *ctx = &dev_priv->reset_ctx;
3589         struct drm_atomic_state *state = dev_priv->modeset_restore_state;
3590         int ret;
3591
3592         /*
3593          * Flips in the rings will be nuked by the reset,
3594          * so complete all pending flips so that user space
3595          * will get its events and not get stuck.
3596          */
3597         intel_complete_page_flips(dev_priv);
3598
3599         dev_priv->modeset_restore_state = NULL;
3600
3601         /* reset doesn't touch the display */
3602         if (!gpu_reset_clobbers_display(dev_priv)) {
3603                 if (!state) {
3604                         /*
3605                          * Flips in the rings have been nuked by the reset,
3606                          * so update the base address of all primary
3607                          * planes to the the last fb to make sure we're
3608                          * showing the correct fb after a reset.
3609                          *
3610                          * FIXME: Atomic will make this obsolete since we won't schedule
3611                          * CS-based flips (which might get lost in gpu resets) any more.
3612                          */
3613                         intel_update_primary_planes(dev);
3614                 } else {
3615                         ret = __intel_display_resume(dev, state);
3616                         if (ret)
3617                                 DRM_ERROR("Restoring old state failed with %i\n", ret);
3618                 }
3619         } else {
3620                 /*
3621                  * The display has been reset as well,
3622                  * so need a full re-initialization.
3623                  */
3624                 intel_runtime_pm_disable_interrupts(dev_priv);
3625                 intel_runtime_pm_enable_interrupts(dev_priv);
3626
3627                 intel_pps_unlock_regs_wa(dev_priv);
3628                 intel_modeset_init_hw(dev);
3629
3630                 spin_lock_irq(&dev_priv->irq_lock);
3631                 if (dev_priv->display.hpd_irq_setup)
3632                         dev_priv->display.hpd_irq_setup(dev_priv);
3633                 spin_unlock_irq(&dev_priv->irq_lock);
3634
3635                 ret = __intel_display_resume(dev, state);
3636                 if (ret)
3637                         DRM_ERROR("Restoring old state failed with %i\n", ret);
3638
3639                 intel_hpd_init(dev_priv);
3640         }
3641
3642         drm_modeset_drop_locks(ctx);
3643         drm_modeset_acquire_fini(ctx);
3644         mutex_unlock(&dev->mode_config.mutex);
3645 }
3646
3647 static bool abort_flip_on_reset(struct intel_crtc *crtc)
3648 {
3649         struct i915_gpu_error *error = &to_i915(crtc->base.dev)->gpu_error;
3650
3651         if (i915_reset_in_progress(error))
3652                 return true;
3653
3654         if (crtc->reset_count != i915_reset_count(error))
3655                 return true;
3656
3657         return false;
3658 }
3659
3660 static bool intel_crtc_has_pending_flip(struct drm_crtc *crtc)
3661 {
3662         struct drm_device *dev = crtc->dev;
3663         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
3664         bool pending;
3665
3666         if (abort_flip_on_reset(intel_crtc))
3667                 return false;
3668
3669         spin_lock_irq(&dev->event_lock);
3670         pending = to_intel_crtc(crtc)->flip_work != NULL;
3671         spin_unlock_irq(&dev->event_lock);
3672
3673         return pending;
3674 }
3675
3676 static void intel_update_pipe_config(struct intel_crtc *crtc,
3677                                      struct intel_crtc_state *old_crtc_state)
3678 {
3679         struct drm_device *dev = crtc->base.dev;
3680         struct drm_i915_private *dev_priv = to_i915(dev);
3681         struct intel_crtc_state *pipe_config =
3682                 to_intel_crtc_state(crtc->base.state);
3683
3684         /* drm_atomic_helper_update_legacy_modeset_state might not be called. */
3685         crtc->base.mode = crtc->base.state->mode;
3686
3687         DRM_DEBUG_KMS("Updating pipe size %ix%i -> %ix%i\n",
3688                       old_crtc_state->pipe_src_w, old_crtc_state->pipe_src_h,
3689                       pipe_config->pipe_src_w, pipe_config->pipe_src_h);
3690
3691         /*
3692          * Update pipe size and adjust fitter if needed: the reason for this is
3693          * that in compute_mode_changes we check the native mode (not the pfit
3694          * mode) to see if we can flip rather than do a full mode set. In the
3695          * fastboot case, we'll flip, but if we don't update the pipesrc and
3696          * pfit state, we'll end up with a big fb scanned out into the wrong
3697          * sized surface.
3698          */
3699
3700         I915_WRITE(PIPESRC(crtc->pipe),
3701                    ((pipe_config->pipe_src_w - 1) << 16) |
3702                    (pipe_config->pipe_src_h - 1));
3703
3704         /* on skylake this is done by detaching scalers */
3705         if (INTEL_INFO(dev)->gen >= 9) {
3706                 skl_detach_scalers(crtc);
3707
3708                 if (pipe_config->pch_pfit.enabled)
3709                         skylake_pfit_enable(crtc);
3710         } else if (HAS_PCH_SPLIT(dev_priv)) {
3711                 if (pipe_config->pch_pfit.enabled)
3712                         ironlake_pfit_enable(crtc);
3713                 else if (old_crtc_state->pch_pfit.enabled)
3714                         ironlake_pfit_disable(crtc, true);
3715         }
3716 }
3717
3718 static void intel_fdi_normal_train(struct drm_crtc *crtc)
3719 {
3720         struct drm_device *dev = crtc->dev;
3721         struct drm_i915_private *dev_priv = to_i915(dev);
3722         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
3723         int pipe = intel_crtc->pipe;
3724         i915_reg_t reg;
3725         u32 temp;
3726
3727         /* enable normal train */
3728         reg = FDI_TX_CTL(pipe);
3729         temp = I915_READ(reg);
3730         if (IS_IVYBRIDGE(dev_priv)) {
3731                 temp &= ~FDI_LINK_TRAIN_NONE_IVB;
3732                 temp |= FDI_LINK_TRAIN_NONE_IVB | FDI_TX_ENHANCE_FRAME_ENABLE;
3733         } else {
3734                 temp &= ~FDI_LINK_TRAIN_NONE;
3735                 temp |= FDI_LINK_TRAIN_NONE | FDI_TX_ENHANCE_FRAME_ENABLE;
3736         }
3737         I915_WRITE(reg, temp);
3738
3739         reg = FDI_RX_CTL(pipe);
3740         temp = I915_READ(reg);
3741         if (HAS_PCH_CPT(dev_priv)) {
3742                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
3743                 temp |= FDI_LINK_TRAIN_NORMAL_CPT;
3744         } else {
3745                 temp &= ~FDI_LINK_TRAIN_NONE;
3746                 temp |= FDI_LINK_TRAIN_NONE;
3747         }
3748         I915_WRITE(reg, temp | FDI_RX_ENHANCE_FRAME_ENABLE);
3749
3750         /* wait one idle pattern time */
3751         POSTING_READ(reg);
3752         udelay(1000);
3753
3754         /* IVB wants error correction enabled */
3755         if (IS_IVYBRIDGE(dev_priv))
3756                 I915_WRITE(reg, I915_READ(reg) | FDI_FS_ERRC_ENABLE |
3757                            FDI_FE_ERRC_ENABLE);
3758 }
3759
3760 /* The FDI link training functions for ILK/Ibexpeak. */
3761 static void ironlake_fdi_link_train(struct drm_crtc *crtc)
3762 {
3763         struct drm_device *dev = crtc->dev;
3764         struct drm_i915_private *dev_priv = to_i915(dev);
3765         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
3766         int pipe = intel_crtc->pipe;
3767         i915_reg_t reg;
3768         u32 temp, tries;
3769
3770         /* FDI needs bits from pipe first */
3771         assert_pipe_enabled(dev_priv, pipe);
3772
3773         /* Train 1: umask FDI RX Interrupt symbol_lock and bit_lock bit
3774            for train result */
3775         reg = FDI_RX_IMR(pipe);
3776         temp = I915_READ(reg);
3777         temp &= ~FDI_RX_SYMBOL_LOCK;
3778         temp &= ~FDI_RX_BIT_LOCK;
3779         I915_WRITE(reg, temp);
3780         I915_READ(reg);
3781         udelay(150);
3782
3783         /* enable CPU FDI TX and PCH FDI RX */
3784         reg = FDI_TX_CTL(pipe);
3785         temp = I915_READ(reg);
3786         temp &= ~FDI_DP_PORT_WIDTH_MASK;
3787         temp |= FDI_DP_PORT_WIDTH(intel_crtc->config->fdi_lanes);
3788         temp &= ~FDI_LINK_TRAIN_NONE;
3789         temp |= FDI_LINK_TRAIN_PATTERN_1;
3790         I915_WRITE(reg, temp | FDI_TX_ENABLE);
3791
3792         reg = FDI_RX_CTL(pipe);
3793         temp = I915_READ(reg);
3794         temp &= ~FDI_LINK_TRAIN_NONE;
3795         temp |= FDI_LINK_TRAIN_PATTERN_1;
3796         I915_WRITE(reg, temp | FDI_RX_ENABLE);
3797
3798         POSTING_READ(reg);
3799         udelay(150);
3800
3801         /* Ironlake workaround, enable clock pointer after FDI enable*/
3802         I915_WRITE(FDI_RX_CHICKEN(pipe), FDI_RX_PHASE_SYNC_POINTER_OVR);
3803         I915_WRITE(FDI_RX_CHICKEN(pipe), FDI_RX_PHASE_SYNC_POINTER_OVR |
3804                    FDI_RX_PHASE_SYNC_POINTER_EN);
3805
3806         reg = FDI_RX_IIR(pipe);
3807         for (tries = 0; tries < 5; tries++) {
3808                 temp = I915_READ(reg);
3809                 DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
3810
3811                 if ((temp & FDI_RX_BIT_LOCK)) {
3812                         DRM_DEBUG_KMS("FDI train 1 done.\n");
3813                         I915_WRITE(reg, temp | FDI_RX_BIT_LOCK);
3814                         break;
3815                 }
3816         }
3817         if (tries == 5)
3818                 DRM_ERROR("FDI train 1 fail!\n");
3819
3820         /* Train 2 */
3821         reg = FDI_TX_CTL(pipe);
3822         temp = I915_READ(reg);
3823         temp &= ~FDI_LINK_TRAIN_NONE;
3824         temp |= FDI_LINK_TRAIN_PATTERN_2;
3825         I915_WRITE(reg, temp);
3826
3827         reg = FDI_RX_CTL(pipe);
3828         temp = I915_READ(reg);
3829         temp &= ~FDI_LINK_TRAIN_NONE;
3830         temp |= FDI_LINK_TRAIN_PATTERN_2;
3831         I915_WRITE(reg, temp);
3832
3833         POSTING_READ(reg);
3834         udelay(150);
3835
3836         reg = FDI_RX_IIR(pipe);
3837         for (tries = 0; tries < 5; tries++) {
3838                 temp = I915_READ(reg);
3839                 DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
3840
3841                 if (temp & FDI_RX_SYMBOL_LOCK) {
3842                         I915_WRITE(reg, temp | FDI_RX_SYMBOL_LOCK);
3843                         DRM_DEBUG_KMS("FDI train 2 done.\n");
3844                         break;
3845                 }
3846         }
3847         if (tries == 5)
3848                 DRM_ERROR("FDI train 2 fail!\n");
3849
3850         DRM_DEBUG_KMS("FDI train done\n");
3851
3852 }
3853
3854 static const int snb_b_fdi_train_param[] = {
3855         FDI_LINK_TRAIN_400MV_0DB_SNB_B,
3856         FDI_LINK_TRAIN_400MV_6DB_SNB_B,
3857         FDI_LINK_TRAIN_600MV_3_5DB_SNB_B,
3858         FDI_LINK_TRAIN_800MV_0DB_SNB_B,
3859 };
3860
3861 /* The FDI link training functions for SNB/Cougarpoint. */
3862 static void gen6_fdi_link_train(struct drm_crtc *crtc)
3863 {
3864         struct drm_device *dev = crtc->dev;
3865         struct drm_i915_private *dev_priv = to_i915(dev);
3866         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
3867         int pipe = intel_crtc->pipe;
3868         i915_reg_t reg;
3869         u32 temp, i, retry;
3870
3871         /* Train 1: umask FDI RX Interrupt symbol_lock and bit_lock bit
3872            for train result */
3873         reg = FDI_RX_IMR(pipe);
3874         temp = I915_READ(reg);
3875         temp &= ~FDI_RX_SYMBOL_LOCK;
3876         temp &= ~FDI_RX_BIT_LOCK;
3877         I915_WRITE(reg, temp);
3878
3879         POSTING_READ(reg);
3880         udelay(150);
3881
3882         /* enable CPU FDI TX and PCH FDI RX */
3883         reg = FDI_TX_CTL(pipe);
3884         temp = I915_READ(reg);
3885         temp &= ~FDI_DP_PORT_WIDTH_MASK;
3886         temp |= FDI_DP_PORT_WIDTH(intel_crtc->config->fdi_lanes);
3887         temp &= ~FDI_LINK_TRAIN_NONE;
3888         temp |= FDI_LINK_TRAIN_PATTERN_1;
3889         temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
3890         /* SNB-B */
3891         temp |= FDI_LINK_TRAIN_400MV_0DB_SNB_B;
3892         I915_WRITE(reg, temp | FDI_TX_ENABLE);
3893
3894         I915_WRITE(FDI_RX_MISC(pipe),
3895                    FDI_RX_TP1_TO_TP2_48 | FDI_RX_FDI_DELAY_90);
3896
3897         reg = FDI_RX_CTL(pipe);
3898         temp = I915_READ(reg);
3899         if (HAS_PCH_CPT(dev_priv)) {
3900                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
3901                 temp |= FDI_LINK_TRAIN_PATTERN_1_CPT;
3902         } else {
3903                 temp &= ~FDI_LINK_TRAIN_NONE;
3904                 temp |= FDI_LINK_TRAIN_PATTERN_1;
3905         }
3906         I915_WRITE(reg, temp | FDI_RX_ENABLE);
3907
3908         POSTING_READ(reg);
3909         udelay(150);
3910
3911         for (i = 0; i < 4; i++) {
3912                 reg = FDI_TX_CTL(pipe);
3913                 temp = I915_READ(reg);
3914                 temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
3915                 temp |= snb_b_fdi_train_param[i];
3916                 I915_WRITE(reg, temp);
3917
3918                 POSTING_READ(reg);
3919                 udelay(500);
3920
3921                 for (retry = 0; retry < 5; retry++) {
3922                         reg = FDI_RX_IIR(pipe);
3923                         temp = I915_READ(reg);
3924                         DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
3925                         if (temp & FDI_RX_BIT_LOCK) {
3926                                 I915_WRITE(reg, temp | FDI_RX_BIT_LOCK);
3927                                 DRM_DEBUG_KMS("FDI train 1 done.\n");
3928                                 break;
3929                         }
3930                         udelay(50);
3931                 }
3932                 if (retry < 5)
3933                         break;
3934         }
3935         if (i == 4)
3936                 DRM_ERROR("FDI train 1 fail!\n");
3937
3938         /* Train 2 */
3939         reg = FDI_TX_CTL(pipe);
3940         temp = I915_READ(reg);
3941         temp &= ~FDI_LINK_TRAIN_NONE;
3942         temp |= FDI_LINK_TRAIN_PATTERN_2;
3943         if (IS_GEN6(dev)) {
3944                 temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
3945                 /* SNB-B */
3946                 temp |= FDI_LINK_TRAIN_400MV_0DB_SNB_B;
3947         }
3948         I915_WRITE(reg, temp);
3949
3950         reg = FDI_RX_CTL(pipe);
3951         temp = I915_READ(reg);
3952         if (HAS_PCH_CPT(dev_priv)) {
3953                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
3954                 temp |= FDI_LINK_TRAIN_PATTERN_2_CPT;
3955         } else {
3956                 temp &= ~FDI_LINK_TRAIN_NONE;
3957                 temp |= FDI_LINK_TRAIN_PATTERN_2;
3958         }
3959         I915_WRITE(reg, temp);
3960
3961         POSTING_READ(reg);
3962         udelay(150);
3963
3964         for (i = 0; i < 4; i++) {
3965                 reg = FDI_TX_CTL(pipe);
3966                 temp = I915_READ(reg);
3967                 temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
3968                 temp |= snb_b_fdi_train_param[i];
3969                 I915_WRITE(reg, temp);
3970
3971                 POSTING_READ(reg);
3972                 udelay(500);
3973
3974                 for (retry = 0; retry < 5; retry++) {
3975                         reg = FDI_RX_IIR(pipe);
3976                         temp = I915_READ(reg);
3977                         DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
3978                         if (temp & FDI_RX_SYMBOL_LOCK) {
3979                                 I915_WRITE(reg, temp | FDI_RX_SYMBOL_LOCK);
3980                                 DRM_DEBUG_KMS("FDI train 2 done.\n");
3981                                 break;
3982                         }
3983                         udelay(50);
3984                 }
3985                 if (retry < 5)
3986                         break;
3987         }
3988         if (i == 4)
3989                 DRM_ERROR("FDI train 2 fail!\n");
3990
3991         DRM_DEBUG_KMS("FDI train done.\n");
3992 }
3993
3994 /* Manual link training for Ivy Bridge A0 parts */
3995 static void ivb_manual_fdi_link_train(struct drm_crtc *crtc)
3996 {
3997         struct drm_device *dev = crtc->dev;
3998         struct drm_i915_private *dev_priv = to_i915(dev);
3999         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4000         int pipe = intel_crtc->pipe;
4001         i915_reg_t reg;
4002         u32 temp, i, j;
4003
4004         /* Train 1: umask FDI RX Interrupt symbol_lock and bit_lock bit
4005            for train result */
4006         reg = FDI_RX_IMR(pipe);
4007         temp = I915_READ(reg);
4008         temp &= ~FDI_RX_SYMBOL_LOCK;
4009         temp &= ~FDI_RX_BIT_LOCK;
4010         I915_WRITE(reg, temp);
4011
4012         POSTING_READ(reg);
4013         udelay(150);
4014
4015         DRM_DEBUG_KMS("FDI_RX_IIR before link train 0x%x\n",
4016                       I915_READ(FDI_RX_IIR(pipe)));
4017
4018         /* Try each vswing and preemphasis setting twice before moving on */
4019         for (j = 0; j < ARRAY_SIZE(snb_b_fdi_train_param) * 2; j++) {
4020                 /* disable first in case we need to retry */
4021                 reg = FDI_TX_CTL(pipe);
4022                 temp = I915_READ(reg);
4023                 temp &= ~(FDI_LINK_TRAIN_AUTO | FDI_LINK_TRAIN_NONE_IVB);
4024                 temp &= ~FDI_TX_ENABLE;
4025                 I915_WRITE(reg, temp);
4026
4027                 reg = FDI_RX_CTL(pipe);
4028                 temp = I915_READ(reg);
4029                 temp &= ~FDI_LINK_TRAIN_AUTO;
4030                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
4031                 temp &= ~FDI_RX_ENABLE;
4032                 I915_WRITE(reg, temp);
4033
4034                 /* enable CPU FDI TX and PCH FDI RX */
4035                 reg = FDI_TX_CTL(pipe);
4036                 temp = I915_READ(reg);
4037                 temp &= ~FDI_DP_PORT_WIDTH_MASK;
4038                 temp |= FDI_DP_PORT_WIDTH(intel_crtc->config->fdi_lanes);
4039                 temp |= FDI_LINK_TRAIN_PATTERN_1_IVB;
4040                 temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
4041                 temp |= snb_b_fdi_train_param[j/2];
4042                 temp |= FDI_COMPOSITE_SYNC;
4043                 I915_WRITE(reg, temp | FDI_TX_ENABLE);
4044
4045                 I915_WRITE(FDI_RX_MISC(pipe),
4046                            FDI_RX_TP1_TO_TP2_48 | FDI_RX_FDI_DELAY_90);
4047
4048                 reg = FDI_RX_CTL(pipe);
4049                 temp = I915_READ(reg);
4050                 temp |= FDI_LINK_TRAIN_PATTERN_1_CPT;
4051                 temp |= FDI_COMPOSITE_SYNC;
4052                 I915_WRITE(reg, temp | FDI_RX_ENABLE);
4053
4054                 POSTING_READ(reg);
4055                 udelay(1); /* should be 0.5us */
4056
4057                 for (i = 0; i < 4; i++) {
4058                         reg = FDI_RX_IIR(pipe);
4059                         temp = I915_READ(reg);
4060                         DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
4061
4062                         if (temp & FDI_RX_BIT_LOCK ||
4063                             (I915_READ(reg) & FDI_RX_BIT_LOCK)) {
4064                                 I915_WRITE(reg, temp | FDI_RX_BIT_LOCK);
4065                                 DRM_DEBUG_KMS("FDI train 1 done, level %i.\n",
4066                                               i);
4067                                 break;
4068                         }
4069                         udelay(1); /* should be 0.5us */
4070                 }
4071                 if (i == 4) {
4072                         DRM_DEBUG_KMS("FDI train 1 fail on vswing %d\n", j / 2);
4073                         continue;
4074                 }
4075
4076                 /* Train 2 */
4077                 reg = FDI_TX_CTL(pipe);
4078                 temp = I915_READ(reg);
4079                 temp &= ~FDI_LINK_TRAIN_NONE_IVB;
4080                 temp |= FDI_LINK_TRAIN_PATTERN_2_IVB;
4081                 I915_WRITE(reg, temp);
4082
4083                 reg = FDI_RX_CTL(pipe);
4084                 temp = I915_READ(reg);
4085                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
4086                 temp |= FDI_LINK_TRAIN_PATTERN_2_CPT;
4087                 I915_WRITE(reg, temp);
4088
4089                 POSTING_READ(reg);
4090                 udelay(2); /* should be 1.5us */
4091
4092                 for (i = 0; i < 4; i++) {
4093                         reg = FDI_RX_IIR(pipe);
4094                         temp = I915_READ(reg);
4095                         DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
4096
4097                         if (temp & FDI_RX_SYMBOL_LOCK ||
4098                             (I915_READ(reg) & FDI_RX_SYMBOL_LOCK)) {
4099                                 I915_WRITE(reg, temp | FDI_RX_SYMBOL_LOCK);
4100                                 DRM_DEBUG_KMS("FDI train 2 done, level %i.\n",
4101                                               i);
4102                                 goto train_done;
4103                         }
4104                         udelay(2); /* should be 1.5us */
4105                 }
4106                 if (i == 4)
4107                         DRM_DEBUG_KMS("FDI train 2 fail on vswing %d\n", j / 2);
4108         }
4109
4110 train_done:
4111         DRM_DEBUG_KMS("FDI train done.\n");
4112 }
4113
4114 static void ironlake_fdi_pll_enable(struct intel_crtc *intel_crtc)
4115 {
4116         struct drm_device *dev = intel_crtc->base.dev;
4117         struct drm_i915_private *dev_priv = to_i915(dev);
4118         int pipe = intel_crtc->pipe;
4119         i915_reg_t reg;
4120         u32 temp;
4121
4122         /* enable PCH FDI RX PLL, wait warmup plus DMI latency */
4123         reg = FDI_RX_CTL(pipe);
4124         temp = I915_READ(reg);
4125         temp &= ~(FDI_DP_PORT_WIDTH_MASK | (0x7 << 16));
4126         temp |= FDI_DP_PORT_WIDTH(intel_crtc->config->fdi_lanes);
4127         temp |= (I915_READ(PIPECONF(pipe)) & PIPECONF_BPC_MASK) << 11;
4128         I915_WRITE(reg, temp | FDI_RX_PLL_ENABLE);
4129
4130         POSTING_READ(reg);
4131         udelay(200);
4132
4133         /* Switch from Rawclk to PCDclk */
4134         temp = I915_READ(reg);
4135         I915_WRITE(reg, temp | FDI_PCDCLK);
4136
4137         POSTING_READ(reg);
4138         udelay(200);
4139
4140         /* Enable CPU FDI TX PLL, always on for Ironlake */
4141         reg = FDI_TX_CTL(pipe);
4142         temp = I915_READ(reg);
4143         if ((temp & FDI_TX_PLL_ENABLE) == 0) {
4144                 I915_WRITE(reg, temp | FDI_TX_PLL_ENABLE);
4145
4146                 POSTING_READ(reg);
4147                 udelay(100);
4148         }
4149 }
4150
4151 static void ironlake_fdi_pll_disable(struct intel_crtc *intel_crtc)
4152 {
4153         struct drm_device *dev = intel_crtc->base.dev;
4154         struct drm_i915_private *dev_priv = to_i915(dev);
4155         int pipe = intel_crtc->pipe;
4156         i915_reg_t reg;
4157         u32 temp;
4158
4159         /* Switch from PCDclk to Rawclk */
4160         reg = FDI_RX_CTL(pipe);
4161         temp = I915_READ(reg);
4162         I915_WRITE(reg, temp & ~FDI_PCDCLK);
4163
4164         /* Disable CPU FDI TX PLL */
4165         reg = FDI_TX_CTL(pipe);
4166         temp = I915_READ(reg);
4167         I915_WRITE(reg, temp & ~FDI_TX_PLL_ENABLE);
4168
4169         POSTING_READ(reg);
4170         udelay(100);
4171
4172         reg = FDI_RX_CTL(pipe);
4173         temp = I915_READ(reg);
4174         I915_WRITE(reg, temp & ~FDI_RX_PLL_ENABLE);
4175
4176         /* Wait for the clocks to turn off. */
4177         POSTING_READ(reg);
4178         udelay(100);
4179 }
4180
4181 static void ironlake_fdi_disable(struct drm_crtc *crtc)
4182 {
4183         struct drm_device *dev = crtc->dev;
4184         struct drm_i915_private *dev_priv = to_i915(dev);
4185         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4186         int pipe = intel_crtc->pipe;
4187         i915_reg_t reg;
4188         u32 temp;
4189
4190         /* disable CPU FDI tx and PCH FDI rx */
4191         reg = FDI_TX_CTL(pipe);
4192         temp = I915_READ(reg);
4193         I915_WRITE(reg, temp & ~FDI_TX_ENABLE);
4194         POSTING_READ(reg);
4195
4196         reg = FDI_RX_CTL(pipe);
4197         temp = I915_READ(reg);
4198         temp &= ~(0x7 << 16);
4199         temp |= (I915_READ(PIPECONF(pipe)) & PIPECONF_BPC_MASK) << 11;
4200         I915_WRITE(reg, temp & ~FDI_RX_ENABLE);
4201
4202         POSTING_READ(reg);
4203         udelay(100);
4204
4205         /* Ironlake workaround, disable clock pointer after downing FDI */
4206         if (HAS_PCH_IBX(dev_priv))
4207                 I915_WRITE(FDI_RX_CHICKEN(pipe), FDI_RX_PHASE_SYNC_POINTER_OVR);
4208
4209         /* still set train pattern 1 */
4210         reg = FDI_TX_CTL(pipe);
4211         temp = I915_READ(reg);
4212         temp &= ~FDI_LINK_TRAIN_NONE;
4213         temp |= FDI_LINK_TRAIN_PATTERN_1;
4214         I915_WRITE(reg, temp);
4215
4216         reg = FDI_RX_CTL(pipe);
4217         temp = I915_READ(reg);
4218         if (HAS_PCH_CPT(dev_priv)) {
4219                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
4220                 temp |= FDI_LINK_TRAIN_PATTERN_1_CPT;
4221         } else {
4222                 temp &= ~FDI_LINK_TRAIN_NONE;
4223                 temp |= FDI_LINK_TRAIN_PATTERN_1;
4224         }
4225         /* BPC in FDI rx is consistent with that in PIPECONF */
4226         temp &= ~(0x07 << 16);
4227         temp |= (I915_READ(PIPECONF(pipe)) & PIPECONF_BPC_MASK) << 11;
4228         I915_WRITE(reg, temp);
4229
4230         POSTING_READ(reg);
4231         udelay(100);
4232 }
4233
4234 bool intel_has_pending_fb_unpin(struct drm_device *dev)
4235 {
4236         struct intel_crtc *crtc;
4237
4238         /* Note that we don't need to be called with mode_config.lock here
4239          * as our list of CRTC objects is static for the lifetime of the
4240          * device and so cannot disappear as we iterate. Similarly, we can
4241          * happily treat the predicates as racy, atomic checks as userspace
4242          * cannot claim and pin a new fb without at least acquring the
4243          * struct_mutex and so serialising with us.
4244          */
4245         for_each_intel_crtc(dev, crtc) {
4246                 if (atomic_read(&crtc->unpin_work_count) == 0)
4247                         continue;
4248
4249                 if (crtc->flip_work)
4250                         intel_wait_for_vblank(dev, crtc->pipe);
4251
4252                 return true;
4253         }
4254
4255         return false;
4256 }
4257
4258 static void page_flip_completed(struct intel_crtc *intel_crtc)
4259 {
4260         struct drm_i915_private *dev_priv = to_i915(intel_crtc->base.dev);
4261         struct intel_flip_work *work = intel_crtc->flip_work;
4262
4263         intel_crtc->flip_work = NULL;
4264
4265         if (work->event)
4266                 drm_crtc_send_vblank_event(&intel_crtc->base, work->event);
4267
4268         drm_crtc_vblank_put(&intel_crtc->base);
4269
4270         wake_up_all(&dev_priv->pending_flip_queue);
4271         queue_work(dev_priv->wq, &work->unpin_work);
4272
4273         trace_i915_flip_complete(intel_crtc->plane,
4274                                  work->pending_flip_obj);
4275 }
4276
4277 static int intel_crtc_wait_for_pending_flips(struct drm_crtc *crtc)
4278 {
4279         struct drm_device *dev = crtc->dev;
4280         struct drm_i915_private *dev_priv = to_i915(dev);
4281         long ret;
4282
4283         WARN_ON(waitqueue_active(&dev_priv->pending_flip_queue));
4284
4285         ret = wait_event_interruptible_timeout(
4286                                         dev_priv->pending_flip_queue,
4287                                         !intel_crtc_has_pending_flip(crtc),
4288                                         60*HZ);
4289
4290         if (ret < 0)
4291                 return ret;
4292
4293         if (ret == 0) {
4294                 struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4295                 struct intel_flip_work *work;
4296
4297                 spin_lock_irq(&dev->event_lock);
4298                 work = intel_crtc->flip_work;
4299                 if (work && !is_mmio_work(work)) {
4300                         WARN_ONCE(1, "Removing stuck page flip\n");
4301                         page_flip_completed(intel_crtc);
4302                 }
4303                 spin_unlock_irq(&dev->event_lock);
4304         }
4305
4306         return 0;
4307 }
4308
4309 void lpt_disable_iclkip(struct drm_i915_private *dev_priv)
4310 {
4311         u32 temp;
4312
4313         I915_WRITE(PIXCLK_GATE, PIXCLK_GATE_GATE);
4314
4315         mutex_lock(&dev_priv->sb_lock);
4316
4317         temp = intel_sbi_read(dev_priv, SBI_SSCCTL6, SBI_ICLK);
4318         temp |= SBI_SSCCTL_DISABLE;
4319         intel_sbi_write(dev_priv, SBI_SSCCTL6, temp, SBI_ICLK);
4320
4321         mutex_unlock(&dev_priv->sb_lock);
4322 }
4323
4324 /* Program iCLKIP clock to the desired frequency */
4325 static void lpt_program_iclkip(struct drm_crtc *crtc)
4326 {
4327         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
4328         int clock = to_intel_crtc(crtc)->config->base.adjusted_mode.crtc_clock;
4329         u32 divsel, phaseinc, auxdiv, phasedir = 0;
4330         u32 temp;
4331
4332         lpt_disable_iclkip(dev_priv);
4333
4334         /* The iCLK virtual clock root frequency is in MHz,
4335          * but the adjusted_mode->crtc_clock in in KHz. To get the
4336          * divisors, it is necessary to divide one by another, so we
4337          * convert the virtual clock precision to KHz here for higher
4338          * precision.
4339          */
4340         for (auxdiv = 0; auxdiv < 2; auxdiv++) {
4341                 u32 iclk_virtual_root_freq = 172800 * 1000;
4342                 u32 iclk_pi_range = 64;
4343                 u32 desired_divisor;
4344
4345                 desired_divisor = DIV_ROUND_CLOSEST(iclk_virtual_root_freq,
4346                                                     clock << auxdiv);
4347                 divsel = (desired_divisor / iclk_pi_range) - 2;
4348                 phaseinc = desired_divisor % iclk_pi_range;
4349
4350                 /*
4351                  * Near 20MHz is a corner case which is
4352                  * out of range for the 7-bit divisor
4353                  */
4354                 if (divsel <= 0x7f)
4355                         break;
4356         }
4357
4358         /* This should not happen with any sane values */
4359         WARN_ON(SBI_SSCDIVINTPHASE_DIVSEL(divsel) &
4360                 ~SBI_SSCDIVINTPHASE_DIVSEL_MASK);
4361         WARN_ON(SBI_SSCDIVINTPHASE_DIR(phasedir) &
4362                 ~SBI_SSCDIVINTPHASE_INCVAL_MASK);
4363
4364         DRM_DEBUG_KMS("iCLKIP clock: found settings for %dKHz refresh rate: auxdiv=%x, divsel=%x, phasedir=%x, phaseinc=%x\n",
4365                         clock,
4366                         auxdiv,
4367                         divsel,
4368                         phasedir,
4369                         phaseinc);
4370
4371         mutex_lock(&dev_priv->sb_lock);
4372
4373         /* Program SSCDIVINTPHASE6 */
4374         temp = intel_sbi_read(dev_priv, SBI_SSCDIVINTPHASE6, SBI_ICLK);
4375         temp &= ~SBI_SSCDIVINTPHASE_DIVSEL_MASK;
4376         temp |= SBI_SSCDIVINTPHASE_DIVSEL(divsel);
4377         temp &= ~SBI_SSCDIVINTPHASE_INCVAL_MASK;
4378         temp |= SBI_SSCDIVINTPHASE_INCVAL(phaseinc);
4379         temp |= SBI_SSCDIVINTPHASE_DIR(phasedir);
4380         temp |= SBI_SSCDIVINTPHASE_PROPAGATE;
4381         intel_sbi_write(dev_priv, SBI_SSCDIVINTPHASE6, temp, SBI_ICLK);
4382
4383         /* Program SSCAUXDIV */
4384         temp = intel_sbi_read(dev_priv, SBI_SSCAUXDIV6, SBI_ICLK);
4385         temp &= ~SBI_SSCAUXDIV_FINALDIV2SEL(1);
4386         temp |= SBI_SSCAUXDIV_FINALDIV2SEL(auxdiv);
4387         intel_sbi_write(dev_priv, SBI_SSCAUXDIV6, temp, SBI_ICLK);
4388
4389         /* Enable modulator and associated divider */
4390         temp = intel_sbi_read(dev_priv, SBI_SSCCTL6, SBI_ICLK);
4391         temp &= ~SBI_SSCCTL_DISABLE;
4392         intel_sbi_write(dev_priv, SBI_SSCCTL6, temp, SBI_ICLK);
4393
4394         mutex_unlock(&dev_priv->sb_lock);
4395
4396         /* Wait for initialization time */
4397         udelay(24);
4398
4399         I915_WRITE(PIXCLK_GATE, PIXCLK_GATE_UNGATE);
4400 }
4401
4402 int lpt_get_iclkip(struct drm_i915_private *dev_priv)
4403 {
4404         u32 divsel, phaseinc, auxdiv;
4405         u32 iclk_virtual_root_freq = 172800 * 1000;
4406         u32 iclk_pi_range = 64;
4407         u32 desired_divisor;
4408         u32 temp;
4409
4410         if ((I915_READ(PIXCLK_GATE) & PIXCLK_GATE_UNGATE) == 0)
4411                 return 0;
4412
4413         mutex_lock(&dev_priv->sb_lock);
4414
4415         temp = intel_sbi_read(dev_priv, SBI_SSCCTL6, SBI_ICLK);
4416         if (temp & SBI_SSCCTL_DISABLE) {
4417                 mutex_unlock(&dev_priv->sb_lock);
4418                 return 0;
4419         }
4420
4421         temp = intel_sbi_read(dev_priv, SBI_SSCDIVINTPHASE6, SBI_ICLK);
4422         divsel = (temp & SBI_SSCDIVINTPHASE_DIVSEL_MASK) >>
4423                 SBI_SSCDIVINTPHASE_DIVSEL_SHIFT;
4424         phaseinc = (temp & SBI_SSCDIVINTPHASE_INCVAL_MASK) >>
4425                 SBI_SSCDIVINTPHASE_INCVAL_SHIFT;
4426
4427         temp = intel_sbi_read(dev_priv, SBI_SSCAUXDIV6, SBI_ICLK);
4428         auxdiv = (temp & SBI_SSCAUXDIV_FINALDIV2SEL_MASK) >>
4429                 SBI_SSCAUXDIV_FINALDIV2SEL_SHIFT;
4430
4431         mutex_unlock(&dev_priv->sb_lock);
4432
4433         desired_divisor = (divsel + 2) * iclk_pi_range + phaseinc;
4434
4435         return DIV_ROUND_CLOSEST(iclk_virtual_root_freq,
4436                                  desired_divisor << auxdiv);
4437 }
4438
4439 static void ironlake_pch_transcoder_set_timings(struct intel_crtc *crtc,
4440                                                 enum pipe pch_transcoder)
4441 {
4442         struct drm_device *dev = crtc->base.dev;
4443         struct drm_i915_private *dev_priv = to_i915(dev);
4444         enum transcoder cpu_transcoder = crtc->config->cpu_transcoder;
4445
4446         I915_WRITE(PCH_TRANS_HTOTAL(pch_transcoder),
4447                    I915_READ(HTOTAL(cpu_transcoder)));
4448         I915_WRITE(PCH_TRANS_HBLANK(pch_transcoder),
4449                    I915_READ(HBLANK(cpu_transcoder)));
4450         I915_WRITE(PCH_TRANS_HSYNC(pch_transcoder),
4451                    I915_READ(HSYNC(cpu_transcoder)));
4452
4453         I915_WRITE(PCH_TRANS_VTOTAL(pch_transcoder),
4454                    I915_READ(VTOTAL(cpu_transcoder)));
4455         I915_WRITE(PCH_TRANS_VBLANK(pch_transcoder),
4456                    I915_READ(VBLANK(cpu_transcoder)));
4457         I915_WRITE(PCH_TRANS_VSYNC(pch_transcoder),
4458                    I915_READ(VSYNC(cpu_transcoder)));
4459         I915_WRITE(PCH_TRANS_VSYNCSHIFT(pch_transcoder),
4460                    I915_READ(VSYNCSHIFT(cpu_transcoder)));
4461 }
4462
4463 static void cpt_set_fdi_bc_bifurcation(struct drm_device *dev, bool enable)
4464 {
4465         struct drm_i915_private *dev_priv = to_i915(dev);
4466         uint32_t temp;
4467
4468         temp = I915_READ(SOUTH_CHICKEN1);
4469         if (!!(temp & FDI_BC_BIFURCATION_SELECT) == enable)
4470                 return;
4471
4472         WARN_ON(I915_READ(FDI_RX_CTL(PIPE_B)) & FDI_RX_ENABLE);
4473         WARN_ON(I915_READ(FDI_RX_CTL(PIPE_C)) & FDI_RX_ENABLE);
4474
4475         temp &= ~FDI_BC_BIFURCATION_SELECT;
4476         if (enable)
4477                 temp |= FDI_BC_BIFURCATION_SELECT;
4478
4479         DRM_DEBUG_KMS("%sabling fdi C rx\n", enable ? "en" : "dis");
4480         I915_WRITE(SOUTH_CHICKEN1, temp);
4481         POSTING_READ(SOUTH_CHICKEN1);
4482 }
4483
4484 static void ivybridge_update_fdi_bc_bifurcation(struct intel_crtc *intel_crtc)
4485 {
4486         struct drm_device *dev = intel_crtc->base.dev;
4487
4488         switch (intel_crtc->pipe) {
4489         case PIPE_A:
4490                 break;
4491         case PIPE_B:
4492                 if (intel_crtc->config->fdi_lanes > 2)
4493                         cpt_set_fdi_bc_bifurcation(dev, false);
4494                 else
4495                         cpt_set_fdi_bc_bifurcation(dev, true);
4496
4497                 break;
4498         case PIPE_C:
4499                 cpt_set_fdi_bc_bifurcation(dev, true);
4500
4501                 break;
4502         default:
4503                 BUG();
4504         }
4505 }
4506
4507 /* Return which DP Port should be selected for Transcoder DP control */
4508 static enum port
4509 intel_trans_dp_port_sel(struct drm_crtc *crtc)
4510 {
4511         struct drm_device *dev = crtc->dev;
4512         struct intel_encoder *encoder;
4513
4514         for_each_encoder_on_crtc(dev, crtc, encoder) {
4515                 if (encoder->type == INTEL_OUTPUT_DP ||
4516                     encoder->type == INTEL_OUTPUT_EDP)
4517                         return enc_to_dig_port(&encoder->base)->port;
4518         }
4519
4520         return -1;
4521 }
4522
4523 /*
4524  * Enable PCH resources required for PCH ports:
4525  *   - PCH PLLs
4526  *   - FDI training & RX/TX
4527  *   - update transcoder timings
4528  *   - DP transcoding bits
4529  *   - transcoder
4530  */
4531 static void ironlake_pch_enable(struct drm_crtc *crtc)
4532 {
4533         struct drm_device *dev = crtc->dev;
4534         struct drm_i915_private *dev_priv = to_i915(dev);
4535         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4536         int pipe = intel_crtc->pipe;
4537         u32 temp;
4538
4539         assert_pch_transcoder_disabled(dev_priv, pipe);
4540
4541         if (IS_IVYBRIDGE(dev_priv))
4542                 ivybridge_update_fdi_bc_bifurcation(intel_crtc);
4543
4544         /* Write the TU size bits before fdi link training, so that error
4545          * detection works. */
4546         I915_WRITE(FDI_RX_TUSIZE1(pipe),
4547                    I915_READ(PIPE_DATA_M1(pipe)) & TU_SIZE_MASK);
4548
4549         /* For PCH output, training FDI link */
4550         dev_priv->display.fdi_link_train(crtc);
4551
4552         /* We need to program the right clock selection before writing the pixel
4553          * mutliplier into the DPLL. */
4554         if (HAS_PCH_CPT(dev_priv)) {
4555                 u32 sel;
4556
4557                 temp = I915_READ(PCH_DPLL_SEL);
4558                 temp |= TRANS_DPLL_ENABLE(pipe);
4559                 sel = TRANS_DPLLB_SEL(pipe);
4560                 if (intel_crtc->config->shared_dpll ==
4561                     intel_get_shared_dpll_by_id(dev_priv, DPLL_ID_PCH_PLL_B))
4562                         temp |= sel;
4563                 else
4564                         temp &= ~sel;
4565                 I915_WRITE(PCH_DPLL_SEL, temp);
4566         }
4567
4568         /* XXX: pch pll's can be enabled any time before we enable the PCH
4569          * transcoder, and we actually should do this to not upset any PCH
4570          * transcoder that already use the clock when we share it.
4571          *
4572          * Note that enable_shared_dpll tries to do the right thing, but
4573          * get_shared_dpll unconditionally resets the pll - we need that to have
4574          * the right LVDS enable sequence. */
4575         intel_enable_shared_dpll(intel_crtc);
4576
4577         /* set transcoder timing, panel must allow it */
4578         assert_panel_unlocked(dev_priv, pipe);
4579         ironlake_pch_transcoder_set_timings(intel_crtc, pipe);
4580
4581         intel_fdi_normal_train(crtc);
4582
4583         /* For PCH DP, enable TRANS_DP_CTL */
4584         if (HAS_PCH_CPT(dev_priv) &&
4585             intel_crtc_has_dp_encoder(intel_crtc->config)) {
4586                 const struct drm_display_mode *adjusted_mode =
4587                         &intel_crtc->config->base.adjusted_mode;
4588                 u32 bpc = (I915_READ(PIPECONF(pipe)) & PIPECONF_BPC_MASK) >> 5;
4589                 i915_reg_t reg = TRANS_DP_CTL(pipe);
4590                 temp = I915_READ(reg);
4591                 temp &= ~(TRANS_DP_PORT_SEL_MASK |
4592                           TRANS_DP_SYNC_MASK |
4593                           TRANS_DP_BPC_MASK);
4594                 temp |= TRANS_DP_OUTPUT_ENABLE;
4595                 temp |= bpc << 9; /* same format but at 11:9 */
4596
4597                 if (adjusted_mode->flags & DRM_MODE_FLAG_PHSYNC)
4598                         temp |= TRANS_DP_HSYNC_ACTIVE_HIGH;
4599                 if (adjusted_mode->flags & DRM_MODE_FLAG_PVSYNC)
4600                         temp |= TRANS_DP_VSYNC_ACTIVE_HIGH;
4601
4602                 switch (intel_trans_dp_port_sel(crtc)) {
4603                 case PORT_B:
4604                         temp |= TRANS_DP_PORT_SEL_B;
4605                         break;
4606                 case PORT_C:
4607                         temp |= TRANS_DP_PORT_SEL_C;
4608                         break;
4609                 case PORT_D:
4610                         temp |= TRANS_DP_PORT_SEL_D;
4611                         break;
4612                 default:
4613                         BUG();
4614                 }
4615
4616                 I915_WRITE(reg, temp);
4617         }
4618
4619         ironlake_enable_pch_transcoder(dev_priv, pipe);
4620 }
4621
4622 static void lpt_pch_enable(struct drm_crtc *crtc)
4623 {
4624         struct drm_device *dev = crtc->dev;
4625         struct drm_i915_private *dev_priv = to_i915(dev);
4626         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4627         enum transcoder cpu_transcoder = intel_crtc->config->cpu_transcoder;
4628
4629         assert_pch_transcoder_disabled(dev_priv, TRANSCODER_A);
4630
4631         lpt_program_iclkip(crtc);
4632
4633         /* Set transcoder timing. */
4634         ironlake_pch_transcoder_set_timings(intel_crtc, PIPE_A);
4635
4636         lpt_enable_pch_transcoder(dev_priv, cpu_transcoder);
4637 }
4638
4639 static void cpt_verify_modeset(struct drm_device *dev, int pipe)
4640 {
4641         struct drm_i915_private *dev_priv = to_i915(dev);
4642         i915_reg_t dslreg = PIPEDSL(pipe);
4643         u32 temp;
4644
4645         temp = I915_READ(dslreg);
4646         udelay(500);
4647         if (wait_for(I915_READ(dslreg) != temp, 5)) {
4648                 if (wait_for(I915_READ(dslreg) != temp, 5))
4649                         DRM_ERROR("mode set failed: pipe %c stuck\n", pipe_name(pipe));
4650         }
4651 }
4652
4653 static int
4654 skl_update_scaler(struct intel_crtc_state *crtc_state, bool force_detach,
4655                   unsigned scaler_user, int *scaler_id, unsigned int rotation,
4656                   int src_w, int src_h, int dst_w, int dst_h)
4657 {
4658         struct intel_crtc_scaler_state *scaler_state =
4659                 &crtc_state->scaler_state;
4660         struct intel_crtc *intel_crtc =
4661                 to_intel_crtc(crtc_state->base.crtc);
4662         int need_scaling;
4663
4664         need_scaling = intel_rotation_90_or_270(rotation) ?
4665                 (src_h != dst_w || src_w != dst_h):
4666                 (src_w != dst_w || src_h != dst_h);
4667
4668         /*
4669          * if plane is being disabled or scaler is no more required or force detach
4670          *  - free scaler binded to this plane/crtc
4671          *  - in order to do this, update crtc->scaler_usage
4672          *
4673          * Here scaler state in crtc_state is set free so that
4674          * scaler can be assigned to other user. Actual register
4675          * update to free the scaler is done in plane/panel-fit programming.
4676          * For this purpose crtc/plane_state->scaler_id isn't reset here.
4677          */
4678         if (force_detach || !need_scaling) {
4679                 if (*scaler_id >= 0) {
4680                         scaler_state->scaler_users &= ~(1 << scaler_user);
4681                         scaler_state->scalers[*scaler_id].in_use = 0;
4682
4683                         DRM_DEBUG_KMS("scaler_user index %u.%u: "
4684                                 "Staged freeing scaler id %d scaler_users = 0x%x\n",
4685                                 intel_crtc->pipe, scaler_user, *scaler_id,
4686                                 scaler_state->scaler_users);
4687                         *scaler_id = -1;
4688                 }
4689                 return 0;
4690         }
4691
4692         /* range checks */
4693         if (src_w < SKL_MIN_SRC_W || src_h < SKL_MIN_SRC_H ||
4694                 dst_w < SKL_MIN_DST_W || dst_h < SKL_MIN_DST_H ||
4695
4696                 src_w > SKL_MAX_SRC_W || src_h > SKL_MAX_SRC_H ||
4697                 dst_w > SKL_MAX_DST_W || dst_h > SKL_MAX_DST_H) {
4698                 DRM_DEBUG_KMS("scaler_user index %u.%u: src %ux%u dst %ux%u "
4699                         "size is out of scaler range\n",
4700                         intel_crtc->pipe, scaler_user, src_w, src_h, dst_w, dst_h);
4701                 return -EINVAL;
4702         }
4703
4704         /* mark this plane as a scaler user in crtc_state */
4705         scaler_state->scaler_users |= (1 << scaler_user);
4706         DRM_DEBUG_KMS("scaler_user index %u.%u: "
4707                 "staged scaling request for %ux%u->%ux%u scaler_users = 0x%x\n",
4708                 intel_crtc->pipe, scaler_user, src_w, src_h, dst_w, dst_h,
4709                 scaler_state->scaler_users);
4710
4711         return 0;
4712 }
4713
4714 /**
4715  * skl_update_scaler_crtc - Stages update to scaler state for a given crtc.
4716  *
4717  * @state: crtc's scaler state
4718  *
4719  * Return
4720  *     0 - scaler_usage updated successfully
4721  *    error - requested scaling cannot be supported or other error condition
4722  */
4723 int skl_update_scaler_crtc(struct intel_crtc_state *state)
4724 {
4725         struct intel_crtc *intel_crtc = to_intel_crtc(state->base.crtc);
4726         const struct drm_display_mode *adjusted_mode = &state->base.adjusted_mode;
4727
4728         DRM_DEBUG_KMS("Updating scaler for [CRTC:%d:%s] scaler_user index %u.%u\n",
4729                       intel_crtc->base.base.id, intel_crtc->base.name,
4730                       intel_crtc->pipe, SKL_CRTC_INDEX);
4731
4732         return skl_update_scaler(state, !state->base.active, SKL_CRTC_INDEX,
4733                 &state->scaler_state.scaler_id, DRM_ROTATE_0,
4734                 state->pipe_src_w, state->pipe_src_h,
4735                 adjusted_mode->crtc_hdisplay, adjusted_mode->crtc_vdisplay);
4736 }
4737
4738 /**
4739  * skl_update_scaler_plane - Stages update to scaler state for a given plane.
4740  *
4741  * @state: crtc's scaler state
4742  * @plane_state: atomic plane state to update
4743  *
4744  * Return
4745  *     0 - scaler_usage updated successfully
4746  *    error - requested scaling cannot be supported or other error condition
4747  */
4748 static int skl_update_scaler_plane(struct intel_crtc_state *crtc_state,
4749                                    struct intel_plane_state *plane_state)
4750 {
4751
4752         struct intel_crtc *intel_crtc = to_intel_crtc(crtc_state->base.crtc);
4753         struct intel_plane *intel_plane =
4754                 to_intel_plane(plane_state->base.plane);
4755         struct drm_framebuffer *fb = plane_state->base.fb;
4756         int ret;
4757
4758         bool force_detach = !fb || !plane_state->base.visible;
4759
4760         DRM_DEBUG_KMS("Updating scaler for [PLANE:%d:%s] scaler_user index %u.%u\n",
4761                       intel_plane->base.base.id, intel_plane->base.name,
4762                       intel_crtc->pipe, drm_plane_index(&intel_plane->base));
4763
4764         ret = skl_update_scaler(crtc_state, force_detach,
4765                                 drm_plane_index(&intel_plane->base),
4766                                 &plane_state->scaler_id,
4767                                 plane_state->base.rotation,
4768                                 drm_rect_width(&plane_state->base.src) >> 16,
4769                                 drm_rect_height(&plane_state->base.src) >> 16,
4770                                 drm_rect_width(&plane_state->base.dst),
4771                                 drm_rect_height(&plane_state->base.dst));
4772
4773         if (ret || plane_state->scaler_id < 0)
4774                 return ret;
4775
4776         /* check colorkey */
4777         if (plane_state->ckey.flags != I915_SET_COLORKEY_NONE) {
4778                 DRM_DEBUG_KMS("[PLANE:%d:%s] scaling with color key not allowed",
4779                               intel_plane->base.base.id,
4780                               intel_plane->base.name);
4781                 return -EINVAL;
4782         }
4783
4784         /* Check src format */
4785         switch (fb->pixel_format) {
4786         case DRM_FORMAT_RGB565:
4787         case DRM_FORMAT_XBGR8888:
4788         case DRM_FORMAT_XRGB8888:
4789         case DRM_FORMAT_ABGR8888:
4790         case DRM_FORMAT_ARGB8888:
4791         case DRM_FORMAT_XRGB2101010:
4792         case DRM_FORMAT_XBGR2101010:
4793         case DRM_FORMAT_YUYV:
4794         case DRM_FORMAT_YVYU:
4795         case DRM_FORMAT_UYVY:
4796         case DRM_FORMAT_VYUY:
4797                 break;
4798         default:
4799                 DRM_DEBUG_KMS("[PLANE:%d:%s] FB:%d unsupported scaling format 0x%x\n",
4800                               intel_plane->base.base.id, intel_plane->base.name,
4801                               fb->base.id, fb->pixel_format);
4802                 return -EINVAL;
4803         }
4804
4805         return 0;
4806 }
4807
4808 static void skylake_scaler_disable(struct intel_crtc *crtc)
4809 {
4810         int i;
4811
4812         for (i = 0; i < crtc->num_scalers; i++)
4813                 skl_detach_scaler(crtc, i);
4814 }
4815
4816 static void skylake_pfit_enable(struct intel_crtc *crtc)
4817 {
4818         struct drm_device *dev = crtc->base.dev;
4819         struct drm_i915_private *dev_priv = to_i915(dev);
4820         int pipe = crtc->pipe;
4821         struct intel_crtc_scaler_state *scaler_state =
4822                 &crtc->config->scaler_state;
4823
4824         DRM_DEBUG_KMS("for crtc_state = %p\n", crtc->config);
4825
4826         if (crtc->config->pch_pfit.enabled) {
4827                 int id;
4828
4829                 if (WARN_ON(crtc->config->scaler_state.scaler_id < 0)) {
4830                         DRM_ERROR("Requesting pfit without getting a scaler first\n");
4831                         return;
4832                 }
4833
4834                 id = scaler_state->scaler_id;
4835                 I915_WRITE(SKL_PS_CTRL(pipe, id), PS_SCALER_EN |
4836                         PS_FILTER_MEDIUM | scaler_state->scalers[id].mode);
4837                 I915_WRITE(SKL_PS_WIN_POS(pipe, id), crtc->config->pch_pfit.pos);
4838                 I915_WRITE(SKL_PS_WIN_SZ(pipe, id), crtc->config->pch_pfit.size);
4839
4840                 DRM_DEBUG_KMS("for crtc_state = %p scaler_id = %d\n", crtc->config, id);
4841         }
4842 }
4843
4844 static void ironlake_pfit_enable(struct intel_crtc *crtc)
4845 {
4846         struct drm_device *dev = crtc->base.dev;
4847         struct drm_i915_private *dev_priv = to_i915(dev);
4848         int pipe = crtc->pipe;
4849
4850         if (crtc->config->pch_pfit.enabled) {
4851                 /* Force use of hard-coded filter coefficients
4852                  * as some pre-programmed values are broken,
4853                  * e.g. x201.
4854                  */
4855                 if (IS_IVYBRIDGE(dev_priv) || IS_HASWELL(dev_priv))
4856                         I915_WRITE(PF_CTL(pipe), PF_ENABLE | PF_FILTER_MED_3x3 |
4857                                                  PF_PIPE_SEL_IVB(pipe));
4858                 else
4859                         I915_WRITE(PF_CTL(pipe), PF_ENABLE | PF_FILTER_MED_3x3);
4860                 I915_WRITE(PF_WIN_POS(pipe), crtc->config->pch_pfit.pos);
4861                 I915_WRITE(PF_WIN_SZ(pipe), crtc->config->pch_pfit.size);
4862         }
4863 }
4864
4865 void hsw_enable_ips(struct intel_crtc *crtc)
4866 {
4867         struct drm_device *dev = crtc->base.dev;
4868         struct drm_i915_private *dev_priv = to_i915(dev);
4869
4870         if (!crtc->config->ips_enabled)
4871                 return;
4872
4873         /*
4874          * We can only enable IPS after we enable a plane and wait for a vblank
4875          * This function is called from post_plane_update, which is run after
4876          * a vblank wait.
4877          */
4878
4879         assert_plane_enabled(dev_priv, crtc->plane);
4880         if (IS_BROADWELL(dev)) {
4881                 mutex_lock(&dev_priv->rps.hw_lock);
4882                 WARN_ON(sandybridge_pcode_write(dev_priv, DISPLAY_IPS_CONTROL, 0xc0000000));
4883                 mutex_unlock(&dev_priv->rps.hw_lock);
4884                 /* Quoting Art Runyan: "its not safe to expect any particular
4885                  * value in IPS_CTL bit 31 after enabling IPS through the
4886                  * mailbox." Moreover, the mailbox may return a bogus state,
4887                  * so we need to just enable it and continue on.
4888                  */
4889         } else {
4890                 I915_WRITE(IPS_CTL, IPS_ENABLE);
4891                 /* The bit only becomes 1 in the next vblank, so this wait here
4892                  * is essentially intel_wait_for_vblank. If we don't have this
4893                  * and don't wait for vblanks until the end of crtc_enable, then
4894                  * the HW state readout code will complain that the expected
4895                  * IPS_CTL value is not the one we read. */
4896                 if (intel_wait_for_register(dev_priv,
4897                                             IPS_CTL, IPS_ENABLE, IPS_ENABLE,
4898                                             50))
4899                         DRM_ERROR("Timed out waiting for IPS enable\n");
4900         }
4901 }
4902
4903 void hsw_disable_ips(struct intel_crtc *crtc)
4904 {
4905         struct drm_device *dev = crtc->base.dev;
4906         struct drm_i915_private *dev_priv = to_i915(dev);
4907
4908         if (!crtc->config->ips_enabled)
4909                 return;
4910
4911         assert_plane_enabled(dev_priv, crtc->plane);
4912         if (IS_BROADWELL(dev)) {
4913                 mutex_lock(&dev_priv->rps.hw_lock);
4914                 WARN_ON(sandybridge_pcode_write(dev_priv, DISPLAY_IPS_CONTROL, 0));
4915                 mutex_unlock(&dev_priv->rps.hw_lock);
4916                 /* wait for pcode to finish disabling IPS, which may take up to 42ms */
4917                 if (intel_wait_for_register(dev_priv,
4918                                             IPS_CTL, IPS_ENABLE, 0,
4919                                             42))
4920                         DRM_ERROR("Timed out waiting for IPS disable\n");
4921         } else {
4922                 I915_WRITE(IPS_CTL, 0);
4923                 POSTING_READ(IPS_CTL);
4924         }
4925
4926         /* We need to wait for a vblank before we can disable the plane. */
4927         intel_wait_for_vblank(dev, crtc->pipe);
4928 }
4929
4930 static void intel_crtc_dpms_overlay_disable(struct intel_crtc *intel_crtc)
4931 {
4932         if (intel_crtc->overlay) {
4933                 struct drm_device *dev = intel_crtc->base.dev;
4934                 struct drm_i915_private *dev_priv = to_i915(dev);
4935
4936                 mutex_lock(&dev->struct_mutex);
4937                 dev_priv->mm.interruptible = false;
4938                 (void) intel_overlay_switch_off(intel_crtc->overlay);
4939                 dev_priv->mm.interruptible = true;
4940                 mutex_unlock(&dev->struct_mutex);
4941         }
4942
4943         /* Let userspace switch the overlay on again. In most cases userspace
4944          * has to recompute where to put it anyway.
4945          */
4946 }
4947
4948 /**
4949  * intel_post_enable_primary - Perform operations after enabling primary plane
4950  * @crtc: the CRTC whose primary plane was just enabled
4951  *
4952  * Performs potentially sleeping operations that must be done after the primary
4953  * plane is enabled, such as updating FBC and IPS.  Note that this may be
4954  * called due to an explicit primary plane update, or due to an implicit
4955  * re-enable that is caused when a sprite plane is updated to no longer
4956  * completely hide the primary plane.
4957  */
4958 static void
4959 intel_post_enable_primary(struct drm_crtc *crtc)
4960 {
4961         struct drm_device *dev = crtc->dev;
4962         struct drm_i915_private *dev_priv = to_i915(dev);
4963         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4964         int pipe = intel_crtc->pipe;
4965
4966         /*
4967          * FIXME IPS should be fine as long as one plane is
4968          * enabled, but in practice it seems to have problems
4969          * when going from primary only to sprite only and vice
4970          * versa.
4971          */
4972         hsw_enable_ips(intel_crtc);
4973
4974         /*
4975          * Gen2 reports pipe underruns whenever all planes are disabled.
4976          * So don't enable underrun reporting before at least some planes
4977          * are enabled.
4978          * FIXME: Need to fix the logic to work when we turn off all planes
4979          * but leave the pipe running.
4980          */
4981         if (IS_GEN2(dev))
4982                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
4983
4984         /* Underruns don't always raise interrupts, so check manually. */
4985         intel_check_cpu_fifo_underruns(dev_priv);
4986         intel_check_pch_fifo_underruns(dev_priv);
4987 }
4988
4989 /* FIXME move all this to pre_plane_update() with proper state tracking */
4990 static void
4991 intel_pre_disable_primary(struct drm_crtc *crtc)
4992 {
4993         struct drm_device *dev = crtc->dev;
4994         struct drm_i915_private *dev_priv = to_i915(dev);
4995         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4996         int pipe = intel_crtc->pipe;
4997
4998         /*
4999          * Gen2 reports pipe underruns whenever all planes are disabled.
5000          * So diasble underrun reporting before all the planes get disabled.
5001          * FIXME: Need to fix the logic to work when we turn off all planes
5002          * but leave the pipe running.
5003          */
5004         if (IS_GEN2(dev))
5005                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, false);
5006
5007         /*
5008          * FIXME IPS should be fine as long as one plane is
5009          * enabled, but in practice it seems to have problems
5010          * when going from primary only to sprite only and vice
5011          * versa.
5012          */
5013         hsw_disable_ips(intel_crtc);
5014 }
5015
5016 /* FIXME get rid of this and use pre_plane_update */
5017 static void
5018 intel_pre_disable_primary_noatomic(struct drm_crtc *crtc)
5019 {
5020         struct drm_device *dev = crtc->dev;
5021         struct drm_i915_private *dev_priv = to_i915(dev);
5022         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5023         int pipe = intel_crtc->pipe;
5024
5025         intel_pre_disable_primary(crtc);
5026
5027         /*
5028          * Vblank time updates from the shadow to live plane control register
5029          * are blocked if the memory self-refresh mode is active at that
5030          * moment. So to make sure the plane gets truly disabled, disable
5031          * first the self-refresh mode. The self-refresh enable bit in turn
5032          * will be checked/applied by the HW only at the next frame start
5033          * event which is after the vblank start event, so we need to have a
5034          * wait-for-vblank between disabling the plane and the pipe.
5035          */
5036         if (HAS_GMCH_DISPLAY(dev_priv)) {
5037                 intel_set_memory_cxsr(dev_priv, false);
5038                 dev_priv->wm.vlv.cxsr = false;
5039                 intel_wait_for_vblank(dev, pipe);
5040         }
5041 }
5042
5043 static void intel_post_plane_update(struct intel_crtc_state *old_crtc_state)
5044 {
5045         struct intel_crtc *crtc = to_intel_crtc(old_crtc_state->base.crtc);
5046         struct drm_atomic_state *old_state = old_crtc_state->base.state;
5047         struct intel_crtc_state *pipe_config =
5048                 to_intel_crtc_state(crtc->base.state);
5049         struct drm_plane *primary = crtc->base.primary;
5050         struct drm_plane_state *old_pri_state =
5051                 drm_atomic_get_existing_plane_state(old_state, primary);
5052
5053         intel_frontbuffer_flip(to_i915(crtc->base.dev), pipe_config->fb_bits);
5054
5055         crtc->wm.cxsr_allowed = true;
5056
5057         if (pipe_config->update_wm_post && pipe_config->base.active)
5058                 intel_update_watermarks(&crtc->base);
5059
5060         if (old_pri_state) {
5061                 struct intel_plane_state *primary_state =
5062                         to_intel_plane_state(primary->state);
5063                 struct intel_plane_state *old_primary_state =
5064                         to_intel_plane_state(old_pri_state);
5065
5066                 intel_fbc_post_update(crtc);
5067
5068                 if (primary_state->base.visible &&
5069                     (needs_modeset(&pipe_config->base) ||
5070                      !old_primary_state->base.visible))
5071                         intel_post_enable_primary(&crtc->base);
5072         }
5073 }
5074
5075 static void intel_pre_plane_update(struct intel_crtc_state *old_crtc_state)
5076 {
5077         struct intel_crtc *crtc = to_intel_crtc(old_crtc_state->base.crtc);
5078         struct drm_device *dev = crtc->base.dev;
5079         struct drm_i915_private *dev_priv = to_i915(dev);
5080         struct intel_crtc_state *pipe_config =
5081                 to_intel_crtc_state(crtc->base.state);
5082         struct drm_atomic_state *old_state = old_crtc_state->base.state;
5083         struct drm_plane *primary = crtc->base.primary;
5084         struct drm_plane_state *old_pri_state =
5085                 drm_atomic_get_existing_plane_state(old_state, primary);
5086         bool modeset = needs_modeset(&pipe_config->base);
5087
5088         if (old_pri_state) {
5089                 struct intel_plane_state *primary_state =
5090                         to_intel_plane_state(primary->state);
5091                 struct intel_plane_state *old_primary_state =
5092                         to_intel_plane_state(old_pri_state);
5093
5094                 intel_fbc_pre_update(crtc, pipe_config, primary_state);
5095
5096                 if (old_primary_state->base.visible &&
5097                     (modeset || !primary_state->base.visible))
5098                         intel_pre_disable_primary(&crtc->base);
5099         }
5100
5101         if (pipe_config->disable_cxsr && HAS_GMCH_DISPLAY(dev_priv)) {
5102                 crtc->wm.cxsr_allowed = false;
5103
5104                 /*
5105                  * Vblank time updates from the shadow to live plane control register
5106                  * are blocked if the memory self-refresh mode is active at that
5107                  * moment. So to make sure the plane gets truly disabled, disable
5108                  * first the self-refresh mode. The self-refresh enable bit in turn
5109                  * will be checked/applied by the HW only at the next frame start
5110                  * event which is after the vblank start event, so we need to have a
5111                  * wait-for-vblank between disabling the plane and the pipe.
5112                  */
5113                 if (old_crtc_state->base.active) {
5114                         intel_set_memory_cxsr(dev_priv, false);
5115                         dev_priv->wm.vlv.cxsr = false;
5116                         intel_wait_for_vblank(dev, crtc->pipe);
5117                 }
5118         }
5119
5120         /*
5121          * IVB workaround: must disable low power watermarks for at least
5122          * one frame before enabling scaling.  LP watermarks can be re-enabled
5123          * when scaling is disabled.
5124          *
5125          * WaCxSRDisabledForSpriteScaling:ivb
5126          */
5127         if (pipe_config->disable_lp_wm) {
5128                 ilk_disable_lp_wm(dev);
5129                 intel_wait_for_vblank(dev, crtc->pipe);
5130         }
5131
5132         /*
5133          * If we're doing a modeset, we're done.  No need to do any pre-vblank
5134          * watermark programming here.
5135          */
5136         if (needs_modeset(&pipe_config->base))
5137                 return;
5138
5139         /*
5140          * For platforms that support atomic watermarks, program the
5141          * 'intermediate' watermarks immediately.  On pre-gen9 platforms, these
5142          * will be the intermediate values that are safe for both pre- and
5143          * post- vblank; when vblank happens, the 'active' values will be set
5144          * to the final 'target' values and we'll do this again to get the
5145          * optimal watermarks.  For gen9+ platforms, the values we program here
5146          * will be the final target values which will get automatically latched
5147          * at vblank time; no further programming will be necessary.
5148          *
5149          * If a platform hasn't been transitioned to atomic watermarks yet,
5150          * we'll continue to update watermarks the old way, if flags tell
5151          * us to.
5152          */
5153         if (dev_priv->display.initial_watermarks != NULL)
5154                 dev_priv->display.initial_watermarks(pipe_config);
5155         else if (pipe_config->update_wm_pre)
5156                 intel_update_watermarks(&crtc->base);
5157 }
5158
5159 static void intel_crtc_disable_planes(struct drm_crtc *crtc, unsigned plane_mask)
5160 {
5161         struct drm_device *dev = crtc->dev;
5162         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5163         struct drm_plane *p;
5164         int pipe = intel_crtc->pipe;
5165
5166         intel_crtc_dpms_overlay_disable(intel_crtc);
5167
5168         drm_for_each_plane_mask(p, dev, plane_mask)
5169                 to_intel_plane(p)->disable_plane(p, crtc);
5170
5171         /*
5172          * FIXME: Once we grow proper nuclear flip support out of this we need
5173          * to compute the mask of flip planes precisely. For the time being
5174          * consider this a flip to a NULL plane.
5175          */
5176         intel_frontbuffer_flip(to_i915(dev), INTEL_FRONTBUFFER_ALL_MASK(pipe));
5177 }
5178
5179 static void intel_encoders_pre_pll_enable(struct drm_crtc *crtc,
5180                                           struct intel_crtc_state *crtc_state,
5181                                           struct drm_atomic_state *old_state)
5182 {
5183         struct drm_connector_state *old_conn_state;
5184         struct drm_connector *conn;
5185         int i;
5186
5187         for_each_connector_in_state(old_state, conn, old_conn_state, i) {
5188                 struct drm_connector_state *conn_state = conn->state;
5189                 struct intel_encoder *encoder =
5190                         to_intel_encoder(conn_state->best_encoder);
5191
5192                 if (conn_state->crtc != crtc)
5193                         continue;
5194
5195                 if (encoder->pre_pll_enable)
5196                         encoder->pre_pll_enable(encoder, crtc_state, conn_state);
5197         }
5198 }
5199
5200 static void intel_encoders_pre_enable(struct drm_crtc *crtc,
5201                                       struct intel_crtc_state *crtc_state,
5202                                       struct drm_atomic_state *old_state)
5203 {
5204         struct drm_connector_state *old_conn_state;
5205         struct drm_connector *conn;
5206         int i;
5207
5208         for_each_connector_in_state(old_state, conn, old_conn_state, i) {
5209                 struct drm_connector_state *conn_state = conn->state;
5210                 struct intel_encoder *encoder =
5211                         to_intel_encoder(conn_state->best_encoder);
5212
5213                 if (conn_state->crtc != crtc)
5214                         continue;
5215
5216                 if (encoder->pre_enable)
5217                         encoder->pre_enable(encoder, crtc_state, conn_state);
5218         }
5219 }
5220
5221 static void intel_encoders_enable(struct drm_crtc *crtc,
5222                                   struct intel_crtc_state *crtc_state,
5223                                   struct drm_atomic_state *old_state)
5224 {
5225         struct drm_connector_state *old_conn_state;
5226         struct drm_connector *conn;
5227         int i;
5228
5229         for_each_connector_in_state(old_state, conn, old_conn_state, i) {
5230                 struct drm_connector_state *conn_state = conn->state;
5231                 struct intel_encoder *encoder =
5232                         to_intel_encoder(conn_state->best_encoder);
5233
5234                 if (conn_state->crtc != crtc)
5235                         continue;
5236
5237                 encoder->enable(encoder, crtc_state, conn_state);
5238                 intel_opregion_notify_encoder(encoder, true);
5239         }
5240 }
5241
5242 static void intel_encoders_disable(struct drm_crtc *crtc,
5243                                    struct intel_crtc_state *old_crtc_state,
5244                                    struct drm_atomic_state *old_state)
5245 {
5246         struct drm_connector_state *old_conn_state;
5247         struct drm_connector *conn;
5248         int i;
5249
5250         for_each_connector_in_state(old_state, conn, old_conn_state, i) {
5251                 struct intel_encoder *encoder =
5252                         to_intel_encoder(old_conn_state->best_encoder);
5253
5254                 if (old_conn_state->crtc != crtc)
5255                         continue;
5256
5257                 intel_opregion_notify_encoder(encoder, false);
5258                 encoder->disable(encoder, old_crtc_state, old_conn_state);
5259         }
5260 }
5261
5262 static void intel_encoders_post_disable(struct drm_crtc *crtc,
5263                                         struct intel_crtc_state *old_crtc_state,
5264                                         struct drm_atomic_state *old_state)
5265 {
5266         struct drm_connector_state *old_conn_state;
5267         struct drm_connector *conn;
5268         int i;
5269
5270         for_each_connector_in_state(old_state, conn, old_conn_state, i) {
5271                 struct intel_encoder *encoder =
5272                         to_intel_encoder(old_conn_state->best_encoder);
5273
5274                 if (old_conn_state->crtc != crtc)
5275                         continue;
5276
5277                 if (encoder->post_disable)
5278                         encoder->post_disable(encoder, old_crtc_state, old_conn_state);
5279         }
5280 }
5281
5282 static void intel_encoders_post_pll_disable(struct drm_crtc *crtc,
5283                                             struct intel_crtc_state *old_crtc_state,
5284                                             struct drm_atomic_state *old_state)
5285 {
5286         struct drm_connector_state *old_conn_state;
5287         struct drm_connector *conn;
5288         int i;
5289
5290         for_each_connector_in_state(old_state, conn, old_conn_state, i) {
5291                 struct intel_encoder *encoder =
5292                         to_intel_encoder(old_conn_state->best_encoder);
5293
5294                 if (old_conn_state->crtc != crtc)
5295                         continue;
5296
5297                 if (encoder->post_pll_disable)
5298                         encoder->post_pll_disable(encoder, old_crtc_state, old_conn_state);
5299         }
5300 }
5301
5302 static void ironlake_crtc_enable(struct intel_crtc_state *pipe_config,
5303                                  struct drm_atomic_state *old_state)
5304 {
5305         struct drm_crtc *crtc = pipe_config->base.crtc;
5306         struct drm_device *dev = crtc->dev;
5307         struct drm_i915_private *dev_priv = to_i915(dev);
5308         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5309         int pipe = intel_crtc->pipe;
5310
5311         if (WARN_ON(intel_crtc->active))
5312                 return;
5313
5314         /*
5315          * Sometimes spurious CPU pipe underruns happen during FDI
5316          * training, at least with VGA+HDMI cloning. Suppress them.
5317          *
5318          * On ILK we get an occasional spurious CPU pipe underruns
5319          * between eDP port A enable and vdd enable. Also PCH port
5320          * enable seems to result in the occasional CPU pipe underrun.
5321          *
5322          * Spurious PCH underruns also occur during PCH enabling.
5323          */
5324         if (intel_crtc->config->has_pch_encoder || IS_GEN5(dev_priv))
5325                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, false);
5326         if (intel_crtc->config->has_pch_encoder)
5327                 intel_set_pch_fifo_underrun_reporting(dev_priv, pipe, false);
5328
5329         if (intel_crtc->config->has_pch_encoder)
5330                 intel_prepare_shared_dpll(intel_crtc);
5331
5332         if (intel_crtc_has_dp_encoder(intel_crtc->config))
5333                 intel_dp_set_m_n(intel_crtc, M1_N1);
5334
5335         intel_set_pipe_timings(intel_crtc);
5336         intel_set_pipe_src_size(intel_crtc);
5337
5338         if (intel_crtc->config->has_pch_encoder) {
5339                 intel_cpu_transcoder_set_m_n(intel_crtc,
5340                                      &intel_crtc->config->fdi_m_n, NULL);
5341         }
5342
5343         ironlake_set_pipeconf(crtc);
5344
5345         intel_crtc->active = true;
5346
5347         intel_encoders_pre_enable(crtc, pipe_config, old_state);
5348
5349         if (intel_crtc->config->has_pch_encoder) {
5350                 /* Note: FDI PLL enabling _must_ be done before we enable the
5351                  * cpu pipes, hence this is separate from all the other fdi/pch
5352                  * enabling. */
5353                 ironlake_fdi_pll_enable(intel_crtc);
5354         } else {
5355                 assert_fdi_tx_disabled(dev_priv, pipe);
5356                 assert_fdi_rx_disabled(dev_priv, pipe);
5357         }
5358
5359         ironlake_pfit_enable(intel_crtc);
5360
5361         /*
5362          * On ILK+ LUT must be loaded before the pipe is running but with
5363          * clocks enabled
5364          */
5365         intel_color_load_luts(&pipe_config->base);
5366
5367         if (dev_priv->display.initial_watermarks != NULL)
5368                 dev_priv->display.initial_watermarks(intel_crtc->config);
5369         intel_enable_pipe(intel_crtc);
5370
5371         if (intel_crtc->config->has_pch_encoder)
5372                 ironlake_pch_enable(crtc);
5373
5374         assert_vblank_disabled(crtc);
5375         drm_crtc_vblank_on(crtc);
5376
5377         intel_encoders_enable(crtc, pipe_config, old_state);
5378
5379         if (HAS_PCH_CPT(dev_priv))
5380                 cpt_verify_modeset(dev, intel_crtc->pipe);
5381
5382         /* Must wait for vblank to avoid spurious PCH FIFO underruns */
5383         if (intel_crtc->config->has_pch_encoder)
5384                 intel_wait_for_vblank(dev, pipe);
5385         intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
5386         intel_set_pch_fifo_underrun_reporting(dev_priv, pipe, true);
5387 }
5388
5389 /* IPS only exists on ULT machines and is tied to pipe A. */
5390 static bool hsw_crtc_supports_ips(struct intel_crtc *crtc)
5391 {
5392         return HAS_IPS(to_i915(crtc->base.dev)) && crtc->pipe == PIPE_A;
5393 }
5394
5395 static void haswell_crtc_enable(struct intel_crtc_state *pipe_config,
5396                                 struct drm_atomic_state *old_state)
5397 {
5398         struct drm_crtc *crtc = pipe_config->base.crtc;
5399         struct drm_device *dev = crtc->dev;
5400         struct drm_i915_private *dev_priv = to_i915(dev);
5401         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5402         int pipe = intel_crtc->pipe, hsw_workaround_pipe;
5403         enum transcoder cpu_transcoder = intel_crtc->config->cpu_transcoder;
5404
5405         if (WARN_ON(intel_crtc->active))
5406                 return;
5407
5408         if (intel_crtc->config->has_pch_encoder)
5409                 intel_set_pch_fifo_underrun_reporting(dev_priv, TRANSCODER_A,
5410                                                       false);
5411
5412         intel_encoders_pre_pll_enable(crtc, pipe_config, old_state);
5413
5414         if (intel_crtc->config->shared_dpll)
5415                 intel_enable_shared_dpll(intel_crtc);
5416
5417         if (intel_crtc_has_dp_encoder(intel_crtc->config))
5418                 intel_dp_set_m_n(intel_crtc, M1_N1);
5419
5420         if (!transcoder_is_dsi(cpu_transcoder))
5421                 intel_set_pipe_timings(intel_crtc);
5422
5423         intel_set_pipe_src_size(intel_crtc);
5424
5425         if (cpu_transcoder != TRANSCODER_EDP &&
5426             !transcoder_is_dsi(cpu_transcoder)) {
5427                 I915_WRITE(PIPE_MULT(cpu_transcoder),
5428                            intel_crtc->config->pixel_multiplier - 1);
5429         }
5430
5431         if (intel_crtc->config->has_pch_encoder) {
5432                 intel_cpu_transcoder_set_m_n(intel_crtc,
5433                                      &intel_crtc->config->fdi_m_n, NULL);
5434         }
5435
5436         if (!transcoder_is_dsi(cpu_transcoder))
5437                 haswell_set_pipeconf(crtc);
5438
5439         haswell_set_pipemisc(crtc);
5440
5441         intel_color_set_csc(&pipe_config->base);
5442
5443         intel_crtc->active = true;
5444
5445         if (intel_crtc->config->has_pch_encoder)
5446                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, false);
5447         else
5448                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
5449
5450         intel_encoders_pre_enable(crtc, pipe_config, old_state);
5451
5452         if (intel_crtc->config->has_pch_encoder)
5453                 dev_priv->display.fdi_link_train(crtc);
5454
5455         if (!transcoder_is_dsi(cpu_transcoder))
5456                 intel_ddi_enable_pipe_clock(intel_crtc);
5457
5458         if (INTEL_INFO(dev)->gen >= 9)
5459                 skylake_pfit_enable(intel_crtc);
5460         else
5461                 ironlake_pfit_enable(intel_crtc);
5462
5463         /*
5464          * On ILK+ LUT must be loaded before the pipe is running but with
5465          * clocks enabled
5466          */
5467         intel_color_load_luts(&pipe_config->base);
5468
5469         intel_ddi_set_pipe_settings(crtc);
5470         if (!transcoder_is_dsi(cpu_transcoder))
5471                 intel_ddi_enable_transcoder_func(crtc);
5472
5473         if (dev_priv->display.initial_watermarks != NULL)
5474                 dev_priv->display.initial_watermarks(pipe_config);
5475         else
5476                 intel_update_watermarks(crtc);
5477
5478         /* XXX: Do the pipe assertions at the right place for BXT DSI. */
5479         if (!transcoder_is_dsi(cpu_transcoder))
5480                 intel_enable_pipe(intel_crtc);
5481
5482         if (intel_crtc->config->has_pch_encoder)
5483                 lpt_pch_enable(crtc);
5484
5485         if (intel_crtc->config->dp_encoder_is_mst)
5486                 intel_ddi_set_vc_payload_alloc(crtc, true);
5487
5488         assert_vblank_disabled(crtc);
5489         drm_crtc_vblank_on(crtc);
5490
5491         intel_encoders_enable(crtc, pipe_config, old_state);
5492
5493         if (intel_crtc->config->has_pch_encoder) {
5494                 intel_wait_for_vblank(dev, pipe);
5495                 intel_wait_for_vblank(dev, pipe);
5496                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
5497                 intel_set_pch_fifo_underrun_reporting(dev_priv, TRANSCODER_A,
5498                                                       true);
5499         }
5500
5501         /* If we change the relative order between pipe/planes enabling, we need
5502          * to change the workaround. */
5503         hsw_workaround_pipe = pipe_config->hsw_workaround_pipe;
5504         if (IS_HASWELL(dev) && hsw_workaround_pipe != INVALID_PIPE) {
5505                 intel_wait_for_vblank(dev, hsw_workaround_pipe);
5506                 intel_wait_for_vblank(dev, hsw_workaround_pipe);
5507         }
5508 }
5509
5510 static void ironlake_pfit_disable(struct intel_crtc *crtc, bool force)
5511 {
5512         struct drm_device *dev = crtc->base.dev;
5513         struct drm_i915_private *dev_priv = to_i915(dev);
5514         int pipe = crtc->pipe;
5515
5516         /* To avoid upsetting the power well on haswell only disable the pfit if
5517          * it's in use. The hw state code will make sure we get this right. */
5518         if (force || crtc->config->pch_pfit.enabled) {
5519                 I915_WRITE(PF_CTL(pipe), 0);
5520                 I915_WRITE(PF_WIN_POS(pipe), 0);
5521                 I915_WRITE(PF_WIN_SZ(pipe), 0);
5522         }
5523 }
5524
5525 static void ironlake_crtc_disable(struct intel_crtc_state *old_crtc_state,
5526                                   struct drm_atomic_state *old_state)
5527 {
5528         struct drm_crtc *crtc = old_crtc_state->base.crtc;
5529         struct drm_device *dev = crtc->dev;
5530         struct drm_i915_private *dev_priv = to_i915(dev);
5531         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5532         int pipe = intel_crtc->pipe;
5533
5534         /*
5535          * Sometimes spurious CPU pipe underruns happen when the
5536          * pipe is already disabled, but FDI RX/TX is still enabled.
5537          * Happens at least with VGA+HDMI cloning. Suppress them.
5538          */
5539         if (intel_crtc->config->has_pch_encoder) {
5540                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, false);
5541                 intel_set_pch_fifo_underrun_reporting(dev_priv, pipe, false);
5542         }
5543
5544         intel_encoders_disable(crtc, old_crtc_state, old_state);
5545
5546         drm_crtc_vblank_off(crtc);
5547         assert_vblank_disabled(crtc);
5548
5549         intel_disable_pipe(intel_crtc);
5550
5551         ironlake_pfit_disable(intel_crtc, false);
5552
5553         if (intel_crtc->config->has_pch_encoder)
5554                 ironlake_fdi_disable(crtc);
5555
5556         intel_encoders_post_disable(crtc, old_crtc_state, old_state);
5557
5558         if (intel_crtc->config->has_pch_encoder) {
5559                 ironlake_disable_pch_transcoder(dev_priv, pipe);
5560
5561                 if (HAS_PCH_CPT(dev_priv)) {
5562                         i915_reg_t reg;
5563                         u32 temp;
5564
5565                         /* disable TRANS_DP_CTL */
5566                         reg = TRANS_DP_CTL(pipe);
5567                         temp = I915_READ(reg);
5568                         temp &= ~(TRANS_DP_OUTPUT_ENABLE |
5569                                   TRANS_DP_PORT_SEL_MASK);
5570                         temp |= TRANS_DP_PORT_SEL_NONE;
5571                         I915_WRITE(reg, temp);
5572
5573                         /* disable DPLL_SEL */
5574                         temp = I915_READ(PCH_DPLL_SEL);
5575                         temp &= ~(TRANS_DPLL_ENABLE(pipe) | TRANS_DPLLB_SEL(pipe));
5576                         I915_WRITE(PCH_DPLL_SEL, temp);
5577                 }
5578
5579                 ironlake_fdi_pll_disable(intel_crtc);
5580         }
5581
5582         intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
5583         intel_set_pch_fifo_underrun_reporting(dev_priv, pipe, true);
5584 }
5585
5586 static void haswell_crtc_disable(struct intel_crtc_state *old_crtc_state,
5587                                  struct drm_atomic_state *old_state)
5588 {
5589         struct drm_crtc *crtc = old_crtc_state->base.crtc;
5590         struct drm_device *dev = crtc->dev;
5591         struct drm_i915_private *dev_priv = to_i915(dev);
5592         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5593         enum transcoder cpu_transcoder = intel_crtc->config->cpu_transcoder;
5594
5595         if (intel_crtc->config->has_pch_encoder)
5596                 intel_set_pch_fifo_underrun_reporting(dev_priv, TRANSCODER_A,
5597                                                       false);
5598
5599         intel_encoders_disable(crtc, old_crtc_state, old_state);
5600
5601         drm_crtc_vblank_off(crtc);
5602         assert_vblank_disabled(crtc);
5603
5604         /* XXX: Do the pipe assertions at the right place for BXT DSI. */
5605         if (!transcoder_is_dsi(cpu_transcoder))
5606                 intel_disable_pipe(intel_crtc);
5607
5608         if (intel_crtc->config->dp_encoder_is_mst)
5609                 intel_ddi_set_vc_payload_alloc(crtc, false);
5610
5611         if (!transcoder_is_dsi(cpu_transcoder))
5612                 intel_ddi_disable_transcoder_func(dev_priv, cpu_transcoder);
5613
5614         if (INTEL_INFO(dev)->gen >= 9)
5615                 skylake_scaler_disable(intel_crtc);
5616         else
5617                 ironlake_pfit_disable(intel_crtc, false);
5618
5619         if (!transcoder_is_dsi(cpu_transcoder))
5620                 intel_ddi_disable_pipe_clock(intel_crtc);
5621
5622         intel_encoders_post_disable(crtc, old_crtc_state, old_state);
5623
5624         if (old_crtc_state->has_pch_encoder)
5625                 intel_set_pch_fifo_underrun_reporting(dev_priv, TRANSCODER_A,
5626                                                       true);
5627 }
5628
5629 static void i9xx_pfit_enable(struct intel_crtc *crtc)
5630 {
5631         struct drm_device *dev = crtc->base.dev;
5632         struct drm_i915_private *dev_priv = to_i915(dev);
5633         struct intel_crtc_state *pipe_config = crtc->config;
5634
5635         if (!pipe_config->gmch_pfit.control)
5636                 return;
5637
5638         /*
5639          * The panel fitter should only be adjusted whilst the pipe is disabled,
5640          * according to register description and PRM.
5641          */
5642         WARN_ON(I915_READ(PFIT_CONTROL) & PFIT_ENABLE);
5643         assert_pipe_disabled(dev_priv, crtc->pipe);
5644
5645         I915_WRITE(PFIT_PGM_RATIOS, pipe_config->gmch_pfit.pgm_ratios);
5646         I915_WRITE(PFIT_CONTROL, pipe_config->gmch_pfit.control);
5647
5648         /* Border color in case we don't scale up to the full screen. Black by
5649          * default, change to something else for debugging. */
5650         I915_WRITE(BCLRPAT(crtc->pipe), 0);
5651 }
5652
5653 static enum intel_display_power_domain port_to_power_domain(enum port port)
5654 {
5655         switch (port) {
5656         case PORT_A:
5657                 return POWER_DOMAIN_PORT_DDI_A_LANES;
5658         case PORT_B:
5659                 return POWER_DOMAIN_PORT_DDI_B_LANES;
5660         case PORT_C:
5661                 return POWER_DOMAIN_PORT_DDI_C_LANES;
5662         case PORT_D:
5663                 return POWER_DOMAIN_PORT_DDI_D_LANES;
5664         case PORT_E:
5665                 return POWER_DOMAIN_PORT_DDI_E_LANES;
5666         default:
5667                 MISSING_CASE(port);
5668                 return POWER_DOMAIN_PORT_OTHER;
5669         }
5670 }
5671
5672 static enum intel_display_power_domain port_to_aux_power_domain(enum port port)
5673 {
5674         switch (port) {
5675         case PORT_A:
5676                 return POWER_DOMAIN_AUX_A;
5677         case PORT_B:
5678                 return POWER_DOMAIN_AUX_B;
5679         case PORT_C:
5680                 return POWER_DOMAIN_AUX_C;
5681         case PORT_D:
5682                 return POWER_DOMAIN_AUX_D;
5683         case PORT_E:
5684                 /* FIXME: Check VBT for actual wiring of PORT E */
5685                 return POWER_DOMAIN_AUX_D;
5686         default:
5687                 MISSING_CASE(port);
5688                 return POWER_DOMAIN_AUX_A;
5689         }
5690 }
5691
5692 enum intel_display_power_domain
5693 intel_display_port_power_domain(struct intel_encoder *intel_encoder)
5694 {
5695         struct drm_i915_private *dev_priv = to_i915(intel_encoder->base.dev);
5696         struct intel_digital_port *intel_dig_port;
5697
5698         switch (intel_encoder->type) {
5699         case INTEL_OUTPUT_UNKNOWN:
5700                 /* Only DDI platforms should ever use this output type */
5701                 WARN_ON_ONCE(!HAS_DDI(dev_priv));
5702         case INTEL_OUTPUT_DP:
5703         case INTEL_OUTPUT_HDMI:
5704         case INTEL_OUTPUT_EDP:
5705                 intel_dig_port = enc_to_dig_port(&intel_encoder->base);
5706                 return port_to_power_domain(intel_dig_port->port);
5707         case INTEL_OUTPUT_DP_MST:
5708                 intel_dig_port = enc_to_mst(&intel_encoder->base)->primary;
5709                 return port_to_power_domain(intel_dig_port->port);
5710         case INTEL_OUTPUT_ANALOG:
5711                 return POWER_DOMAIN_PORT_CRT;
5712         case INTEL_OUTPUT_DSI:
5713                 return POWER_DOMAIN_PORT_DSI;
5714         default:
5715                 return POWER_DOMAIN_PORT_OTHER;
5716         }
5717 }
5718
5719 enum intel_display_power_domain
5720 intel_display_port_aux_power_domain(struct intel_encoder *intel_encoder)
5721 {
5722         struct drm_i915_private *dev_priv = to_i915(intel_encoder->base.dev);
5723         struct intel_digital_port *intel_dig_port;
5724
5725         switch (intel_encoder->type) {
5726         case INTEL_OUTPUT_UNKNOWN:
5727         case INTEL_OUTPUT_HDMI:
5728                 /*
5729                  * Only DDI platforms should ever use these output types.
5730                  * We can get here after the HDMI detect code has already set
5731                  * the type of the shared encoder. Since we can't be sure
5732                  * what's the status of the given connectors, play safe and
5733                  * run the DP detection too.
5734                  */
5735                 WARN_ON_ONCE(!HAS_DDI(dev_priv));
5736         case INTEL_OUTPUT_DP:
5737         case INTEL_OUTPUT_EDP:
5738                 intel_dig_port = enc_to_dig_port(&intel_encoder->base);
5739                 return port_to_aux_power_domain(intel_dig_port->port);
5740         case INTEL_OUTPUT_DP_MST:
5741                 intel_dig_port = enc_to_mst(&intel_encoder->base)->primary;
5742                 return port_to_aux_power_domain(intel_dig_port->port);
5743         default:
5744                 MISSING_CASE(intel_encoder->type);
5745                 return POWER_DOMAIN_AUX_A;
5746         }
5747 }
5748
5749 static unsigned long get_crtc_power_domains(struct drm_crtc *crtc,
5750                                             struct intel_crtc_state *crtc_state)
5751 {
5752         struct drm_device *dev = crtc->dev;
5753         struct drm_encoder *encoder;
5754         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5755         enum pipe pipe = intel_crtc->pipe;
5756         unsigned long mask;
5757         enum transcoder transcoder = crtc_state->cpu_transcoder;
5758
5759         if (!crtc_state->base.active)
5760                 return 0;
5761
5762         mask = BIT(POWER_DOMAIN_PIPE(pipe));
5763         mask |= BIT(POWER_DOMAIN_TRANSCODER(transcoder));
5764         if (crtc_state->pch_pfit.enabled ||
5765             crtc_state->pch_pfit.force_thru)
5766                 mask |= BIT(POWER_DOMAIN_PIPE_PANEL_FITTER(pipe));
5767
5768         drm_for_each_encoder_mask(encoder, dev, crtc_state->base.encoder_mask) {
5769                 struct intel_encoder *intel_encoder = to_intel_encoder(encoder);
5770
5771                 mask |= BIT(intel_display_port_power_domain(intel_encoder));
5772         }
5773
5774         if (crtc_state->shared_dpll)
5775                 mask |= BIT(POWER_DOMAIN_PLLS);
5776
5777         return mask;
5778 }
5779
5780 static unsigned long
5781 modeset_get_crtc_power_domains(struct drm_crtc *crtc,
5782                                struct intel_crtc_state *crtc_state)
5783 {
5784         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
5785         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5786         enum intel_display_power_domain domain;
5787         unsigned long domains, new_domains, old_domains;
5788
5789         old_domains = intel_crtc->enabled_power_domains;
5790         intel_crtc->enabled_power_domains = new_domains =
5791                 get_crtc_power_domains(crtc, crtc_state);
5792
5793         domains = new_domains & ~old_domains;
5794
5795         for_each_power_domain(domain, domains)
5796                 intel_display_power_get(dev_priv, domain);
5797
5798         return old_domains & ~new_domains;
5799 }
5800
5801 static void modeset_put_power_domains(struct drm_i915_private *dev_priv,
5802                                       unsigned long domains)
5803 {
5804         enum intel_display_power_domain domain;
5805
5806         for_each_power_domain(domain, domains)
5807                 intel_display_power_put(dev_priv, domain);
5808 }
5809
5810 static int intel_compute_max_dotclk(struct drm_i915_private *dev_priv)
5811 {
5812         int max_cdclk_freq = dev_priv->max_cdclk_freq;
5813
5814         if (INTEL_INFO(dev_priv)->gen >= 9 ||
5815             IS_HASWELL(dev_priv) || IS_BROADWELL(dev_priv))
5816                 return max_cdclk_freq;
5817         else if (IS_CHERRYVIEW(dev_priv))
5818                 return max_cdclk_freq*95/100;
5819         else if (INTEL_INFO(dev_priv)->gen < 4)
5820                 return 2*max_cdclk_freq*90/100;
5821         else
5822                 return max_cdclk_freq*90/100;
5823 }
5824
5825 static int skl_calc_cdclk(int max_pixclk, int vco);
5826
5827 static void intel_update_max_cdclk(struct drm_device *dev)
5828 {
5829         struct drm_i915_private *dev_priv = to_i915(dev);
5830
5831         if (IS_SKYLAKE(dev) || IS_KABYLAKE(dev)) {
5832                 u32 limit = I915_READ(SKL_DFSM) & SKL_DFSM_CDCLK_LIMIT_MASK;
5833                 int max_cdclk, vco;
5834
5835                 vco = dev_priv->skl_preferred_vco_freq;
5836                 WARN_ON(vco != 8100000 && vco != 8640000);
5837
5838                 /*
5839                  * Use the lower (vco 8640) cdclk values as a
5840                  * first guess. skl_calc_cdclk() will correct it
5841                  * if the preferred vco is 8100 instead.
5842                  */
5843                 if (limit == SKL_DFSM_CDCLK_LIMIT_675)
5844                         max_cdclk = 617143;
5845                 else if (limit == SKL_DFSM_CDCLK_LIMIT_540)
5846                         max_cdclk = 540000;
5847                 else if (limit == SKL_DFSM_CDCLK_LIMIT_450)
5848                         max_cdclk = 432000;
5849                 else
5850                         max_cdclk = 308571;
5851
5852                 dev_priv->max_cdclk_freq = skl_calc_cdclk(max_cdclk, vco);
5853         } else if (IS_BROXTON(dev)) {
5854                 dev_priv->max_cdclk_freq = 624000;
5855         } else if (IS_BROADWELL(dev))  {
5856                 /*
5857                  * FIXME with extra cooling we can allow
5858                  * 540 MHz for ULX and 675 Mhz for ULT.
5859                  * How can we know if extra cooling is
5860                  * available? PCI ID, VTB, something else?
5861                  */
5862                 if (I915_READ(FUSE_STRAP) & HSW_CDCLK_LIMIT)
5863                         dev_priv->max_cdclk_freq = 450000;
5864                 else if (IS_BDW_ULX(dev_priv))
5865                         dev_priv->max_cdclk_freq = 450000;
5866                 else if (IS_BDW_ULT(dev_priv))
5867                         dev_priv->max_cdclk_freq = 540000;
5868                 else
5869                         dev_priv->max_cdclk_freq = 675000;
5870         } else if (IS_CHERRYVIEW(dev)) {
5871                 dev_priv->max_cdclk_freq = 320000;
5872         } else if (IS_VALLEYVIEW(dev)) {
5873                 dev_priv->max_cdclk_freq = 400000;
5874         } else {
5875                 /* otherwise assume cdclk is fixed */
5876                 dev_priv->max_cdclk_freq = dev_priv->cdclk_freq;
5877         }
5878
5879         dev_priv->max_dotclk_freq = intel_compute_max_dotclk(dev_priv);
5880
5881         DRM_DEBUG_DRIVER("Max CD clock rate: %d kHz\n",
5882                          dev_priv->max_cdclk_freq);
5883
5884         DRM_DEBUG_DRIVER("Max dotclock rate: %d kHz\n",
5885                          dev_priv->max_dotclk_freq);
5886 }
5887
5888 static void intel_update_cdclk(struct drm_device *dev)
5889 {
5890         struct drm_i915_private *dev_priv = to_i915(dev);
5891
5892         dev_priv->cdclk_freq = dev_priv->display.get_display_clock_speed(dev);
5893
5894         if (INTEL_GEN(dev_priv) >= 9)
5895                 DRM_DEBUG_DRIVER("Current CD clock rate: %d kHz, VCO: %d kHz, ref: %d kHz\n",
5896                                  dev_priv->cdclk_freq, dev_priv->cdclk_pll.vco,
5897                                  dev_priv->cdclk_pll.ref);
5898         else
5899                 DRM_DEBUG_DRIVER("Current CD clock rate: %d kHz\n",
5900                                  dev_priv->cdclk_freq);
5901
5902         /*
5903          * 9:0 CMBUS [sic] CDCLK frequency (cdfreq):
5904          * Programmng [sic] note: bit[9:2] should be programmed to the number
5905          * of cdclk that generates 4MHz reference clock freq which is used to
5906          * generate GMBus clock. This will vary with the cdclk freq.
5907          */
5908         if (IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv))
5909                 I915_WRITE(GMBUSFREQ_VLV, DIV_ROUND_UP(dev_priv->cdclk_freq, 1000));
5910 }
5911
5912 /* convert from kHz to .1 fixpoint MHz with -1MHz offset */
5913 static int skl_cdclk_decimal(int cdclk)
5914 {
5915         return DIV_ROUND_CLOSEST(cdclk - 1000, 500);
5916 }
5917
5918 static int bxt_de_pll_vco(struct drm_i915_private *dev_priv, int cdclk)
5919 {
5920         int ratio;
5921
5922         if (cdclk == dev_priv->cdclk_pll.ref)
5923                 return 0;
5924
5925         switch (cdclk) {
5926         default:
5927                 MISSING_CASE(cdclk);
5928         case 144000:
5929         case 288000:
5930         case 384000:
5931         case 576000:
5932                 ratio = 60;
5933                 break;
5934         case 624000:
5935                 ratio = 65;
5936                 break;
5937         }
5938
5939         return dev_priv->cdclk_pll.ref * ratio;
5940 }
5941
5942 static void bxt_de_pll_disable(struct drm_i915_private *dev_priv)
5943 {
5944         I915_WRITE(BXT_DE_PLL_ENABLE, 0);
5945
5946         /* Timeout 200us */
5947         if (intel_wait_for_register(dev_priv,
5948                                     BXT_DE_PLL_ENABLE, BXT_DE_PLL_LOCK, 0,
5949                                     1))
5950                 DRM_ERROR("timeout waiting for DE PLL unlock\n");
5951
5952         dev_priv->cdclk_pll.vco = 0;
5953 }
5954
5955 static void bxt_de_pll_enable(struct drm_i915_private *dev_priv, int vco)
5956 {
5957         int ratio = DIV_ROUND_CLOSEST(vco, dev_priv->cdclk_pll.ref);
5958         u32 val;
5959
5960         val = I915_READ(BXT_DE_PLL_CTL);
5961         val &= ~BXT_DE_PLL_RATIO_MASK;
5962         val |= BXT_DE_PLL_RATIO(ratio);
5963         I915_WRITE(BXT_DE_PLL_CTL, val);
5964
5965         I915_WRITE(BXT_DE_PLL_ENABLE, BXT_DE_PLL_PLL_ENABLE);
5966
5967         /* Timeout 200us */
5968         if (intel_wait_for_register(dev_priv,
5969                                     BXT_DE_PLL_ENABLE,
5970                                     BXT_DE_PLL_LOCK,
5971                                     BXT_DE_PLL_LOCK,
5972                                     1))
5973                 DRM_ERROR("timeout waiting for DE PLL lock\n");
5974
5975         dev_priv->cdclk_pll.vco = vco;
5976 }
5977
5978 static void bxt_set_cdclk(struct drm_i915_private *dev_priv, int cdclk)
5979 {
5980         u32 val, divider;
5981         int vco, ret;
5982
5983         vco = bxt_de_pll_vco(dev_priv, cdclk);
5984
5985         DRM_DEBUG_DRIVER("Changing CDCLK to %d kHz (VCO %d kHz)\n", cdclk, vco);
5986
5987         /* cdclk = vco / 2 / div{1,1.5,2,4} */
5988         switch (DIV_ROUND_CLOSEST(vco, cdclk)) {
5989         case 8:
5990                 divider = BXT_CDCLK_CD2X_DIV_SEL_4;
5991                 break;
5992         case 4:
5993                 divider = BXT_CDCLK_CD2X_DIV_SEL_2;
5994                 break;
5995         case 3:
5996                 divider = BXT_CDCLK_CD2X_DIV_SEL_1_5;
5997                 break;
5998         case 2:
5999                 divider = BXT_CDCLK_CD2X_DIV_SEL_1;
6000                 break;
6001         default:
6002                 WARN_ON(cdclk != dev_priv->cdclk_pll.ref);
6003                 WARN_ON(vco != 0);
6004
6005                 divider = BXT_CDCLK_CD2X_DIV_SEL_1;
6006                 break;
6007         }
6008
6009         /* Inform power controller of upcoming frequency change */
6010         mutex_lock(&dev_priv->rps.hw_lock);
6011         ret = sandybridge_pcode_write(dev_priv, HSW_PCODE_DE_WRITE_FREQ_REQ,
6012                                       0x80000000);
6013         mutex_unlock(&dev_priv->rps.hw_lock);
6014
6015         if (ret) {
6016                 DRM_ERROR("PCode CDCLK freq change notify failed (err %d, freq %d)\n",
6017                           ret, cdclk);
6018                 return;
6019         }
6020
6021         if (dev_priv->cdclk_pll.vco != 0 &&
6022             dev_priv->cdclk_pll.vco != vco)
6023                 bxt_de_pll_disable(dev_priv);
6024
6025         if (dev_priv->cdclk_pll.vco != vco)
6026                 bxt_de_pll_enable(dev_priv, vco);
6027
6028         val = divider | skl_cdclk_decimal(cdclk);
6029         /*
6030          * FIXME if only the cd2x divider needs changing, it could be done
6031          * without shutting off the pipe (if only one pipe is active).
6032          */
6033         val |= BXT_CDCLK_CD2X_PIPE_NONE;
6034         /*
6035          * Disable SSA Precharge when CD clock frequency < 500 MHz,
6036          * enable otherwise.
6037          */
6038         if (cdclk >= 500000)
6039                 val |= BXT_CDCLK_SSA_PRECHARGE_ENABLE;
6040         I915_WRITE(CDCLK_CTL, val);
6041
6042         mutex_lock(&dev_priv->rps.hw_lock);
6043         ret = sandybridge_pcode_write(dev_priv, HSW_PCODE_DE_WRITE_FREQ_REQ,
6044                                       DIV_ROUND_UP(cdclk, 25000));
6045         mutex_unlock(&dev_priv->rps.hw_lock);
6046
6047         if (ret) {
6048                 DRM_ERROR("PCode CDCLK freq set failed, (err %d, freq %d)\n",
6049                           ret, cdclk);
6050                 return;
6051         }
6052
6053         intel_update_cdclk(&dev_priv->drm);
6054 }
6055
6056 static void bxt_sanitize_cdclk(struct drm_i915_private *dev_priv)
6057 {
6058         u32 cdctl, expected;
6059
6060         intel_update_cdclk(&dev_priv->drm);
6061
6062         if (dev_priv->cdclk_pll.vco == 0 ||
6063             dev_priv->cdclk_freq == dev_priv->cdclk_pll.ref)
6064                 goto sanitize;
6065
6066         /* DPLL okay; verify the cdclock
6067          *
6068          * Some BIOS versions leave an incorrect decimal frequency value and
6069          * set reserved MBZ bits in CDCLK_CTL at least during exiting from S4,
6070          * so sanitize this register.
6071          */
6072         cdctl = I915_READ(CDCLK_CTL);
6073         /*
6074          * Let's ignore the pipe field, since BIOS could have configured the
6075          * dividers both synching to an active pipe, or asynchronously
6076          * (PIPE_NONE).
6077          */
6078         cdctl &= ~BXT_CDCLK_CD2X_PIPE_NONE;
6079
6080         expected = (cdctl & BXT_CDCLK_CD2X_DIV_SEL_MASK) |
6081                    skl_cdclk_decimal(dev_priv->cdclk_freq);
6082         /*
6083          * Disable SSA Precharge when CD clock frequency < 500 MHz,
6084          * enable otherwise.
6085          */
6086         if (dev_priv->cdclk_freq >= 500000)
6087                 expected |= BXT_CDCLK_SSA_PRECHARGE_ENABLE;
6088
6089         if (cdctl == expected)
6090                 /* All well; nothing to sanitize */
6091                 return;
6092
6093 sanitize:
6094         DRM_DEBUG_KMS("Sanitizing cdclk programmed by pre-os\n");
6095
6096         /* force cdclk programming */
6097         dev_priv->cdclk_freq = 0;
6098
6099         /* force full PLL disable + enable */
6100         dev_priv->cdclk_pll.vco = -1;
6101 }
6102
6103 void bxt_init_cdclk(struct drm_i915_private *dev_priv)
6104 {
6105         bxt_sanitize_cdclk(dev_priv);
6106
6107         if (dev_priv->cdclk_freq != 0 && dev_priv->cdclk_pll.vco != 0)
6108                 return;
6109
6110         /*
6111          * FIXME:
6112          * - The initial CDCLK needs to be read from VBT.
6113          *   Need to make this change after VBT has changes for BXT.
6114          */
6115         bxt_set_cdclk(dev_priv, bxt_calc_cdclk(0));
6116 }
6117
6118 void bxt_uninit_cdclk(struct drm_i915_private *dev_priv)
6119 {
6120         bxt_set_cdclk(dev_priv, dev_priv->cdclk_pll.ref);
6121 }
6122
6123 static int skl_calc_cdclk(int max_pixclk, int vco)
6124 {
6125         if (vco == 8640000) {
6126                 if (max_pixclk > 540000)
6127                         return 617143;
6128                 else if (max_pixclk > 432000)
6129                         return 540000;
6130                 else if (max_pixclk > 308571)
6131                         return 432000;
6132                 else
6133                         return 308571;
6134         } else {
6135                 if (max_pixclk > 540000)
6136                         return 675000;
6137                 else if (max_pixclk > 450000)
6138                         return 540000;
6139                 else if (max_pixclk > 337500)
6140                         return 450000;
6141                 else
6142                         return 337500;
6143         }
6144 }
6145
6146 static void
6147 skl_dpll0_update(struct drm_i915_private *dev_priv)
6148 {
6149         u32 val;
6150
6151         dev_priv->cdclk_pll.ref = 24000;
6152         dev_priv->cdclk_pll.vco = 0;
6153
6154         val = I915_READ(LCPLL1_CTL);
6155         if ((val & LCPLL_PLL_ENABLE) == 0)
6156                 return;
6157
6158         if (WARN_ON((val & LCPLL_PLL_LOCK) == 0))
6159                 return;
6160
6161         val = I915_READ(DPLL_CTRL1);
6162
6163         if (WARN_ON((val & (DPLL_CTRL1_HDMI_MODE(SKL_DPLL0) |
6164                             DPLL_CTRL1_SSC(SKL_DPLL0) |
6165                             DPLL_CTRL1_OVERRIDE(SKL_DPLL0))) !=
6166                     DPLL_CTRL1_OVERRIDE(SKL_DPLL0)))
6167                 return;
6168
6169         switch (val & DPLL_CTRL1_LINK_RATE_MASK(SKL_DPLL0)) {
6170         case DPLL_CTRL1_LINK_RATE(DPLL_CTRL1_LINK_RATE_810, SKL_DPLL0):
6171         case DPLL_CTRL1_LINK_RATE(DPLL_CTRL1_LINK_RATE_1350, SKL_DPLL0):
6172         case DPLL_CTRL1_LINK_RATE(DPLL_CTRL1_LINK_RATE_1620, SKL_DPLL0):
6173         case DPLL_CTRL1_LINK_RATE(DPLL_CTRL1_LINK_RATE_2700, SKL_DPLL0):
6174                 dev_priv->cdclk_pll.vco = 8100000;
6175                 break;
6176         case DPLL_CTRL1_LINK_RATE(DPLL_CTRL1_LINK_RATE_1080, SKL_DPLL0):
6177         case DPLL_CTRL1_LINK_RATE(DPLL_CTRL1_LINK_RATE_2160, SKL_DPLL0):
6178                 dev_priv->cdclk_pll.vco = 8640000;
6179                 break;
6180         default:
6181                 MISSING_CASE(val & DPLL_CTRL1_LINK_RATE_MASK(SKL_DPLL0));
6182                 break;
6183         }
6184 }
6185
6186 void skl_set_preferred_cdclk_vco(struct drm_i915_private *dev_priv, int vco)
6187 {
6188         bool changed = dev_priv->skl_preferred_vco_freq != vco;
6189
6190         dev_priv->skl_preferred_vco_freq = vco;
6191
6192         if (changed)
6193                 intel_update_max_cdclk(&dev_priv->drm);
6194 }
6195
6196 static void
6197 skl_dpll0_enable(struct drm_i915_private *dev_priv, int vco)
6198 {
6199         int min_cdclk = skl_calc_cdclk(0, vco);
6200         u32 val;
6201
6202         WARN_ON(vco != 8100000 && vco != 8640000);
6203
6204         /* select the minimum CDCLK before enabling DPLL 0 */
6205         val = CDCLK_FREQ_337_308 | skl_cdclk_decimal(min_cdclk);
6206         I915_WRITE(CDCLK_CTL, val);
6207         POSTING_READ(CDCLK_CTL);
6208
6209         /*
6210          * We always enable DPLL0 with the lowest link rate possible, but still
6211          * taking into account the VCO required to operate the eDP panel at the
6212          * desired frequency. The usual DP link rates operate with a VCO of
6213          * 8100 while the eDP 1.4 alternate link rates need a VCO of 8640.
6214          * The modeset code is responsible for the selection of the exact link
6215          * rate later on, with the constraint of choosing a frequency that
6216          * works with vco.
6217          */
6218         val = I915_READ(DPLL_CTRL1);
6219
6220         val &= ~(DPLL_CTRL1_HDMI_MODE(SKL_DPLL0) | DPLL_CTRL1_SSC(SKL_DPLL0) |
6221                  DPLL_CTRL1_LINK_RATE_MASK(SKL_DPLL0));
6222         val |= DPLL_CTRL1_OVERRIDE(SKL_DPLL0);
6223         if (vco == 8640000)
6224                 val |= DPLL_CTRL1_LINK_RATE(DPLL_CTRL1_LINK_RATE_1080,
6225                                             SKL_DPLL0);
6226         else
6227                 val |= DPLL_CTRL1_LINK_RATE(DPLL_CTRL1_LINK_RATE_810,
6228                                             SKL_DPLL0);
6229
6230         I915_WRITE(DPLL_CTRL1, val);
6231         POSTING_READ(DPLL_CTRL1);
6232
6233         I915_WRITE(LCPLL1_CTL, I915_READ(LCPLL1_CTL) | LCPLL_PLL_ENABLE);
6234
6235         if (intel_wait_for_register(dev_priv,
6236                                     LCPLL1_CTL, LCPLL_PLL_LOCK, LCPLL_PLL_LOCK,
6237                                     5))
6238                 DRM_ERROR("DPLL0 not locked\n");
6239
6240         dev_priv->cdclk_pll.vco = vco;
6241
6242         /* We'll want to keep using the current vco from now on. */
6243         skl_set_preferred_cdclk_vco(dev_priv, vco);
6244 }
6245
6246 static void
6247 skl_dpll0_disable(struct drm_i915_private *dev_priv)
6248 {
6249         I915_WRITE(LCPLL1_CTL, I915_READ(LCPLL1_CTL) & ~LCPLL_PLL_ENABLE);
6250         if (intel_wait_for_register(dev_priv,
6251                                    LCPLL1_CTL, LCPLL_PLL_LOCK, 0,
6252                                    1))
6253                 DRM_ERROR("Couldn't disable DPLL0\n");
6254
6255         dev_priv->cdclk_pll.vco = 0;
6256 }
6257
6258 static bool skl_cdclk_pcu_ready(struct drm_i915_private *dev_priv)
6259 {
6260         int ret;
6261         u32 val;
6262
6263         /* inform PCU we want to change CDCLK */
6264         val = SKL_CDCLK_PREPARE_FOR_CHANGE;
6265         mutex_lock(&dev_priv->rps.hw_lock);
6266         ret = sandybridge_pcode_read(dev_priv, SKL_PCODE_CDCLK_CONTROL, &val);
6267         mutex_unlock(&dev_priv->rps.hw_lock);
6268
6269         return ret == 0 && (val & SKL_CDCLK_READY_FOR_CHANGE);
6270 }
6271
6272 static bool skl_cdclk_wait_for_pcu_ready(struct drm_i915_private *dev_priv)
6273 {
6274         return _wait_for(skl_cdclk_pcu_ready(dev_priv), 3000, 10) == 0;
6275 }
6276
6277 static void skl_set_cdclk(struct drm_i915_private *dev_priv, int cdclk, int vco)
6278 {
6279         struct drm_device *dev = &dev_priv->drm;
6280         u32 freq_select, pcu_ack;
6281
6282         WARN_ON((cdclk == 24000) != (vco == 0));
6283
6284         DRM_DEBUG_DRIVER("Changing CDCLK to %d kHz (VCO %d kHz)\n", cdclk, vco);
6285
6286         if (!skl_cdclk_wait_for_pcu_ready(dev_priv)) {
6287                 DRM_ERROR("failed to inform PCU about cdclk change\n");
6288                 return;
6289         }
6290
6291         /* set CDCLK_CTL */
6292         switch (cdclk) {
6293         case 450000:
6294         case 432000:
6295                 freq_select = CDCLK_FREQ_450_432;
6296                 pcu_ack = 1;
6297                 break;
6298         case 540000:
6299                 freq_select = CDCLK_FREQ_540;
6300                 pcu_ack = 2;
6301                 break;
6302         case 308571:
6303         case 337500:
6304         default:
6305                 freq_select = CDCLK_FREQ_337_308;
6306                 pcu_ack = 0;
6307                 break;
6308         case 617143:
6309         case 675000:
6310                 freq_select = CDCLK_FREQ_675_617;
6311                 pcu_ack = 3;
6312                 break;
6313         }
6314
6315         if (dev_priv->cdclk_pll.vco != 0 &&
6316             dev_priv->cdclk_pll.vco != vco)
6317                 skl_dpll0_disable(dev_priv);
6318
6319         if (dev_priv->cdclk_pll.vco != vco)
6320                 skl_dpll0_enable(dev_priv, vco);
6321
6322         I915_WRITE(CDCLK_CTL, freq_select | skl_cdclk_decimal(cdclk));
6323         POSTING_READ(CDCLK_CTL);
6324
6325         /* inform PCU of the change */
6326         mutex_lock(&dev_priv->rps.hw_lock);
6327         sandybridge_pcode_write(dev_priv, SKL_PCODE_CDCLK_CONTROL, pcu_ack);
6328         mutex_unlock(&dev_priv->rps.hw_lock);
6329
6330         intel_update_cdclk(dev);
6331 }
6332
6333 static void skl_sanitize_cdclk(struct drm_i915_private *dev_priv);
6334
6335 void skl_uninit_cdclk(struct drm_i915_private *dev_priv)
6336 {
6337         skl_set_cdclk(dev_priv, dev_priv->cdclk_pll.ref, 0);
6338 }
6339
6340 void skl_init_cdclk(struct drm_i915_private *dev_priv)
6341 {
6342         int cdclk, vco;
6343
6344         skl_sanitize_cdclk(dev_priv);
6345
6346         if (dev_priv->cdclk_freq != 0 && dev_priv->cdclk_pll.vco != 0) {
6347                 /*
6348                  * Use the current vco as our initial
6349                  * guess as to what the preferred vco is.
6350                  */
6351                 if (dev_priv->skl_preferred_vco_freq == 0)
6352                         skl_set_preferred_cdclk_vco(dev_priv,
6353                                                     dev_priv->cdclk_pll.vco);
6354                 return;
6355         }
6356
6357         vco = dev_priv->skl_preferred_vco_freq;
6358         if (vco == 0)
6359                 vco = 8100000;
6360         cdclk = skl_calc_cdclk(0, vco);
6361
6362         skl_set_cdclk(dev_priv, cdclk, vco);
6363 }
6364
6365 static void skl_sanitize_cdclk(struct drm_i915_private *dev_priv)
6366 {
6367         uint32_t cdctl, expected;
6368
6369         /*
6370          * check if the pre-os intialized the display
6371          * There is SWF18 scratchpad register defined which is set by the
6372          * pre-os which can be used by the OS drivers to check the status
6373          */
6374         if ((I915_READ(SWF_ILK(0x18)) & 0x00FFFFFF) == 0)
6375                 goto sanitize;
6376
6377         intel_update_cdclk(&dev_priv->drm);
6378         /* Is PLL enabled and locked ? */
6379         if (dev_priv->cdclk_pll.vco == 0 ||
6380             dev_priv->cdclk_freq == dev_priv->cdclk_pll.ref)
6381                 goto sanitize;
6382
6383         /* DPLL okay; verify the cdclock
6384          *
6385          * Noticed in some instances that the freq selection is correct but
6386          * decimal part is programmed wrong from BIOS where pre-os does not
6387          * enable display. Verify the same as well.
6388          */
6389         cdctl = I915_READ(CDCLK_CTL);
6390         expected = (cdctl & CDCLK_FREQ_SEL_MASK) |
6391                 skl_cdclk_decimal(dev_priv->cdclk_freq);
6392         if (cdctl == expected)
6393                 /* All well; nothing to sanitize */
6394                 return;
6395
6396 sanitize:
6397         DRM_DEBUG_KMS("Sanitizing cdclk programmed by pre-os\n");
6398
6399         /* force cdclk programming */
6400         dev_priv->cdclk_freq = 0;
6401         /* force full PLL disable + enable */
6402         dev_priv->cdclk_pll.vco = -1;
6403 }
6404
6405 /* Adjust CDclk dividers to allow high res or save power if possible */
6406 static void valleyview_set_cdclk(struct drm_device *dev, int cdclk)
6407 {
6408         struct drm_i915_private *dev_priv = to_i915(dev);
6409         u32 val, cmd;
6410
6411         WARN_ON(dev_priv->display.get_display_clock_speed(dev)
6412                                         != dev_priv->cdclk_freq);
6413
6414         if (cdclk >= 320000) /* jump to highest voltage for 400MHz too */
6415                 cmd = 2;
6416         else if (cdclk == 266667)
6417                 cmd = 1;
6418         else
6419                 cmd = 0;
6420
6421         mutex_lock(&dev_priv->rps.hw_lock);
6422         val = vlv_punit_read(dev_priv, PUNIT_REG_DSPFREQ);
6423         val &= ~DSPFREQGUAR_MASK;
6424         val |= (cmd << DSPFREQGUAR_SHIFT);
6425         vlv_punit_write(dev_priv, PUNIT_REG_DSPFREQ, val);
6426         if (wait_for((vlv_punit_read(dev_priv, PUNIT_REG_DSPFREQ) &
6427                       DSPFREQSTAT_MASK) == (cmd << DSPFREQSTAT_SHIFT),
6428                      50)) {
6429                 DRM_ERROR("timed out waiting for CDclk change\n");
6430         }
6431         mutex_unlock(&dev_priv->rps.hw_lock);
6432
6433         mutex_lock(&dev_priv->sb_lock);
6434
6435         if (cdclk == 400000) {
6436                 u32 divider;
6437
6438                 divider = DIV_ROUND_CLOSEST(dev_priv->hpll_freq << 1, cdclk) - 1;
6439
6440                 /* adjust cdclk divider */
6441                 val = vlv_cck_read(dev_priv, CCK_DISPLAY_CLOCK_CONTROL);
6442                 val &= ~CCK_FREQUENCY_VALUES;
6443                 val |= divider;
6444                 vlv_cck_write(dev_priv, CCK_DISPLAY_CLOCK_CONTROL, val);
6445
6446                 if (wait_for((vlv_cck_read(dev_priv, CCK_DISPLAY_CLOCK_CONTROL) &
6447                               CCK_FREQUENCY_STATUS) == (divider << CCK_FREQUENCY_STATUS_SHIFT),
6448                              50))
6449                         DRM_ERROR("timed out waiting for CDclk change\n");
6450         }
6451
6452         /* adjust self-refresh exit latency value */
6453         val = vlv_bunit_read(dev_priv, BUNIT_REG_BISOC);
6454         val &= ~0x7f;
6455
6456         /*
6457          * For high bandwidth configs, we set a higher latency in the bunit
6458          * so that the core display fetch happens in time to avoid underruns.
6459          */
6460         if (cdclk == 400000)
6461                 val |= 4500 / 250; /* 4.5 usec */
6462         else
6463                 val |= 3000 / 250; /* 3.0 usec */
6464         vlv_bunit_write(dev_priv, BUNIT_REG_BISOC, val);
6465
6466         mutex_unlock(&dev_priv->sb_lock);
6467
6468         intel_update_cdclk(dev);
6469 }
6470
6471 static void cherryview_set_cdclk(struct drm_device *dev, int cdclk)
6472 {
6473         struct drm_i915_private *dev_priv = to_i915(dev);
6474         u32 val, cmd;
6475
6476         WARN_ON(dev_priv->display.get_display_clock_speed(dev)
6477                                                 != dev_priv->cdclk_freq);
6478
6479         switch (cdclk) {
6480         case 333333:
6481         case 320000:
6482         case 266667:
6483         case 200000:
6484                 break;
6485         default:
6486                 MISSING_CASE(cdclk);
6487                 return;
6488         }
6489
6490         /*
6491          * Specs are full of misinformation, but testing on actual
6492          * hardware has shown that we just need to write the desired
6493          * CCK divider into the Punit register.
6494          */
6495         cmd = DIV_ROUND_CLOSEST(dev_priv->hpll_freq << 1, cdclk) - 1;
6496
6497         mutex_lock(&dev_priv->rps.hw_lock);
6498         val = vlv_punit_read(dev_priv, PUNIT_REG_DSPFREQ);
6499         val &= ~DSPFREQGUAR_MASK_CHV;
6500         val |= (cmd << DSPFREQGUAR_SHIFT_CHV);
6501         vlv_punit_write(dev_priv, PUNIT_REG_DSPFREQ, val);
6502         if (wait_for((vlv_punit_read(dev_priv, PUNIT_REG_DSPFREQ) &
6503                       DSPFREQSTAT_MASK_CHV) == (cmd << DSPFREQSTAT_SHIFT_CHV),
6504                      50)) {
6505                 DRM_ERROR("timed out waiting for CDclk change\n");
6506         }
6507         mutex_unlock(&dev_priv->rps.hw_lock);
6508
6509         intel_update_cdclk(dev);
6510 }
6511
6512 static int valleyview_calc_cdclk(struct drm_i915_private *dev_priv,
6513                                  int max_pixclk)
6514 {
6515         int freq_320 = (dev_priv->hpll_freq <<  1) % 320000 != 0 ? 333333 : 320000;
6516         int limit = IS_CHERRYVIEW(dev_priv) ? 95 : 90;
6517
6518         /*
6519          * Really only a few cases to deal with, as only 4 CDclks are supported:
6520          *   200MHz
6521          *   267MHz
6522          *   320/333MHz (depends on HPLL freq)
6523          *   400MHz (VLV only)
6524          * So we check to see whether we're above 90% (VLV) or 95% (CHV)
6525          * of the lower bin and adjust if needed.
6526          *
6527          * We seem to get an unstable or solid color picture at 200MHz.
6528          * Not sure what's wrong. For now use 200MHz only when all pipes
6529          * are off.
6530          */
6531         if (!IS_CHERRYVIEW(dev_priv) &&
6532             max_pixclk > freq_320*limit/100)
6533                 return 400000;
6534         else if (max_pixclk > 266667*limit/100)
6535                 return freq_320;
6536         else if (max_pixclk > 0)
6537                 return 266667;
6538         else
6539                 return 200000;
6540 }
6541
6542 static int bxt_calc_cdclk(int max_pixclk)
6543 {
6544         if (max_pixclk > 576000)
6545                 return 624000;
6546         else if (max_pixclk > 384000)
6547                 return 576000;
6548         else if (max_pixclk > 288000)
6549                 return 384000;
6550         else if (max_pixclk > 144000)
6551                 return 288000;
6552         else
6553                 return 144000;
6554 }
6555
6556 /* Compute the max pixel clock for new configuration. */
6557 static int intel_mode_max_pixclk(struct drm_device *dev,
6558                                  struct drm_atomic_state *state)
6559 {
6560         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
6561         struct drm_i915_private *dev_priv = to_i915(dev);
6562         struct drm_crtc *crtc;
6563         struct drm_crtc_state *crtc_state;
6564         unsigned max_pixclk = 0, i;
6565         enum pipe pipe;
6566
6567         memcpy(intel_state->min_pixclk, dev_priv->min_pixclk,
6568                sizeof(intel_state->min_pixclk));
6569
6570         for_each_crtc_in_state(state, crtc, crtc_state, i) {
6571                 int pixclk = 0;
6572
6573                 if (crtc_state->enable)
6574                         pixclk = crtc_state->adjusted_mode.crtc_clock;
6575
6576                 intel_state->min_pixclk[i] = pixclk;
6577         }
6578
6579         for_each_pipe(dev_priv, pipe)
6580                 max_pixclk = max(intel_state->min_pixclk[pipe], max_pixclk);
6581
6582         return max_pixclk;
6583 }
6584
6585 static int valleyview_modeset_calc_cdclk(struct drm_atomic_state *state)
6586 {
6587         struct drm_device *dev = state->dev;
6588         struct drm_i915_private *dev_priv = to_i915(dev);
6589         int max_pixclk = intel_mode_max_pixclk(dev, state);
6590         struct intel_atomic_state *intel_state =
6591                 to_intel_atomic_state(state);
6592
6593         intel_state->cdclk = intel_state->dev_cdclk =
6594                 valleyview_calc_cdclk(dev_priv, max_pixclk);
6595
6596         if (!intel_state->active_crtcs)
6597                 intel_state->dev_cdclk = valleyview_calc_cdclk(dev_priv, 0);
6598
6599         return 0;
6600 }
6601
6602 static int bxt_modeset_calc_cdclk(struct drm_atomic_state *state)
6603 {
6604         int max_pixclk = ilk_max_pixel_rate(state);
6605         struct intel_atomic_state *intel_state =
6606                 to_intel_atomic_state(state);
6607
6608         intel_state->cdclk = intel_state->dev_cdclk =
6609                 bxt_calc_cdclk(max_pixclk);
6610
6611         if (!intel_state->active_crtcs)
6612                 intel_state->dev_cdclk = bxt_calc_cdclk(0);
6613
6614         return 0;
6615 }
6616
6617 static void vlv_program_pfi_credits(struct drm_i915_private *dev_priv)
6618 {
6619         unsigned int credits, default_credits;
6620
6621         if (IS_CHERRYVIEW(dev_priv))
6622                 default_credits = PFI_CREDIT(12);
6623         else
6624                 default_credits = PFI_CREDIT(8);
6625
6626         if (dev_priv->cdclk_freq >= dev_priv->czclk_freq) {
6627                 /* CHV suggested value is 31 or 63 */
6628                 if (IS_CHERRYVIEW(dev_priv))
6629                         credits = PFI_CREDIT_63;
6630                 else
6631                         credits = PFI_CREDIT(15);
6632         } else {
6633                 credits = default_credits;
6634         }
6635
6636         /*
6637          * WA - write default credits before re-programming
6638          * FIXME: should we also set the resend bit here?
6639          */
6640         I915_WRITE(GCI_CONTROL, VGA_FAST_MODE_DISABLE |
6641                    default_credits);
6642
6643         I915_WRITE(GCI_CONTROL, VGA_FAST_MODE_DISABLE |
6644                    credits | PFI_CREDIT_RESEND);
6645
6646         /*
6647          * FIXME is this guaranteed to clear
6648          * immediately or should we poll for it?
6649          */
6650         WARN_ON(I915_READ(GCI_CONTROL) & PFI_CREDIT_RESEND);
6651 }
6652
6653 static void valleyview_modeset_commit_cdclk(struct drm_atomic_state *old_state)
6654 {
6655         struct drm_device *dev = old_state->dev;
6656         struct drm_i915_private *dev_priv = to_i915(dev);
6657         struct intel_atomic_state *old_intel_state =
6658                 to_intel_atomic_state(old_state);
6659         unsigned req_cdclk = old_intel_state->dev_cdclk;
6660
6661         /*
6662          * FIXME: We can end up here with all power domains off, yet
6663          * with a CDCLK frequency other than the minimum. To account
6664          * for this take the PIPE-A power domain, which covers the HW
6665          * blocks needed for the following programming. This can be
6666          * removed once it's guaranteed that we get here either with
6667          * the minimum CDCLK set, or the required power domains
6668          * enabled.
6669          */
6670         intel_display_power_get(dev_priv, POWER_DOMAIN_PIPE_A);
6671
6672         if (IS_CHERRYVIEW(dev))
6673                 cherryview_set_cdclk(dev, req_cdclk);
6674         else
6675                 valleyview_set_cdclk(dev, req_cdclk);
6676
6677         vlv_program_pfi_credits(dev_priv);
6678
6679         intel_display_power_put(dev_priv, POWER_DOMAIN_PIPE_A);
6680 }
6681
6682 static void valleyview_crtc_enable(struct intel_crtc_state *pipe_config,
6683                                    struct drm_atomic_state *old_state)
6684 {
6685         struct drm_crtc *crtc = pipe_config->base.crtc;
6686         struct drm_device *dev = crtc->dev;
6687         struct drm_i915_private *dev_priv = to_i915(dev);
6688         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
6689         int pipe = intel_crtc->pipe;
6690
6691         if (WARN_ON(intel_crtc->active))
6692                 return;
6693
6694         if (intel_crtc_has_dp_encoder(intel_crtc->config))
6695                 intel_dp_set_m_n(intel_crtc, M1_N1);
6696
6697         intel_set_pipe_timings(intel_crtc);
6698         intel_set_pipe_src_size(intel_crtc);
6699
6700         if (IS_CHERRYVIEW(dev) && pipe == PIPE_B) {
6701                 struct drm_i915_private *dev_priv = to_i915(dev);
6702
6703                 I915_WRITE(CHV_BLEND(pipe), CHV_BLEND_LEGACY);
6704                 I915_WRITE(CHV_CANVAS(pipe), 0);
6705         }
6706
6707         i9xx_set_pipeconf(intel_crtc);
6708
6709         intel_crtc->active = true;
6710
6711         intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
6712
6713         intel_encoders_pre_pll_enable(crtc, pipe_config, old_state);
6714
6715         if (IS_CHERRYVIEW(dev)) {
6716                 chv_prepare_pll(intel_crtc, intel_crtc->config);
6717                 chv_enable_pll(intel_crtc, intel_crtc->config);
6718         } else {
6719                 vlv_prepare_pll(intel_crtc, intel_crtc->config);
6720                 vlv_enable_pll(intel_crtc, intel_crtc->config);
6721         }
6722
6723         intel_encoders_pre_enable(crtc, pipe_config, old_state);
6724
6725         i9xx_pfit_enable(intel_crtc);
6726
6727         intel_color_load_luts(&pipe_config->base);
6728
6729         intel_update_watermarks(crtc);
6730         intel_enable_pipe(intel_crtc);
6731
6732         assert_vblank_disabled(crtc);
6733         drm_crtc_vblank_on(crtc);
6734
6735         intel_encoders_enable(crtc, pipe_config, old_state);
6736 }
6737
6738 static void i9xx_set_pll_dividers(struct intel_crtc *crtc)
6739 {
6740         struct drm_device *dev = crtc->base.dev;
6741         struct drm_i915_private *dev_priv = to_i915(dev);
6742
6743         I915_WRITE(FP0(crtc->pipe), crtc->config->dpll_hw_state.fp0);
6744         I915_WRITE(FP1(crtc->pipe), crtc->config->dpll_hw_state.fp1);
6745 }
6746
6747 static void i9xx_crtc_enable(struct intel_crtc_state *pipe_config,
6748                              struct drm_atomic_state *old_state)
6749 {
6750         struct drm_crtc *crtc = pipe_config->base.crtc;
6751         struct drm_device *dev = crtc->dev;
6752         struct drm_i915_private *dev_priv = to_i915(dev);
6753         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
6754         enum pipe pipe = intel_crtc->pipe;
6755
6756         if (WARN_ON(intel_crtc->active))
6757                 return;
6758
6759         i9xx_set_pll_dividers(intel_crtc);
6760
6761         if (intel_crtc_has_dp_encoder(intel_crtc->config))
6762                 intel_dp_set_m_n(intel_crtc, M1_N1);
6763
6764         intel_set_pipe_timings(intel_crtc);
6765         intel_set_pipe_src_size(intel_crtc);
6766
6767         i9xx_set_pipeconf(intel_crtc);
6768
6769         intel_crtc->active = true;
6770
6771         if (!IS_GEN2(dev))
6772                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
6773
6774         intel_encoders_pre_enable(crtc, pipe_config, old_state);
6775
6776         i9xx_enable_pll(intel_crtc);
6777
6778         i9xx_pfit_enable(intel_crtc);
6779
6780         intel_color_load_luts(&pipe_config->base);
6781
6782         intel_update_watermarks(crtc);
6783         intel_enable_pipe(intel_crtc);
6784
6785         assert_vblank_disabled(crtc);
6786         drm_crtc_vblank_on(crtc);
6787
6788         intel_encoders_enable(crtc, pipe_config, old_state);
6789 }
6790
6791 static void i9xx_pfit_disable(struct intel_crtc *crtc)
6792 {
6793         struct drm_device *dev = crtc->base.dev;
6794         struct drm_i915_private *dev_priv = to_i915(dev);
6795
6796         if (!crtc->config->gmch_pfit.control)
6797                 return;
6798
6799         assert_pipe_disabled(dev_priv, crtc->pipe);
6800
6801         DRM_DEBUG_DRIVER("disabling pfit, current: 0x%08x\n",
6802                          I915_READ(PFIT_CONTROL));
6803         I915_WRITE(PFIT_CONTROL, 0);
6804 }
6805
6806 static void i9xx_crtc_disable(struct intel_crtc_state *old_crtc_state,
6807                               struct drm_atomic_state *old_state)
6808 {
6809         struct drm_crtc *crtc = old_crtc_state->base.crtc;
6810         struct drm_device *dev = crtc->dev;
6811         struct drm_i915_private *dev_priv = to_i915(dev);
6812         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
6813         int pipe = intel_crtc->pipe;
6814
6815         /*
6816          * On gen2 planes are double buffered but the pipe isn't, so we must
6817          * wait for planes to fully turn off before disabling the pipe.
6818          */
6819         if (IS_GEN2(dev))
6820                 intel_wait_for_vblank(dev, pipe);
6821
6822         intel_encoders_disable(crtc, old_crtc_state, old_state);
6823
6824         drm_crtc_vblank_off(crtc);
6825         assert_vblank_disabled(crtc);
6826
6827         intel_disable_pipe(intel_crtc);
6828
6829         i9xx_pfit_disable(intel_crtc);
6830
6831         intel_encoders_post_disable(crtc, old_crtc_state, old_state);
6832
6833         if (!intel_crtc_has_type(intel_crtc->config, INTEL_OUTPUT_DSI)) {
6834                 if (IS_CHERRYVIEW(dev))
6835                         chv_disable_pll(dev_priv, pipe);
6836                 else if (IS_VALLEYVIEW(dev))
6837                         vlv_disable_pll(dev_priv, pipe);
6838                 else
6839                         i9xx_disable_pll(intel_crtc);
6840         }
6841
6842         intel_encoders_post_pll_disable(crtc, old_crtc_state, old_state);
6843
6844         if (!IS_GEN2(dev))
6845                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, false);
6846 }
6847
6848 static void intel_crtc_disable_noatomic(struct drm_crtc *crtc)
6849 {
6850         struct intel_encoder *encoder;
6851         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
6852         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
6853         enum intel_display_power_domain domain;
6854         unsigned long domains;
6855         struct drm_atomic_state *state;
6856         struct intel_crtc_state *crtc_state;
6857         int ret;
6858
6859         if (!intel_crtc->active)
6860                 return;
6861
6862         if (to_intel_plane_state(crtc->primary->state)->base.visible) {
6863                 WARN_ON(intel_crtc->flip_work);
6864
6865                 intel_pre_disable_primary_noatomic(crtc);
6866
6867                 intel_crtc_disable_planes(crtc, 1 << drm_plane_index(crtc->primary));
6868                 to_intel_plane_state(crtc->primary->state)->base.visible = false;
6869         }
6870
6871         state = drm_atomic_state_alloc(crtc->dev);
6872         state->acquire_ctx = crtc->dev->mode_config.acquire_ctx;
6873
6874         /* Everything's already locked, -EDEADLK can't happen. */
6875         crtc_state = intel_atomic_get_crtc_state(state, intel_crtc);
6876         ret = drm_atomic_add_affected_connectors(state, crtc);
6877
6878         WARN_ON(IS_ERR(crtc_state) || ret);
6879
6880         dev_priv->display.crtc_disable(crtc_state, state);
6881
6882         drm_atomic_state_free(state);
6883
6884         DRM_DEBUG_KMS("[CRTC:%d:%s] hw state adjusted, was enabled, now disabled\n",
6885                       crtc->base.id, crtc->name);
6886
6887         WARN_ON(drm_atomic_set_mode_for_crtc(crtc->state, NULL) < 0);
6888         crtc->state->active = false;
6889         intel_crtc->active = false;
6890         crtc->enabled = false;
6891         crtc->state->connector_mask = 0;
6892         crtc->state->encoder_mask = 0;
6893
6894         for_each_encoder_on_crtc(crtc->dev, crtc, encoder)
6895                 encoder->base.crtc = NULL;
6896
6897         intel_fbc_disable(intel_crtc);
6898         intel_update_watermarks(crtc);
6899         intel_disable_shared_dpll(intel_crtc);
6900
6901         domains = intel_crtc->enabled_power_domains;
6902         for_each_power_domain(domain, domains)
6903                 intel_display_power_put(dev_priv, domain);
6904         intel_crtc->enabled_power_domains = 0;
6905
6906         dev_priv->active_crtcs &= ~(1 << intel_crtc->pipe);
6907         dev_priv->min_pixclk[intel_crtc->pipe] = 0;
6908 }
6909
6910 /*
6911  * turn all crtc's off, but do not adjust state
6912  * This has to be paired with a call to intel_modeset_setup_hw_state.
6913  */
6914 int intel_display_suspend(struct drm_device *dev)
6915 {
6916         struct drm_i915_private *dev_priv = to_i915(dev);
6917         struct drm_atomic_state *state;
6918         int ret;
6919
6920         state = drm_atomic_helper_suspend(dev);
6921         ret = PTR_ERR_OR_ZERO(state);
6922         if (ret)
6923                 DRM_ERROR("Suspending crtc's failed with %i\n", ret);
6924         else
6925                 dev_priv->modeset_restore_state = state;
6926         return ret;
6927 }
6928
6929 void intel_encoder_destroy(struct drm_encoder *encoder)
6930 {
6931         struct intel_encoder *intel_encoder = to_intel_encoder(encoder);
6932
6933         drm_encoder_cleanup(encoder);
6934         kfree(intel_encoder);
6935 }
6936
6937 /* Cross check the actual hw state with our own modeset state tracking (and it's
6938  * internal consistency). */
6939 static void intel_connector_verify_state(struct intel_connector *connector)
6940 {
6941         struct drm_crtc *crtc = connector->base.state->crtc;
6942
6943         DRM_DEBUG_KMS("[CONNECTOR:%d:%s]\n",
6944                       connector->base.base.id,
6945                       connector->base.name);
6946
6947         if (connector->get_hw_state(connector)) {
6948                 struct intel_encoder *encoder = connector->encoder;
6949                 struct drm_connector_state *conn_state = connector->base.state;
6950
6951                 I915_STATE_WARN(!crtc,
6952                          "connector enabled without attached crtc\n");
6953
6954                 if (!crtc)
6955                         return;
6956
6957                 I915_STATE_WARN(!crtc->state->active,
6958                       "connector is active, but attached crtc isn't\n");
6959
6960                 if (!encoder || encoder->type == INTEL_OUTPUT_DP_MST)
6961                         return;
6962
6963                 I915_STATE_WARN(conn_state->best_encoder != &encoder->base,
6964                         "atomic encoder doesn't match attached encoder\n");
6965
6966                 I915_STATE_WARN(conn_state->crtc != encoder->base.crtc,
6967                         "attached encoder crtc differs from connector crtc\n");
6968         } else {
6969                 I915_STATE_WARN(crtc && crtc->state->active,
6970                         "attached crtc is active, but connector isn't\n");
6971                 I915_STATE_WARN(!crtc && connector->base.state->best_encoder,
6972                         "best encoder set without crtc!\n");
6973         }
6974 }
6975
6976 int intel_connector_init(struct intel_connector *connector)
6977 {
6978         drm_atomic_helper_connector_reset(&connector->base);
6979
6980         if (!connector->base.state)
6981                 return -ENOMEM;
6982
6983         return 0;
6984 }
6985
6986 struct intel_connector *intel_connector_alloc(void)
6987 {
6988         struct intel_connector *connector;
6989
6990         connector = kzalloc(sizeof *connector, GFP_KERNEL);
6991         if (!connector)
6992                 return NULL;
6993
6994         if (intel_connector_init(connector) < 0) {
6995                 kfree(connector);
6996                 return NULL;
6997         }
6998
6999         return connector;
7000 }
7001
7002 /* Simple connector->get_hw_state implementation for encoders that support only
7003  * one connector and no cloning and hence the encoder state determines the state
7004  * of the connector. */
7005 bool intel_connector_get_hw_state(struct intel_connector *connector)
7006 {
7007         enum pipe pipe = 0;
7008         struct intel_encoder *encoder = connector->encoder;
7009
7010         return encoder->get_hw_state(encoder, &pipe);
7011 }
7012
7013 static int pipe_required_fdi_lanes(struct intel_crtc_state *crtc_state)
7014 {
7015         if (crtc_state->base.enable && crtc_state->has_pch_encoder)
7016                 return crtc_state->fdi_lanes;
7017
7018         return 0;
7019 }
7020
7021 static int ironlake_check_fdi_lanes(struct drm_device *dev, enum pipe pipe,
7022                                      struct intel_crtc_state *pipe_config)
7023 {
7024         struct drm_atomic_state *state = pipe_config->base.state;
7025         struct intel_crtc *other_crtc;
7026         struct intel_crtc_state *other_crtc_state;
7027
7028         DRM_DEBUG_KMS("checking fdi config on pipe %c, lanes %i\n",
7029                       pipe_name(pipe), pipe_config->fdi_lanes);
7030         if (pipe_config->fdi_lanes > 4) {
7031                 DRM_DEBUG_KMS("invalid fdi lane config on pipe %c: %i lanes\n",
7032                               pipe_name(pipe), pipe_config->fdi_lanes);
7033                 return -EINVAL;
7034         }
7035
7036         if (IS_HASWELL(dev) || IS_BROADWELL(dev)) {
7037                 if (pipe_config->fdi_lanes > 2) {
7038                         DRM_DEBUG_KMS("only 2 lanes on haswell, required: %i lanes\n",
7039                                       pipe_config->fdi_lanes);
7040                         return -EINVAL;
7041                 } else {
7042                         return 0;
7043                 }
7044         }
7045
7046         if (INTEL_INFO(dev)->num_pipes == 2)
7047                 return 0;
7048
7049         /* Ivybridge 3 pipe is really complicated */
7050         switch (pipe) {
7051         case PIPE_A:
7052                 return 0;
7053         case PIPE_B:
7054                 if (pipe_config->fdi_lanes <= 2)
7055                         return 0;
7056
7057                 other_crtc = to_intel_crtc(intel_get_crtc_for_pipe(dev, PIPE_C));
7058                 other_crtc_state =
7059                         intel_atomic_get_crtc_state(state, other_crtc);
7060                 if (IS_ERR(other_crtc_state))
7061                         return PTR_ERR(other_crtc_state);
7062
7063                 if (pipe_required_fdi_lanes(other_crtc_state) > 0) {
7064                         DRM_DEBUG_KMS("invalid shared fdi lane config on pipe %c: %i lanes\n",
7065                                       pipe_name(pipe), pipe_config->fdi_lanes);
7066                         return -EINVAL;
7067                 }
7068                 return 0;
7069         case PIPE_C:
7070                 if (pipe_config->fdi_lanes > 2) {
7071                         DRM_DEBUG_KMS("only 2 lanes on pipe %c: required %i lanes\n",
7072                                       pipe_name(pipe), pipe_config->fdi_lanes);
7073                         return -EINVAL;
7074                 }
7075
7076                 other_crtc = to_intel_crtc(intel_get_crtc_for_pipe(dev, PIPE_B));
7077                 other_crtc_state =
7078                         intel_atomic_get_crtc_state(state, other_crtc);
7079                 if (IS_ERR(other_crtc_state))
7080                         return PTR_ERR(other_crtc_state);
7081
7082                 if (pipe_required_fdi_lanes(other_crtc_state) > 2) {
7083                         DRM_DEBUG_KMS("fdi link B uses too many lanes to enable link C\n");
7084                         return -EINVAL;
7085                 }
7086                 return 0;
7087         default:
7088                 BUG();
7089         }
7090 }
7091
7092 #define RETRY 1
7093 static int ironlake_fdi_compute_config(struct intel_crtc *intel_crtc,
7094                                        struct intel_crtc_state *pipe_config)
7095 {
7096         struct drm_device *dev = intel_crtc->base.dev;
7097         const struct drm_display_mode *adjusted_mode = &pipe_config->base.adjusted_mode;
7098         int lane, link_bw, fdi_dotclock, ret;
7099         bool needs_recompute = false;
7100
7101 retry:
7102         /* FDI is a binary signal running at ~2.7GHz, encoding
7103          * each output octet as 10 bits. The actual frequency
7104          * is stored as a divider into a 100MHz clock, and the
7105          * mode pixel clock is stored in units of 1KHz.
7106          * Hence the bw of each lane in terms of the mode signal
7107          * is:
7108          */
7109         link_bw = intel_fdi_link_freq(to_i915(dev), pipe_config);
7110
7111         fdi_dotclock = adjusted_mode->crtc_clock;
7112
7113         lane = ironlake_get_lanes_required(fdi_dotclock, link_bw,
7114                                            pipe_config->pipe_bpp);
7115
7116         pipe_config->fdi_lanes = lane;
7117
7118         intel_link_compute_m_n(pipe_config->pipe_bpp, lane, fdi_dotclock,
7119                                link_bw, &pipe_config->fdi_m_n);
7120
7121         ret = ironlake_check_fdi_lanes(dev, intel_crtc->pipe, pipe_config);
7122         if (ret == -EINVAL && pipe_config->pipe_bpp > 6*3) {
7123                 pipe_config->pipe_bpp -= 2*3;
7124                 DRM_DEBUG_KMS("fdi link bw constraint, reducing pipe bpp to %i\n",
7125                               pipe_config->pipe_bpp);
7126                 needs_recompute = true;
7127                 pipe_config->bw_constrained = true;
7128
7129                 goto retry;
7130         }
7131
7132         if (needs_recompute)
7133                 return RETRY;
7134
7135         return ret;
7136 }
7137
7138 static bool pipe_config_supports_ips(struct drm_i915_private *dev_priv,
7139                                      struct intel_crtc_state *pipe_config)
7140 {
7141         if (pipe_config->pipe_bpp > 24)
7142                 return false;
7143
7144         /* HSW can handle pixel rate up to cdclk? */
7145         if (IS_HASWELL(dev_priv))
7146                 return true;
7147
7148         /*
7149          * We compare against max which means we must take
7150          * the increased cdclk requirement into account when
7151          * calculating the new cdclk.
7152          *
7153          * Should measure whether using a lower cdclk w/o IPS
7154          */
7155         return ilk_pipe_pixel_rate(pipe_config) <=
7156                 dev_priv->max_cdclk_freq * 95 / 100;
7157 }
7158
7159 static void hsw_compute_ips_config(struct intel_crtc *crtc,
7160                                    struct intel_crtc_state *pipe_config)
7161 {
7162         struct drm_device *dev = crtc->base.dev;
7163         struct drm_i915_private *dev_priv = to_i915(dev);
7164
7165         pipe_config->ips_enabled = i915.enable_ips &&
7166                 hsw_crtc_supports_ips(crtc) &&
7167                 pipe_config_supports_ips(dev_priv, pipe_config);
7168 }
7169
7170 static bool intel_crtc_supports_double_wide(const struct intel_crtc *crtc)
7171 {
7172         const struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
7173
7174         /* GDG double wide on either pipe, otherwise pipe A only */
7175         return INTEL_INFO(dev_priv)->gen < 4 &&
7176                 (crtc->pipe == PIPE_A || IS_I915G(dev_priv));
7177 }
7178
7179 static int intel_crtc_compute_config(struct intel_crtc *crtc,
7180                                      struct intel_crtc_state *pipe_config)
7181 {
7182         struct drm_device *dev = crtc->base.dev;
7183         struct drm_i915_private *dev_priv = to_i915(dev);
7184         const struct drm_display_mode *adjusted_mode = &pipe_config->base.adjusted_mode;
7185         int clock_limit = dev_priv->max_dotclk_freq;
7186
7187         if (INTEL_INFO(dev)->gen < 4) {
7188                 clock_limit = dev_priv->max_cdclk_freq * 9 / 10;
7189
7190                 /*
7191                  * Enable double wide mode when the dot clock
7192                  * is > 90% of the (display) core speed.
7193                  */
7194                 if (intel_crtc_supports_double_wide(crtc) &&
7195                     adjusted_mode->crtc_clock > clock_limit) {
7196                         clock_limit = dev_priv->max_dotclk_freq;
7197                         pipe_config->double_wide = true;
7198                 }
7199         }
7200
7201         if (adjusted_mode->crtc_clock > clock_limit) {
7202                 DRM_DEBUG_KMS("requested pixel clock (%d kHz) too high (max: %d kHz, double wide: %s)\n",
7203                               adjusted_mode->crtc_clock, clock_limit,
7204                               yesno(pipe_config->double_wide));
7205                 return -EINVAL;
7206         }
7207
7208         /*
7209          * Pipe horizontal size must be even in:
7210          * - DVO ganged mode
7211          * - LVDS dual channel mode
7212          * - Double wide pipe
7213          */
7214         if ((intel_crtc_has_type(pipe_config, INTEL_OUTPUT_LVDS) &&
7215              intel_is_dual_link_lvds(dev)) || pipe_config->double_wide)
7216                 pipe_config->pipe_src_w &= ~1;
7217
7218         /* Cantiga+ cannot handle modes with a hsync front porch of 0.
7219          * WaPruneModeWithIncorrectHsyncOffset:ctg,elk,ilk,snb,ivb,vlv,hsw.
7220          */
7221         if ((INTEL_INFO(dev)->gen > 4 || IS_G4X(dev)) &&
7222                 adjusted_mode->crtc_hsync_start == adjusted_mode->crtc_hdisplay)
7223                 return -EINVAL;
7224
7225         if (HAS_IPS(dev_priv))
7226                 hsw_compute_ips_config(crtc, pipe_config);
7227
7228         if (pipe_config->has_pch_encoder)
7229                 return ironlake_fdi_compute_config(crtc, pipe_config);
7230
7231         return 0;
7232 }
7233
7234 static int skylake_get_display_clock_speed(struct drm_device *dev)
7235 {
7236         struct drm_i915_private *dev_priv = to_i915(dev);
7237         uint32_t cdctl;
7238
7239         skl_dpll0_update(dev_priv);
7240
7241         if (dev_priv->cdclk_pll.vco == 0)
7242                 return dev_priv->cdclk_pll.ref;
7243
7244         cdctl = I915_READ(CDCLK_CTL);
7245
7246         if (dev_priv->cdclk_pll.vco == 8640000) {
7247                 switch (cdctl & CDCLK_FREQ_SEL_MASK) {
7248                 case CDCLK_FREQ_450_432:
7249                         return 432000;
7250                 case CDCLK_FREQ_337_308:
7251                         return 308571;
7252                 case CDCLK_FREQ_540:
7253                         return 540000;
7254                 case CDCLK_FREQ_675_617:
7255                         return 617143;
7256                 default:
7257                         MISSING_CASE(cdctl & CDCLK_FREQ_SEL_MASK);
7258                 }
7259         } else {
7260                 switch (cdctl & CDCLK_FREQ_SEL_MASK) {
7261                 case CDCLK_FREQ_450_432:
7262                         return 450000;
7263                 case CDCLK_FREQ_337_308:
7264                         return 337500;
7265                 case CDCLK_FREQ_540:
7266                         return 540000;
7267                 case CDCLK_FREQ_675_617:
7268                         return 675000;
7269                 default:
7270                         MISSING_CASE(cdctl & CDCLK_FREQ_SEL_MASK);
7271                 }
7272         }
7273
7274         return dev_priv->cdclk_pll.ref;
7275 }
7276
7277 static void bxt_de_pll_update(struct drm_i915_private *dev_priv)
7278 {
7279         u32 val;
7280
7281         dev_priv->cdclk_pll.ref = 19200;
7282         dev_priv->cdclk_pll.vco = 0;
7283
7284         val = I915_READ(BXT_DE_PLL_ENABLE);
7285         if ((val & BXT_DE_PLL_PLL_ENABLE) == 0)
7286                 return;
7287
7288         if (WARN_ON((val & BXT_DE_PLL_LOCK) == 0))
7289                 return;
7290
7291         val = I915_READ(BXT_DE_PLL_CTL);
7292         dev_priv->cdclk_pll.vco = (val & BXT_DE_PLL_RATIO_MASK) *
7293                 dev_priv->cdclk_pll.ref;
7294 }
7295
7296 static int broxton_get_display_clock_speed(struct drm_device *dev)
7297 {
7298         struct drm_i915_private *dev_priv = to_i915(dev);
7299         u32 divider;
7300         int div, vco;
7301
7302         bxt_de_pll_update(dev_priv);
7303
7304         vco = dev_priv->cdclk_pll.vco;
7305         if (vco == 0)
7306                 return dev_priv->cdclk_pll.ref;
7307
7308         divider = I915_READ(CDCLK_CTL) & BXT_CDCLK_CD2X_DIV_SEL_MASK;
7309
7310         switch (divider) {
7311         case BXT_CDCLK_CD2X_DIV_SEL_1:
7312                 div = 2;
7313                 break;
7314         case BXT_CDCLK_CD2X_DIV_SEL_1_5:
7315                 div = 3;
7316                 break;
7317         case BXT_CDCLK_CD2X_DIV_SEL_2:
7318                 div = 4;
7319                 break;
7320         case BXT_CDCLK_CD2X_DIV_SEL_4:
7321                 div = 8;
7322                 break;
7323         default:
7324                 MISSING_CASE(divider);
7325                 return dev_priv->cdclk_pll.ref;
7326         }
7327
7328         return DIV_ROUND_CLOSEST(vco, div);
7329 }
7330
7331 static int broadwell_get_display_clock_speed(struct drm_device *dev)
7332 {
7333         struct drm_i915_private *dev_priv = to_i915(dev);
7334         uint32_t lcpll = I915_READ(LCPLL_CTL);
7335         uint32_t freq = lcpll & LCPLL_CLK_FREQ_MASK;
7336
7337         if (lcpll & LCPLL_CD_SOURCE_FCLK)
7338                 return 800000;
7339         else if (I915_READ(FUSE_STRAP) & HSW_CDCLK_LIMIT)
7340                 return 450000;
7341         else if (freq == LCPLL_CLK_FREQ_450)
7342                 return 450000;
7343         else if (freq == LCPLL_CLK_FREQ_54O_BDW)
7344                 return 540000;
7345         else if (freq == LCPLL_CLK_FREQ_337_5_BDW)
7346                 return 337500;
7347         else
7348                 return 675000;
7349 }
7350
7351 static int haswell_get_display_clock_speed(struct drm_device *dev)
7352 {
7353         struct drm_i915_private *dev_priv = to_i915(dev);
7354         uint32_t lcpll = I915_READ(LCPLL_CTL);
7355         uint32_t freq = lcpll & LCPLL_CLK_FREQ_MASK;
7356
7357         if (lcpll & LCPLL_CD_SOURCE_FCLK)
7358                 return 800000;
7359         else if (I915_READ(FUSE_STRAP) & HSW_CDCLK_LIMIT)
7360                 return 450000;
7361         else if (freq == LCPLL_CLK_FREQ_450)
7362                 return 450000;
7363         else if (IS_HSW_ULT(dev_priv))
7364                 return 337500;
7365         else
7366                 return 540000;
7367 }
7368
7369 static int valleyview_get_display_clock_speed(struct drm_device *dev)
7370 {
7371         return vlv_get_cck_clock_hpll(to_i915(dev), "cdclk",
7372                                       CCK_DISPLAY_CLOCK_CONTROL);
7373 }
7374
7375 static int ilk_get_display_clock_speed(struct drm_device *dev)
7376 {
7377         return 450000;
7378 }
7379
7380 static int i945_get_display_clock_speed(struct drm_device *dev)
7381 {
7382         return 400000;
7383 }
7384
7385 static int i915_get_display_clock_speed(struct drm_device *dev)
7386 {
7387         return 333333;
7388 }
7389
7390 static int i9xx_misc_get_display_clock_speed(struct drm_device *dev)
7391 {
7392         return 200000;
7393 }
7394
7395 static int pnv_get_display_clock_speed(struct drm_device *dev)
7396 {
7397         struct pci_dev *pdev = dev->pdev;
7398         u16 gcfgc = 0;
7399
7400         pci_read_config_word(pdev, GCFGC, &gcfgc);
7401
7402         switch (gcfgc & GC_DISPLAY_CLOCK_MASK) {
7403         case GC_DISPLAY_CLOCK_267_MHZ_PNV:
7404                 return 266667;
7405         case GC_DISPLAY_CLOCK_333_MHZ_PNV:
7406                 return 333333;
7407         case GC_DISPLAY_CLOCK_444_MHZ_PNV:
7408                 return 444444;
7409         case GC_DISPLAY_CLOCK_200_MHZ_PNV:
7410                 return 200000;
7411         default:
7412                 DRM_ERROR("Unknown pnv display core clock 0x%04x\n", gcfgc);
7413         case GC_DISPLAY_CLOCK_133_MHZ_PNV:
7414                 return 133333;
7415         case GC_DISPLAY_CLOCK_167_MHZ_PNV:
7416                 return 166667;
7417         }
7418 }
7419
7420 static int i915gm_get_display_clock_speed(struct drm_device *dev)
7421 {
7422         struct pci_dev *pdev = dev->pdev;
7423         u16 gcfgc = 0;
7424
7425         pci_read_config_word(pdev, GCFGC, &gcfgc);
7426
7427         if (gcfgc & GC_LOW_FREQUENCY_ENABLE)
7428                 return 133333;
7429         else {
7430                 switch (gcfgc & GC_DISPLAY_CLOCK_MASK) {
7431                 case GC_DISPLAY_CLOCK_333_MHZ:
7432                         return 333333;
7433                 default:
7434                 case GC_DISPLAY_CLOCK_190_200_MHZ:
7435                         return 190000;
7436                 }
7437         }
7438 }
7439
7440 static int i865_get_display_clock_speed(struct drm_device *dev)
7441 {
7442         return 266667;
7443 }
7444
7445 static int i85x_get_display_clock_speed(struct drm_device *dev)
7446 {
7447         struct pci_dev *pdev = dev->pdev;
7448         u16 hpllcc = 0;
7449
7450         /*
7451          * 852GM/852GMV only supports 133 MHz and the HPLLCC
7452          * encoding is different :(
7453          * FIXME is this the right way to detect 852GM/852GMV?
7454          */
7455         if (pdev->revision == 0x1)
7456                 return 133333;
7457
7458         pci_bus_read_config_word(pdev->bus,
7459                                  PCI_DEVFN(0, 3), HPLLCC, &hpllcc);
7460
7461         /* Assume that the hardware is in the high speed state.  This
7462          * should be the default.
7463          */
7464         switch (hpllcc & GC_CLOCK_CONTROL_MASK) {
7465         case GC_CLOCK_133_200:
7466         case GC_CLOCK_133_200_2:
7467         case GC_CLOCK_100_200:
7468                 return 200000;
7469         case GC_CLOCK_166_250:
7470                 return 250000;
7471         case GC_CLOCK_100_133:
7472                 return 133333;
7473         case GC_CLOCK_133_266:
7474         case GC_CLOCK_133_266_2:
7475         case GC_CLOCK_166_266:
7476                 return 266667;
7477         }
7478
7479         /* Shouldn't happen */
7480         return 0;
7481 }
7482
7483 static int i830_get_display_clock_speed(struct drm_device *dev)
7484 {
7485         return 133333;
7486 }
7487
7488 static unsigned int intel_hpll_vco(struct drm_device *dev)
7489 {
7490         struct drm_i915_private *dev_priv = to_i915(dev);
7491         static const unsigned int blb_vco[8] = {
7492                 [0] = 3200000,
7493                 [1] = 4000000,
7494                 [2] = 5333333,
7495                 [3] = 4800000,
7496                 [4] = 6400000,
7497         };
7498         static const unsigned int pnv_vco[8] = {
7499                 [0] = 3200000,
7500                 [1] = 4000000,
7501                 [2] = 5333333,
7502                 [3] = 4800000,
7503                 [4] = 2666667,
7504         };
7505         static const unsigned int cl_vco[8] = {
7506                 [0] = 3200000,
7507                 [1] = 4000000,
7508                 [2] = 5333333,
7509                 [3] = 6400000,
7510                 [4] = 3333333,
7511                 [5] = 3566667,
7512                 [6] = 4266667,
7513         };
7514         static const unsigned int elk_vco[8] = {
7515                 [0] = 3200000,
7516                 [1] = 4000000,
7517                 [2] = 5333333,
7518                 [3] = 4800000,
7519         };
7520         static const unsigned int ctg_vco[8] = {
7521                 [0] = 3200000,
7522                 [1] = 4000000,
7523                 [2] = 5333333,
7524                 [3] = 6400000,
7525                 [4] = 2666667,
7526                 [5] = 4266667,
7527         };
7528         const unsigned int *vco_table;
7529         unsigned int vco;
7530         uint8_t tmp = 0;
7531
7532         /* FIXME other chipsets? */
7533         if (IS_GM45(dev_priv))
7534                 vco_table = ctg_vco;
7535         else if (IS_G4X(dev))
7536                 vco_table = elk_vco;
7537         else if (IS_CRESTLINE(dev))
7538                 vco_table = cl_vco;
7539         else if (IS_PINEVIEW(dev))
7540                 vco_table = pnv_vco;
7541         else if (IS_G33(dev))
7542                 vco_table = blb_vco;
7543         else
7544                 return 0;
7545
7546         tmp = I915_READ(IS_MOBILE(dev) ? HPLLVCO_MOBILE : HPLLVCO);
7547
7548         vco = vco_table[tmp & 0x7];
7549         if (vco == 0)
7550                 DRM_ERROR("Bad HPLL VCO (HPLLVCO=0x%02x)\n", tmp);
7551         else
7552                 DRM_DEBUG_KMS("HPLL VCO %u kHz\n", vco);
7553
7554         return vco;
7555 }
7556
7557 static int gm45_get_display_clock_speed(struct drm_device *dev)
7558 {
7559         struct pci_dev *pdev = dev->pdev;
7560         unsigned int cdclk_sel, vco = intel_hpll_vco(dev);
7561         uint16_t tmp = 0;
7562
7563         pci_read_config_word(pdev, GCFGC, &tmp);
7564
7565         cdclk_sel = (tmp >> 12) & 0x1;
7566
7567         switch (vco) {
7568         case 2666667:
7569         case 4000000:
7570         case 5333333:
7571                 return cdclk_sel ? 333333 : 222222;
7572         case 3200000:
7573                 return cdclk_sel ? 320000 : 228571;
7574         default:
7575                 DRM_ERROR("Unable to determine CDCLK. HPLL VCO=%u, CFGC=0x%04x\n", vco, tmp);
7576                 return 222222;
7577         }
7578 }
7579
7580 static int i965gm_get_display_clock_speed(struct drm_device *dev)
7581 {
7582         struct pci_dev *pdev = dev->pdev;
7583         static const uint8_t div_3200[] = { 16, 10,  8 };
7584         static const uint8_t div_4000[] = { 20, 12, 10 };
7585         static const uint8_t div_5333[] = { 24, 16, 14 };
7586         const uint8_t *div_table;
7587         unsigned int cdclk_sel, vco = intel_hpll_vco(dev);
7588         uint16_t tmp = 0;
7589
7590         pci_read_config_word(pdev, GCFGC, &tmp);
7591
7592         cdclk_sel = ((tmp >> 8) & 0x1f) - 1;
7593
7594         if (cdclk_sel >= ARRAY_SIZE(div_3200))
7595                 goto fail;
7596
7597         switch (vco) {
7598         case 3200000:
7599                 div_table = div_3200;
7600                 break;
7601         case 4000000:
7602                 div_table = div_4000;
7603                 break;
7604         case 5333333:
7605                 div_table = div_5333;
7606                 break;
7607         default:
7608                 goto fail;
7609         }
7610
7611         return DIV_ROUND_CLOSEST(vco, div_table[cdclk_sel]);
7612
7613 fail:
7614         DRM_ERROR("Unable to determine CDCLK. HPLL VCO=%u kHz, CFGC=0x%04x\n", vco, tmp);
7615         return 200000;
7616 }
7617
7618 static int g33_get_display_clock_speed(struct drm_device *dev)
7619 {
7620         struct pci_dev *pdev = dev->pdev;
7621         static const uint8_t div_3200[] = { 12, 10,  8,  7, 5, 16 };
7622         static const uint8_t div_4000[] = { 14, 12, 10,  8, 6, 20 };
7623         static const uint8_t div_4800[] = { 20, 14, 12, 10, 8, 24 };
7624         static const uint8_t div_5333[] = { 20, 16, 12, 12, 8, 28 };
7625         const uint8_t *div_table;
7626         unsigned int cdclk_sel, vco = intel_hpll_vco(dev);
7627         uint16_t tmp = 0;
7628
7629         pci_read_config_word(pdev, GCFGC, &tmp);
7630
7631         cdclk_sel = (tmp >> 4) & 0x7;
7632
7633         if (cdclk_sel >= ARRAY_SIZE(div_3200))
7634                 goto fail;
7635
7636         switch (vco) {
7637         case 3200000:
7638                 div_table = div_3200;
7639                 break;
7640         case 4000000:
7641                 div_table = div_4000;
7642                 break;
7643         case 4800000:
7644                 div_table = div_4800;
7645                 break;
7646         case 5333333:
7647                 div_table = div_5333;
7648                 break;
7649         default:
7650                 goto fail;
7651         }
7652
7653         return DIV_ROUND_CLOSEST(vco, div_table[cdclk_sel]);
7654
7655 fail:
7656         DRM_ERROR("Unable to determine CDCLK. HPLL VCO=%u kHz, CFGC=0x%08x\n", vco, tmp);
7657         return 190476;
7658 }
7659
7660 static void
7661 intel_reduce_m_n_ratio(uint32_t *num, uint32_t *den)
7662 {
7663         while (*num > DATA_LINK_M_N_MASK ||
7664                *den > DATA_LINK_M_N_MASK) {
7665                 *num >>= 1;
7666                 *den >>= 1;
7667         }
7668 }
7669
7670 static void compute_m_n(unsigned int m, unsigned int n,
7671                         uint32_t *ret_m, uint32_t *ret_n)
7672 {
7673         *ret_n = min_t(unsigned int, roundup_pow_of_two(n), DATA_LINK_N_MAX);
7674         *ret_m = div_u64((uint64_t) m * *ret_n, n);
7675         intel_reduce_m_n_ratio(ret_m, ret_n);
7676 }
7677
7678 void
7679 intel_link_compute_m_n(int bits_per_pixel, int nlanes,
7680                        int pixel_clock, int link_clock,
7681                        struct intel_link_m_n *m_n)
7682 {
7683         m_n->tu = 64;
7684
7685         compute_m_n(bits_per_pixel * pixel_clock,
7686                     link_clock * nlanes * 8,
7687                     &m_n->gmch_m, &m_n->gmch_n);
7688
7689         compute_m_n(pixel_clock, link_clock,
7690                     &m_n->link_m, &m_n->link_n);
7691 }
7692
7693 static inline bool intel_panel_use_ssc(struct drm_i915_private *dev_priv)
7694 {
7695         if (i915.panel_use_ssc >= 0)
7696                 return i915.panel_use_ssc != 0;
7697         return dev_priv->vbt.lvds_use_ssc
7698                 && !(dev_priv->quirks & QUIRK_LVDS_SSC_DISABLE);
7699 }
7700
7701 static uint32_t pnv_dpll_compute_fp(struct dpll *dpll)
7702 {
7703         return (1 << dpll->n) << 16 | dpll->m2;
7704 }
7705
7706 static uint32_t i9xx_dpll_compute_fp(struct dpll *dpll)
7707 {
7708         return dpll->n << 16 | dpll->m1 << 8 | dpll->m2;
7709 }
7710
7711 static void i9xx_update_pll_dividers(struct intel_crtc *crtc,
7712                                      struct intel_crtc_state *crtc_state,
7713                                      struct dpll *reduced_clock)
7714 {
7715         struct drm_device *dev = crtc->base.dev;
7716         u32 fp, fp2 = 0;
7717
7718         if (IS_PINEVIEW(dev)) {
7719                 fp = pnv_dpll_compute_fp(&crtc_state->dpll);
7720                 if (reduced_clock)
7721                         fp2 = pnv_dpll_compute_fp(reduced_clock);
7722         } else {
7723                 fp = i9xx_dpll_compute_fp(&crtc_state->dpll);
7724                 if (reduced_clock)
7725                         fp2 = i9xx_dpll_compute_fp(reduced_clock);
7726         }
7727
7728         crtc_state->dpll_hw_state.fp0 = fp;
7729
7730         crtc->lowfreq_avail = false;
7731         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS) &&
7732             reduced_clock) {
7733                 crtc_state->dpll_hw_state.fp1 = fp2;
7734                 crtc->lowfreq_avail = true;
7735         } else {
7736                 crtc_state->dpll_hw_state.fp1 = fp;
7737         }
7738 }
7739
7740 static void vlv_pllb_recal_opamp(struct drm_i915_private *dev_priv, enum pipe
7741                 pipe)
7742 {
7743         u32 reg_val;
7744
7745         /*
7746          * PLLB opamp always calibrates to max value of 0x3f, force enable it
7747          * and set it to a reasonable value instead.
7748          */
7749         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW9(1));
7750         reg_val &= 0xffffff00;
7751         reg_val |= 0x00000030;
7752         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW9(1), reg_val);
7753
7754         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_REF_DW13);
7755         reg_val &= 0x8cffffff;
7756         reg_val = 0x8c000000;
7757         vlv_dpio_write(dev_priv, pipe, VLV_REF_DW13, reg_val);
7758
7759         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW9(1));
7760         reg_val &= 0xffffff00;
7761         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW9(1), reg_val);
7762
7763         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_REF_DW13);
7764         reg_val &= 0x00ffffff;
7765         reg_val |= 0xb0000000;
7766         vlv_dpio_write(dev_priv, pipe, VLV_REF_DW13, reg_val);
7767 }
7768
7769 static void intel_pch_transcoder_set_m_n(struct intel_crtc *crtc,
7770                                          struct intel_link_m_n *m_n)
7771 {
7772         struct drm_device *dev = crtc->base.dev;
7773         struct drm_i915_private *dev_priv = to_i915(dev);
7774         int pipe = crtc->pipe;
7775
7776         I915_WRITE(PCH_TRANS_DATA_M1(pipe), TU_SIZE(m_n->tu) | m_n->gmch_m);
7777         I915_WRITE(PCH_TRANS_DATA_N1(pipe), m_n->gmch_n);
7778         I915_WRITE(PCH_TRANS_LINK_M1(pipe), m_n->link_m);
7779         I915_WRITE(PCH_TRANS_LINK_N1(pipe), m_n->link_n);
7780 }
7781
7782 static void intel_cpu_transcoder_set_m_n(struct intel_crtc *crtc,
7783                                          struct intel_link_m_n *m_n,
7784                                          struct intel_link_m_n *m2_n2)
7785 {
7786         struct drm_device *dev = crtc->base.dev;
7787         struct drm_i915_private *dev_priv = to_i915(dev);
7788         int pipe = crtc->pipe;
7789         enum transcoder transcoder = crtc->config->cpu_transcoder;
7790
7791         if (INTEL_INFO(dev)->gen >= 5) {
7792                 I915_WRITE(PIPE_DATA_M1(transcoder), TU_SIZE(m_n->tu) | m_n->gmch_m);
7793                 I915_WRITE(PIPE_DATA_N1(transcoder), m_n->gmch_n);
7794                 I915_WRITE(PIPE_LINK_M1(transcoder), m_n->link_m);
7795                 I915_WRITE(PIPE_LINK_N1(transcoder), m_n->link_n);
7796                 /* M2_N2 registers to be set only for gen < 8 (M2_N2 available
7797                  * for gen < 8) and if DRRS is supported (to make sure the
7798                  * registers are not unnecessarily accessed).
7799                  */
7800                 if (m2_n2 && (IS_CHERRYVIEW(dev) || INTEL_INFO(dev)->gen < 8) &&
7801                         crtc->config->has_drrs) {
7802                         I915_WRITE(PIPE_DATA_M2(transcoder),
7803                                         TU_SIZE(m2_n2->tu) | m2_n2->gmch_m);
7804                         I915_WRITE(PIPE_DATA_N2(transcoder), m2_n2->gmch_n);
7805                         I915_WRITE(PIPE_LINK_M2(transcoder), m2_n2->link_m);
7806                         I915_WRITE(PIPE_LINK_N2(transcoder), m2_n2->link_n);
7807                 }
7808         } else {
7809                 I915_WRITE(PIPE_DATA_M_G4X(pipe), TU_SIZE(m_n->tu) | m_n->gmch_m);
7810                 I915_WRITE(PIPE_DATA_N_G4X(pipe), m_n->gmch_n);
7811                 I915_WRITE(PIPE_LINK_M_G4X(pipe), m_n->link_m);
7812                 I915_WRITE(PIPE_LINK_N_G4X(pipe), m_n->link_n);
7813         }
7814 }
7815
7816 void intel_dp_set_m_n(struct intel_crtc *crtc, enum link_m_n_set m_n)
7817 {
7818         struct intel_link_m_n *dp_m_n, *dp_m2_n2 = NULL;
7819
7820         if (m_n == M1_N1) {
7821                 dp_m_n = &crtc->config->dp_m_n;
7822                 dp_m2_n2 = &crtc->config->dp_m2_n2;
7823         } else if (m_n == M2_N2) {
7824
7825                 /*
7826                  * M2_N2 registers are not supported. Hence m2_n2 divider value
7827                  * needs to be programmed into M1_N1.
7828                  */
7829                 dp_m_n = &crtc->config->dp_m2_n2;
7830         } else {
7831                 DRM_ERROR("Unsupported divider value\n");
7832                 return;
7833         }
7834
7835         if (crtc->config->has_pch_encoder)
7836                 intel_pch_transcoder_set_m_n(crtc, &crtc->config->dp_m_n);
7837         else
7838                 intel_cpu_transcoder_set_m_n(crtc, dp_m_n, dp_m2_n2);
7839 }
7840
7841 static void vlv_compute_dpll(struct intel_crtc *crtc,
7842                              struct intel_crtc_state *pipe_config)
7843 {
7844         pipe_config->dpll_hw_state.dpll = DPLL_INTEGRATED_REF_CLK_VLV |
7845                 DPLL_REF_CLK_ENABLE_VLV | DPLL_VGA_MODE_DIS;
7846         if (crtc->pipe != PIPE_A)
7847                 pipe_config->dpll_hw_state.dpll |= DPLL_INTEGRATED_CRI_CLK_VLV;
7848
7849         /* DPLL not used with DSI, but still need the rest set up */
7850         if (!intel_crtc_has_type(pipe_config, INTEL_OUTPUT_DSI))
7851                 pipe_config->dpll_hw_state.dpll |= DPLL_VCO_ENABLE |
7852                         DPLL_EXT_BUFFER_ENABLE_VLV;
7853
7854         pipe_config->dpll_hw_state.dpll_md =
7855                 (pipe_config->pixel_multiplier - 1) << DPLL_MD_UDI_MULTIPLIER_SHIFT;
7856 }
7857
7858 static void chv_compute_dpll(struct intel_crtc *crtc,
7859                              struct intel_crtc_state *pipe_config)
7860 {
7861         pipe_config->dpll_hw_state.dpll = DPLL_SSC_REF_CLK_CHV |
7862                 DPLL_REF_CLK_ENABLE_VLV | DPLL_VGA_MODE_DIS;
7863         if (crtc->pipe != PIPE_A)
7864                 pipe_config->dpll_hw_state.dpll |= DPLL_INTEGRATED_CRI_CLK_VLV;
7865
7866         /* DPLL not used with DSI, but still need the rest set up */
7867         if (!intel_crtc_has_type(pipe_config, INTEL_OUTPUT_DSI))
7868                 pipe_config->dpll_hw_state.dpll |= DPLL_VCO_ENABLE;
7869
7870         pipe_config->dpll_hw_state.dpll_md =
7871                 (pipe_config->pixel_multiplier - 1) << DPLL_MD_UDI_MULTIPLIER_SHIFT;
7872 }
7873
7874 static void vlv_prepare_pll(struct intel_crtc *crtc,
7875                             const struct intel_crtc_state *pipe_config)
7876 {
7877         struct drm_device *dev = crtc->base.dev;
7878         struct drm_i915_private *dev_priv = to_i915(dev);
7879         enum pipe pipe = crtc->pipe;
7880         u32 mdiv;
7881         u32 bestn, bestm1, bestm2, bestp1, bestp2;
7882         u32 coreclk, reg_val;
7883
7884         /* Enable Refclk */
7885         I915_WRITE(DPLL(pipe),
7886                    pipe_config->dpll_hw_state.dpll &
7887                    ~(DPLL_VCO_ENABLE | DPLL_EXT_BUFFER_ENABLE_VLV));
7888
7889         /* No need to actually set up the DPLL with DSI */
7890         if ((pipe_config->dpll_hw_state.dpll & DPLL_VCO_ENABLE) == 0)
7891                 return;
7892
7893         mutex_lock(&dev_priv->sb_lock);
7894
7895         bestn = pipe_config->dpll.n;
7896         bestm1 = pipe_config->dpll.m1;
7897         bestm2 = pipe_config->dpll.m2;
7898         bestp1 = pipe_config->dpll.p1;
7899         bestp2 = pipe_config->dpll.p2;
7900
7901         /* See eDP HDMI DPIO driver vbios notes doc */
7902
7903         /* PLL B needs special handling */
7904         if (pipe == PIPE_B)
7905                 vlv_pllb_recal_opamp(dev_priv, pipe);
7906
7907         /* Set up Tx target for periodic Rcomp update */
7908         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW9_BCAST, 0x0100000f);
7909
7910         /* Disable target IRef on PLL */
7911         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW8(pipe));
7912         reg_val &= 0x00ffffff;
7913         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW8(pipe), reg_val);
7914
7915         /* Disable fast lock */
7916         vlv_dpio_write(dev_priv, pipe, VLV_CMN_DW0, 0x610);
7917
7918         /* Set idtafcrecal before PLL is enabled */
7919         mdiv = ((bestm1 << DPIO_M1DIV_SHIFT) | (bestm2 & DPIO_M2DIV_MASK));
7920         mdiv |= ((bestp1 << DPIO_P1_SHIFT) | (bestp2 << DPIO_P2_SHIFT));
7921         mdiv |= ((bestn << DPIO_N_SHIFT));
7922         mdiv |= (1 << DPIO_K_SHIFT);
7923
7924         /*
7925          * Post divider depends on pixel clock rate, DAC vs digital (and LVDS,
7926          * but we don't support that).
7927          * Note: don't use the DAC post divider as it seems unstable.
7928          */
7929         mdiv |= (DPIO_POST_DIV_HDMIDP << DPIO_POST_DIV_SHIFT);
7930         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW3(pipe), mdiv);
7931
7932         mdiv |= DPIO_ENABLE_CALIBRATION;
7933         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW3(pipe), mdiv);
7934
7935         /* Set HBR and RBR LPF coefficients */
7936         if (pipe_config->port_clock == 162000 ||
7937             intel_crtc_has_type(crtc->config, INTEL_OUTPUT_ANALOG) ||
7938             intel_crtc_has_type(crtc->config, INTEL_OUTPUT_HDMI))
7939                 vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW10(pipe),
7940                                  0x009f0003);
7941         else
7942                 vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW10(pipe),
7943                                  0x00d0000f);
7944
7945         if (intel_crtc_has_dp_encoder(pipe_config)) {
7946                 /* Use SSC source */
7947                 if (pipe == PIPE_A)
7948                         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW5(pipe),
7949                                          0x0df40000);
7950                 else
7951                         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW5(pipe),
7952                                          0x0df70000);
7953         } else { /* HDMI or VGA */
7954                 /* Use bend source */
7955                 if (pipe == PIPE_A)
7956                         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW5(pipe),
7957                                          0x0df70000);
7958                 else
7959                         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW5(pipe),
7960                                          0x0df40000);
7961         }
7962
7963         coreclk = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW7(pipe));
7964         coreclk = (coreclk & 0x0000ff00) | 0x01c00000;
7965         if (intel_crtc_has_dp_encoder(crtc->config))
7966                 coreclk |= 0x01000000;
7967         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW7(pipe), coreclk);
7968
7969         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW11(pipe), 0x87871000);
7970         mutex_unlock(&dev_priv->sb_lock);
7971 }
7972
7973 static void chv_prepare_pll(struct intel_crtc *crtc,
7974                             const struct intel_crtc_state *pipe_config)
7975 {
7976         struct drm_device *dev = crtc->base.dev;
7977         struct drm_i915_private *dev_priv = to_i915(dev);
7978         enum pipe pipe = crtc->pipe;
7979         enum dpio_channel port = vlv_pipe_to_channel(pipe);
7980         u32 loopfilter, tribuf_calcntr;
7981         u32 bestn, bestm1, bestm2, bestp1, bestp2, bestm2_frac;
7982         u32 dpio_val;
7983         int vco;
7984
7985         /* Enable Refclk and SSC */
7986         I915_WRITE(DPLL(pipe),
7987                    pipe_config->dpll_hw_state.dpll & ~DPLL_VCO_ENABLE);
7988
7989         /* No need to actually set up the DPLL with DSI */
7990         if ((pipe_config->dpll_hw_state.dpll & DPLL_VCO_ENABLE) == 0)
7991                 return;
7992
7993         bestn = pipe_config->dpll.n;
7994         bestm2_frac = pipe_config->dpll.m2 & 0x3fffff;
7995         bestm1 = pipe_config->dpll.m1;
7996         bestm2 = pipe_config->dpll.m2 >> 22;
7997         bestp1 = pipe_config->dpll.p1;
7998         bestp2 = pipe_config->dpll.p2;
7999         vco = pipe_config->dpll.vco;
8000         dpio_val = 0;
8001         loopfilter = 0;
8002
8003         mutex_lock(&dev_priv->sb_lock);
8004
8005         /* p1 and p2 divider */
8006         vlv_dpio_write(dev_priv, pipe, CHV_CMN_DW13(port),
8007                         5 << DPIO_CHV_S1_DIV_SHIFT |
8008                         bestp1 << DPIO_CHV_P1_DIV_SHIFT |
8009                         bestp2 << DPIO_CHV_P2_DIV_SHIFT |
8010                         1 << DPIO_CHV_K_DIV_SHIFT);
8011
8012         /* Feedback post-divider - m2 */
8013         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW0(port), bestm2);
8014
8015         /* Feedback refclk divider - n and m1 */
8016         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW1(port),
8017                         DPIO_CHV_M1_DIV_BY_2 |
8018                         1 << DPIO_CHV_N_DIV_SHIFT);
8019
8020         /* M2 fraction division */
8021         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW2(port), bestm2_frac);
8022
8023         /* M2 fraction division enable */
8024         dpio_val = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW3(port));
8025         dpio_val &= ~(DPIO_CHV_FEEDFWD_GAIN_MASK | DPIO_CHV_FRAC_DIV_EN);
8026         dpio_val |= (2 << DPIO_CHV_FEEDFWD_GAIN_SHIFT);
8027         if (bestm2_frac)
8028                 dpio_val |= DPIO_CHV_FRAC_DIV_EN;
8029         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW3(port), dpio_val);
8030
8031         /* Program digital lock detect threshold */
8032         dpio_val = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW9(port));
8033         dpio_val &= ~(DPIO_CHV_INT_LOCK_THRESHOLD_MASK |
8034                                         DPIO_CHV_INT_LOCK_THRESHOLD_SEL_COARSE);
8035         dpio_val |= (0x5 << DPIO_CHV_INT_LOCK_THRESHOLD_SHIFT);
8036         if (!bestm2_frac)
8037                 dpio_val |= DPIO_CHV_INT_LOCK_THRESHOLD_SEL_COARSE;
8038         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW9(port), dpio_val);
8039
8040         /* Loop filter */
8041         if (vco == 5400000) {
8042                 loopfilter |= (0x3 << DPIO_CHV_PROP_COEFF_SHIFT);
8043                 loopfilter |= (0x8 << DPIO_CHV_INT_COEFF_SHIFT);
8044                 loopfilter |= (0x1 << DPIO_CHV_GAIN_CTRL_SHIFT);
8045                 tribuf_calcntr = 0x9;
8046         } else if (vco <= 6200000) {
8047                 loopfilter |= (0x5 << DPIO_CHV_PROP_COEFF_SHIFT);
8048                 loopfilter |= (0xB << DPIO_CHV_INT_COEFF_SHIFT);
8049                 loopfilter |= (0x3 << DPIO_CHV_GAIN_CTRL_SHIFT);
8050                 tribuf_calcntr = 0x9;
8051         } else if (vco <= 6480000) {
8052                 loopfilter |= (0x4 << DPIO_CHV_PROP_COEFF_SHIFT);
8053                 loopfilter |= (0x9 << DPIO_CHV_INT_COEFF_SHIFT);
8054                 loopfilter |= (0x3 << DPIO_CHV_GAIN_CTRL_SHIFT);
8055                 tribuf_calcntr = 0x8;
8056         } else {
8057                 /* Not supported. Apply the same limits as in the max case */
8058                 loopfilter |= (0x4 << DPIO_CHV_PROP_COEFF_SHIFT);
8059                 loopfilter |= (0x9 << DPIO_CHV_INT_COEFF_SHIFT);
8060                 loopfilter |= (0x3 << DPIO_CHV_GAIN_CTRL_SHIFT);
8061                 tribuf_calcntr = 0;
8062         }
8063         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW6(port), loopfilter);
8064
8065         dpio_val = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW8(port));
8066         dpio_val &= ~DPIO_CHV_TDC_TARGET_CNT_MASK;
8067         dpio_val |= (tribuf_calcntr << DPIO_CHV_TDC_TARGET_CNT_SHIFT);
8068         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW8(port), dpio_val);
8069
8070         /* AFC Recal */
8071         vlv_dpio_write(dev_priv, pipe, CHV_CMN_DW14(port),
8072                         vlv_dpio_read(dev_priv, pipe, CHV_CMN_DW14(port)) |
8073                         DPIO_AFC_RECAL);
8074
8075         mutex_unlock(&dev_priv->sb_lock);
8076 }
8077
8078 /**
8079  * vlv_force_pll_on - forcibly enable just the PLL
8080  * @dev_priv: i915 private structure
8081  * @pipe: pipe PLL to enable
8082  * @dpll: PLL configuration
8083  *
8084  * Enable the PLL for @pipe using the supplied @dpll config. To be used
8085  * in cases where we need the PLL enabled even when @pipe is not going to
8086  * be enabled.
8087  */
8088 int vlv_force_pll_on(struct drm_device *dev, enum pipe pipe,
8089                      const struct dpll *dpll)
8090 {
8091         struct intel_crtc *crtc =
8092                 to_intel_crtc(intel_get_crtc_for_pipe(dev, pipe));
8093         struct intel_crtc_state *pipe_config;
8094
8095         pipe_config = kzalloc(sizeof(*pipe_config), GFP_KERNEL);
8096         if (!pipe_config)
8097                 return -ENOMEM;
8098
8099         pipe_config->base.crtc = &crtc->base;
8100         pipe_config->pixel_multiplier = 1;
8101         pipe_config->dpll = *dpll;
8102
8103         if (IS_CHERRYVIEW(dev)) {
8104                 chv_compute_dpll(crtc, pipe_config);
8105                 chv_prepare_pll(crtc, pipe_config);
8106                 chv_enable_pll(crtc, pipe_config);
8107         } else {
8108                 vlv_compute_dpll(crtc, pipe_config);
8109                 vlv_prepare_pll(crtc, pipe_config);
8110                 vlv_enable_pll(crtc, pipe_config);
8111         }
8112
8113         kfree(pipe_config);
8114
8115         return 0;
8116 }
8117
8118 /**
8119  * vlv_force_pll_off - forcibly disable just the PLL
8120  * @dev_priv: i915 private structure
8121  * @pipe: pipe PLL to disable
8122  *
8123  * Disable the PLL for @pipe. To be used in cases where we need
8124  * the PLL enabled even when @pipe is not going to be enabled.
8125  */
8126 void vlv_force_pll_off(struct drm_device *dev, enum pipe pipe)
8127 {
8128         if (IS_CHERRYVIEW(dev))
8129                 chv_disable_pll(to_i915(dev), pipe);
8130         else
8131                 vlv_disable_pll(to_i915(dev), pipe);
8132 }
8133
8134 static void i9xx_compute_dpll(struct intel_crtc *crtc,
8135                               struct intel_crtc_state *crtc_state,
8136                               struct dpll *reduced_clock)
8137 {
8138         struct drm_device *dev = crtc->base.dev;
8139         struct drm_i915_private *dev_priv = to_i915(dev);
8140         u32 dpll;
8141         struct dpll *clock = &crtc_state->dpll;
8142
8143         i9xx_update_pll_dividers(crtc, crtc_state, reduced_clock);
8144
8145         dpll = DPLL_VGA_MODE_DIS;
8146
8147         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS))
8148                 dpll |= DPLLB_MODE_LVDS;
8149         else
8150                 dpll |= DPLLB_MODE_DAC_SERIAL;
8151
8152         if (IS_I945G(dev_priv) || IS_I945GM(dev_priv) || IS_G33(dev_priv)) {
8153                 dpll |= (crtc_state->pixel_multiplier - 1)
8154                         << SDVO_MULTIPLIER_SHIFT_HIRES;
8155         }
8156
8157         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_SDVO) ||
8158             intel_crtc_has_type(crtc_state, INTEL_OUTPUT_HDMI))
8159                 dpll |= DPLL_SDVO_HIGH_SPEED;
8160
8161         if (intel_crtc_has_dp_encoder(crtc_state))
8162                 dpll |= DPLL_SDVO_HIGH_SPEED;
8163
8164         /* compute bitmask from p1 value */
8165         if (IS_PINEVIEW(dev))
8166                 dpll |= (1 << (clock->p1 - 1)) << DPLL_FPA01_P1_POST_DIV_SHIFT_PINEVIEW;
8167         else {
8168                 dpll |= (1 << (clock->p1 - 1)) << DPLL_FPA01_P1_POST_DIV_SHIFT;
8169                 if (IS_G4X(dev) && reduced_clock)
8170                         dpll |= (1 << (reduced_clock->p1 - 1)) << DPLL_FPA1_P1_POST_DIV_SHIFT;
8171         }
8172         switch (clock->p2) {
8173         case 5:
8174                 dpll |= DPLL_DAC_SERIAL_P2_CLOCK_DIV_5;
8175                 break;
8176         case 7:
8177                 dpll |= DPLLB_LVDS_P2_CLOCK_DIV_7;
8178                 break;
8179         case 10:
8180                 dpll |= DPLL_DAC_SERIAL_P2_CLOCK_DIV_10;
8181                 break;
8182         case 14:
8183                 dpll |= DPLLB_LVDS_P2_CLOCK_DIV_14;
8184                 break;
8185         }
8186         if (INTEL_INFO(dev)->gen >= 4)
8187                 dpll |= (6 << PLL_LOAD_PULSE_PHASE_SHIFT);
8188
8189         if (crtc_state->sdvo_tv_clock)
8190                 dpll |= PLL_REF_INPUT_TVCLKINBC;
8191         else if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS) &&
8192                  intel_panel_use_ssc(dev_priv))
8193                 dpll |= PLLB_REF_INPUT_SPREADSPECTRUMIN;
8194         else
8195                 dpll |= PLL_REF_INPUT_DREFCLK;
8196
8197         dpll |= DPLL_VCO_ENABLE;
8198         crtc_state->dpll_hw_state.dpll = dpll;
8199
8200         if (INTEL_INFO(dev)->gen >= 4) {
8201                 u32 dpll_md = (crtc_state->pixel_multiplier - 1)
8202                         << DPLL_MD_UDI_MULTIPLIER_SHIFT;
8203                 crtc_state->dpll_hw_state.dpll_md = dpll_md;
8204         }
8205 }
8206
8207 static void i8xx_compute_dpll(struct intel_crtc *crtc,
8208                               struct intel_crtc_state *crtc_state,
8209                               struct dpll *reduced_clock)
8210 {
8211         struct drm_device *dev = crtc->base.dev;
8212         struct drm_i915_private *dev_priv = to_i915(dev);
8213         u32 dpll;
8214         struct dpll *clock = &crtc_state->dpll;
8215
8216         i9xx_update_pll_dividers(crtc, crtc_state, reduced_clock);
8217
8218         dpll = DPLL_VGA_MODE_DIS;
8219
8220         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS)) {
8221                 dpll |= (1 << (clock->p1 - 1)) << DPLL_FPA01_P1_POST_DIV_SHIFT;
8222         } else {
8223                 if (clock->p1 == 2)
8224                         dpll |= PLL_P1_DIVIDE_BY_TWO;
8225                 else
8226                         dpll |= (clock->p1 - 2) << DPLL_FPA01_P1_POST_DIV_SHIFT;
8227                 if (clock->p2 == 4)
8228                         dpll |= PLL_P2_DIVIDE_BY_4;
8229         }
8230
8231         if (!IS_I830(dev_priv) &&
8232             intel_crtc_has_type(crtc_state, INTEL_OUTPUT_DVO))
8233                 dpll |= DPLL_DVO_2X_MODE;
8234
8235         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS) &&
8236             intel_panel_use_ssc(dev_priv))
8237                 dpll |= PLLB_REF_INPUT_SPREADSPECTRUMIN;
8238         else
8239                 dpll |= PLL_REF_INPUT_DREFCLK;
8240
8241         dpll |= DPLL_VCO_ENABLE;
8242         crtc_state->dpll_hw_state.dpll = dpll;
8243 }
8244
8245 static void intel_set_pipe_timings(struct intel_crtc *intel_crtc)
8246 {
8247         struct drm_device *dev = intel_crtc->base.dev;
8248         struct drm_i915_private *dev_priv = to_i915(dev);
8249         enum pipe pipe = intel_crtc->pipe;
8250         enum transcoder cpu_transcoder = intel_crtc->config->cpu_transcoder;
8251         const struct drm_display_mode *adjusted_mode = &intel_crtc->config->base.adjusted_mode;
8252         uint32_t crtc_vtotal, crtc_vblank_end;
8253         int vsyncshift = 0;
8254
8255         /* We need to be careful not to changed the adjusted mode, for otherwise
8256          * the hw state checker will get angry at the mismatch. */
8257         crtc_vtotal = adjusted_mode->crtc_vtotal;
8258         crtc_vblank_end = adjusted_mode->crtc_vblank_end;
8259
8260         if (adjusted_mode->flags & DRM_MODE_FLAG_INTERLACE) {
8261                 /* the chip adds 2 halflines automatically */
8262                 crtc_vtotal -= 1;
8263                 crtc_vblank_end -= 1;
8264
8265                 if (intel_crtc_has_type(intel_crtc->config, INTEL_OUTPUT_SDVO))
8266                         vsyncshift = (adjusted_mode->crtc_htotal - 1) / 2;
8267                 else
8268                         vsyncshift = adjusted_mode->crtc_hsync_start -
8269                                 adjusted_mode->crtc_htotal / 2;
8270                 if (vsyncshift < 0)
8271                         vsyncshift += adjusted_mode->crtc_htotal;
8272         }
8273
8274         if (INTEL_INFO(dev)->gen > 3)
8275                 I915_WRITE(VSYNCSHIFT(cpu_transcoder), vsyncshift);
8276
8277         I915_WRITE(HTOTAL(cpu_transcoder),
8278                    (adjusted_mode->crtc_hdisplay - 1) |
8279                    ((adjusted_mode->crtc_htotal - 1) << 16));
8280         I915_WRITE(HBLANK(cpu_transcoder),
8281                    (adjusted_mode->crtc_hblank_start - 1) |
8282                    ((adjusted_mode->crtc_hblank_end - 1) << 16));
8283         I915_WRITE(HSYNC(cpu_transcoder),
8284                    (adjusted_mode->crtc_hsync_start - 1) |
8285                    ((adjusted_mode->crtc_hsync_end - 1) << 16));
8286
8287         I915_WRITE(VTOTAL(cpu_transcoder),
8288                    (adjusted_mode->crtc_vdisplay - 1) |
8289                    ((crtc_vtotal - 1) << 16));
8290         I915_WRITE(VBLANK(cpu_transcoder),
8291                    (adjusted_mode->crtc_vblank_start - 1) |
8292                    ((crtc_vblank_end - 1) << 16));
8293         I915_WRITE(VSYNC(cpu_transcoder),
8294                    (adjusted_mode->crtc_vsync_start - 1) |
8295                    ((adjusted_mode->crtc_vsync_end - 1) << 16));
8296
8297         /* Workaround: when the EDP input selection is B, the VTOTAL_B must be
8298          * programmed with the VTOTAL_EDP value. Same for VTOTAL_C. This is
8299          * documented on the DDI_FUNC_CTL register description, EDP Input Select
8300          * bits. */
8301         if (IS_HASWELL(dev) && cpu_transcoder == TRANSCODER_EDP &&
8302             (pipe == PIPE_B || pipe == PIPE_C))
8303                 I915_WRITE(VTOTAL(pipe), I915_READ(VTOTAL(cpu_transcoder)));
8304
8305 }
8306
8307 static void intel_set_pipe_src_size(struct intel_crtc *intel_crtc)
8308 {
8309         struct drm_device *dev = intel_crtc->base.dev;
8310         struct drm_i915_private *dev_priv = to_i915(dev);
8311         enum pipe pipe = intel_crtc->pipe;
8312
8313         /* pipesrc controls the size that is scaled from, which should
8314          * always be the user's requested size.
8315          */
8316         I915_WRITE(PIPESRC(pipe),
8317                    ((intel_crtc->config->pipe_src_w - 1) << 16) |
8318                    (intel_crtc->config->pipe_src_h - 1));
8319 }
8320
8321 static void intel_get_pipe_timings(struct intel_crtc *crtc,
8322                                    struct intel_crtc_state *pipe_config)
8323 {
8324         struct drm_device *dev = crtc->base.dev;
8325         struct drm_i915_private *dev_priv = to_i915(dev);
8326         enum transcoder cpu_transcoder = pipe_config->cpu_transcoder;
8327         uint32_t tmp;
8328
8329         tmp = I915_READ(HTOTAL(cpu_transcoder));
8330         pipe_config->base.adjusted_mode.crtc_hdisplay = (tmp & 0xffff) + 1;
8331         pipe_config->base.adjusted_mode.crtc_htotal = ((tmp >> 16) & 0xffff) + 1;
8332         tmp = I915_READ(HBLANK(cpu_transcoder));
8333         pipe_config->base.adjusted_mode.crtc_hblank_start = (tmp & 0xffff) + 1;
8334         pipe_config->base.adjusted_mode.crtc_hblank_end = ((tmp >> 16) & 0xffff) + 1;
8335         tmp = I915_READ(HSYNC(cpu_transcoder));
8336         pipe_config->base.adjusted_mode.crtc_hsync_start = (tmp & 0xffff) + 1;
8337         pipe_config->base.adjusted_mode.crtc_hsync_end = ((tmp >> 16) & 0xffff) + 1;
8338
8339         tmp = I915_READ(VTOTAL(cpu_transcoder));
8340         pipe_config->base.adjusted_mode.crtc_vdisplay = (tmp & 0xffff) + 1;
8341         pipe_config->base.adjusted_mode.crtc_vtotal = ((tmp >> 16) & 0xffff) + 1;
8342         tmp = I915_READ(VBLANK(cpu_transcoder));
8343         pipe_config->base.adjusted_mode.crtc_vblank_start = (tmp & 0xffff) + 1;
8344         pipe_config->base.adjusted_mode.crtc_vblank_end = ((tmp >> 16) & 0xffff) + 1;
8345         tmp = I915_READ(VSYNC(cpu_transcoder));
8346         pipe_config->base.adjusted_mode.crtc_vsync_start = (tmp & 0xffff) + 1;
8347         pipe_config->base.adjusted_mode.crtc_vsync_end = ((tmp >> 16) & 0xffff) + 1;
8348
8349         if (I915_READ(PIPECONF(cpu_transcoder)) & PIPECONF_INTERLACE_MASK) {
8350                 pipe_config->base.adjusted_mode.flags |= DRM_MODE_FLAG_INTERLACE;
8351                 pipe_config->base.adjusted_mode.crtc_vtotal += 1;
8352                 pipe_config->base.adjusted_mode.crtc_vblank_end += 1;
8353         }
8354 }
8355
8356 static void intel_get_pipe_src_size(struct intel_crtc *crtc,
8357                                     struct intel_crtc_state *pipe_config)
8358 {
8359         struct drm_device *dev = crtc->base.dev;
8360         struct drm_i915_private *dev_priv = to_i915(dev);
8361         u32 tmp;
8362
8363         tmp = I915_READ(PIPESRC(crtc->pipe));
8364         pipe_config->pipe_src_h = (tmp & 0xffff) + 1;
8365         pipe_config->pipe_src_w = ((tmp >> 16) & 0xffff) + 1;
8366
8367         pipe_config->base.mode.vdisplay = pipe_config->pipe_src_h;
8368         pipe_config->base.mode.hdisplay = pipe_config->pipe_src_w;
8369 }
8370
8371 void intel_mode_from_pipe_config(struct drm_display_mode *mode,
8372                                  struct intel_crtc_state *pipe_config)
8373 {
8374         mode->hdisplay = pipe_config->base.adjusted_mode.crtc_hdisplay;
8375         mode->htotal = pipe_config->base.adjusted_mode.crtc_htotal;
8376         mode->hsync_start = pipe_config->base.adjusted_mode.crtc_hsync_start;
8377         mode->hsync_end = pipe_config->base.adjusted_mode.crtc_hsync_end;
8378
8379         mode->vdisplay = pipe_config->base.adjusted_mode.crtc_vdisplay;
8380         mode->vtotal = pipe_config->base.adjusted_mode.crtc_vtotal;
8381         mode->vsync_start = pipe_config->base.adjusted_mode.crtc_vsync_start;
8382         mode->vsync_end = pipe_config->base.adjusted_mode.crtc_vsync_end;
8383
8384         mode->flags = pipe_config->base.adjusted_mode.flags;
8385         mode->type = DRM_MODE_TYPE_DRIVER;
8386
8387         mode->clock = pipe_config->base.adjusted_mode.crtc_clock;
8388         mode->flags |= pipe_config->base.adjusted_mode.flags;
8389
8390         mode->hsync = drm_mode_hsync(mode);
8391         mode->vrefresh = drm_mode_vrefresh(mode);
8392         drm_mode_set_name(mode);
8393 }
8394
8395 static void i9xx_set_pipeconf(struct intel_crtc *intel_crtc)
8396 {
8397         struct drm_device *dev = intel_crtc->base.dev;
8398         struct drm_i915_private *dev_priv = to_i915(dev);
8399         uint32_t pipeconf;
8400
8401         pipeconf = 0;
8402
8403         if ((intel_crtc->pipe == PIPE_A && dev_priv->quirks & QUIRK_PIPEA_FORCE) ||
8404             (intel_crtc->pipe == PIPE_B && dev_priv->quirks & QUIRK_PIPEB_FORCE))
8405                 pipeconf |= I915_READ(PIPECONF(intel_crtc->pipe)) & PIPECONF_ENABLE;
8406
8407         if (intel_crtc->config->double_wide)
8408                 pipeconf |= PIPECONF_DOUBLE_WIDE;
8409
8410         /* only g4x and later have fancy bpc/dither controls */
8411         if (IS_G4X(dev) || IS_VALLEYVIEW(dev) || IS_CHERRYVIEW(dev)) {
8412                 /* Bspec claims that we can't use dithering for 30bpp pipes. */
8413                 if (intel_crtc->config->dither && intel_crtc->config->pipe_bpp != 30)
8414                         pipeconf |= PIPECONF_DITHER_EN |
8415                                     PIPECONF_DITHER_TYPE_SP;
8416
8417                 switch (intel_crtc->config->pipe_bpp) {
8418                 case 18:
8419                         pipeconf |= PIPECONF_6BPC;
8420                         break;
8421                 case 24:
8422                         pipeconf |= PIPECONF_8BPC;
8423                         break;
8424                 case 30:
8425                         pipeconf |= PIPECONF_10BPC;
8426                         break;
8427                 default:
8428                         /* Case prevented by intel_choose_pipe_bpp_dither. */
8429                         BUG();
8430                 }
8431         }
8432
8433         if (HAS_PIPE_CXSR(dev)) {
8434                 if (intel_crtc->lowfreq_avail) {
8435                         DRM_DEBUG_KMS("enabling CxSR downclocking\n");
8436                         pipeconf |= PIPECONF_CXSR_DOWNCLOCK;
8437                 } else {
8438                         DRM_DEBUG_KMS("disabling CxSR downclocking\n");
8439                 }
8440         }
8441
8442         if (intel_crtc->config->base.adjusted_mode.flags & DRM_MODE_FLAG_INTERLACE) {
8443                 if (INTEL_INFO(dev)->gen < 4 ||
8444                     intel_crtc_has_type(intel_crtc->config, INTEL_OUTPUT_SDVO))
8445                         pipeconf |= PIPECONF_INTERLACE_W_FIELD_INDICATION;
8446                 else
8447                         pipeconf |= PIPECONF_INTERLACE_W_SYNC_SHIFT;
8448         } else
8449                 pipeconf |= PIPECONF_PROGRESSIVE;
8450
8451         if ((IS_VALLEYVIEW(dev) || IS_CHERRYVIEW(dev)) &&
8452              intel_crtc->config->limited_color_range)
8453                 pipeconf |= PIPECONF_COLOR_RANGE_SELECT;
8454
8455         I915_WRITE(PIPECONF(intel_crtc->pipe), pipeconf);
8456         POSTING_READ(PIPECONF(intel_crtc->pipe));
8457 }
8458
8459 static int i8xx_crtc_compute_clock(struct intel_crtc *crtc,
8460                                    struct intel_crtc_state *crtc_state)
8461 {
8462         struct drm_device *dev = crtc->base.dev;
8463         struct drm_i915_private *dev_priv = to_i915(dev);
8464         const struct intel_limit *limit;
8465         int refclk = 48000;
8466
8467         memset(&crtc_state->dpll_hw_state, 0,
8468                sizeof(crtc_state->dpll_hw_state));
8469
8470         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS)) {
8471                 if (intel_panel_use_ssc(dev_priv)) {
8472                         refclk = dev_priv->vbt.lvds_ssc_freq;
8473                         DRM_DEBUG_KMS("using SSC reference clock of %d kHz\n", refclk);
8474                 }
8475
8476                 limit = &intel_limits_i8xx_lvds;
8477         } else if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_DVO)) {
8478                 limit = &intel_limits_i8xx_dvo;
8479         } else {
8480                 limit = &intel_limits_i8xx_dac;
8481         }
8482
8483         if (!crtc_state->clock_set &&
8484             !i9xx_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
8485                                  refclk, NULL, &crtc_state->dpll)) {
8486                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
8487                 return -EINVAL;
8488         }
8489
8490         i8xx_compute_dpll(crtc, crtc_state, NULL);
8491
8492         return 0;
8493 }
8494
8495 static int g4x_crtc_compute_clock(struct intel_crtc *crtc,
8496                                   struct intel_crtc_state *crtc_state)
8497 {
8498         struct drm_device *dev = crtc->base.dev;
8499         struct drm_i915_private *dev_priv = to_i915(dev);
8500         const struct intel_limit *limit;
8501         int refclk = 96000;
8502
8503         memset(&crtc_state->dpll_hw_state, 0,
8504                sizeof(crtc_state->dpll_hw_state));
8505
8506         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS)) {
8507                 if (intel_panel_use_ssc(dev_priv)) {
8508                         refclk = dev_priv->vbt.lvds_ssc_freq;
8509                         DRM_DEBUG_KMS("using SSC reference clock of %d kHz\n", refclk);
8510                 }
8511
8512                 if (intel_is_dual_link_lvds(dev))
8513                         limit = &intel_limits_g4x_dual_channel_lvds;
8514                 else
8515                         limit = &intel_limits_g4x_single_channel_lvds;
8516         } else if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_HDMI) ||
8517                    intel_crtc_has_type(crtc_state, INTEL_OUTPUT_ANALOG)) {
8518                 limit = &intel_limits_g4x_hdmi;
8519         } else if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_SDVO)) {
8520                 limit = &intel_limits_g4x_sdvo;
8521         } else {
8522                 /* The option is for other outputs */
8523                 limit = &intel_limits_i9xx_sdvo;
8524         }
8525
8526         if (!crtc_state->clock_set &&
8527             !g4x_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
8528                                 refclk, NULL, &crtc_state->dpll)) {
8529                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
8530                 return -EINVAL;
8531         }
8532
8533         i9xx_compute_dpll(crtc, crtc_state, NULL);
8534
8535         return 0;
8536 }
8537
8538 static int pnv_crtc_compute_clock(struct intel_crtc *crtc,
8539                                   struct intel_crtc_state *crtc_state)
8540 {
8541         struct drm_device *dev = crtc->base.dev;
8542         struct drm_i915_private *dev_priv = to_i915(dev);
8543         const struct intel_limit *limit;
8544         int refclk = 96000;
8545
8546         memset(&crtc_state->dpll_hw_state, 0,
8547                sizeof(crtc_state->dpll_hw_state));
8548
8549         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS)) {
8550                 if (intel_panel_use_ssc(dev_priv)) {
8551                         refclk = dev_priv->vbt.lvds_ssc_freq;
8552                         DRM_DEBUG_KMS("using SSC reference clock of %d kHz\n", refclk);
8553                 }
8554
8555                 limit = &intel_limits_pineview_lvds;
8556         } else {
8557                 limit = &intel_limits_pineview_sdvo;
8558         }
8559
8560         if (!crtc_state->clock_set &&
8561             !pnv_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
8562                                 refclk, NULL, &crtc_state->dpll)) {
8563                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
8564                 return -EINVAL;
8565         }
8566
8567         i9xx_compute_dpll(crtc, crtc_state, NULL);
8568
8569         return 0;
8570 }
8571
8572 static int i9xx_crtc_compute_clock(struct intel_crtc *crtc,
8573                                    struct intel_crtc_state *crtc_state)
8574 {
8575         struct drm_device *dev = crtc->base.dev;
8576         struct drm_i915_private *dev_priv = to_i915(dev);
8577         const struct intel_limit *limit;
8578         int refclk = 96000;
8579
8580         memset(&crtc_state->dpll_hw_state, 0,
8581                sizeof(crtc_state->dpll_hw_state));
8582
8583         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS)) {
8584                 if (intel_panel_use_ssc(dev_priv)) {
8585                         refclk = dev_priv->vbt.lvds_ssc_freq;
8586                         DRM_DEBUG_KMS("using SSC reference clock of %d kHz\n", refclk);
8587                 }
8588
8589                 limit = &intel_limits_i9xx_lvds;
8590         } else {
8591                 limit = &intel_limits_i9xx_sdvo;
8592         }
8593
8594         if (!crtc_state->clock_set &&
8595             !i9xx_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
8596                                  refclk, NULL, &crtc_state->dpll)) {
8597                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
8598                 return -EINVAL;
8599         }
8600
8601         i9xx_compute_dpll(crtc, crtc_state, NULL);
8602
8603         return 0;
8604 }
8605
8606 static int chv_crtc_compute_clock(struct intel_crtc *crtc,
8607                                   struct intel_crtc_state *crtc_state)
8608 {
8609         int refclk = 100000;
8610         const struct intel_limit *limit = &intel_limits_chv;
8611
8612         memset(&crtc_state->dpll_hw_state, 0,
8613                sizeof(crtc_state->dpll_hw_state));
8614
8615         if (!crtc_state->clock_set &&
8616             !chv_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
8617                                 refclk, NULL, &crtc_state->dpll)) {
8618                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
8619                 return -EINVAL;
8620         }
8621
8622         chv_compute_dpll(crtc, crtc_state);
8623
8624         return 0;
8625 }
8626
8627 static int vlv_crtc_compute_clock(struct intel_crtc *crtc,
8628                                   struct intel_crtc_state *crtc_state)
8629 {
8630         int refclk = 100000;
8631         const struct intel_limit *limit = &intel_limits_vlv;
8632
8633         memset(&crtc_state->dpll_hw_state, 0,
8634                sizeof(crtc_state->dpll_hw_state));
8635
8636         if (!crtc_state->clock_set &&
8637             !vlv_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
8638                                 refclk, NULL, &crtc_state->dpll)) {
8639                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
8640                 return -EINVAL;
8641         }
8642
8643         vlv_compute_dpll(crtc, crtc_state);
8644
8645         return 0;
8646 }
8647
8648 static void i9xx_get_pfit_config(struct intel_crtc *crtc,
8649                                  struct intel_crtc_state *pipe_config)
8650 {
8651         struct drm_device *dev = crtc->base.dev;
8652         struct drm_i915_private *dev_priv = to_i915(dev);
8653         uint32_t tmp;
8654
8655         if (INTEL_GEN(dev_priv) <= 3 &&
8656             (IS_I830(dev_priv) || !IS_MOBILE(dev_priv)))
8657                 return;
8658
8659         tmp = I915_READ(PFIT_CONTROL);
8660         if (!(tmp & PFIT_ENABLE))
8661                 return;
8662
8663         /* Check whether the pfit is attached to our pipe. */
8664         if (INTEL_INFO(dev)->gen < 4) {
8665                 if (crtc->pipe != PIPE_B)
8666                         return;
8667         } else {
8668                 if ((tmp & PFIT_PIPE_MASK) != (crtc->pipe << PFIT_PIPE_SHIFT))
8669                         return;
8670         }
8671
8672         pipe_config->gmch_pfit.control = tmp;
8673         pipe_config->gmch_pfit.pgm_ratios = I915_READ(PFIT_PGM_RATIOS);
8674 }
8675
8676 static void vlv_crtc_clock_get(struct intel_crtc *crtc,
8677                                struct intel_crtc_state *pipe_config)
8678 {
8679         struct drm_device *dev = crtc->base.dev;
8680         struct drm_i915_private *dev_priv = to_i915(dev);
8681         int pipe = pipe_config->cpu_transcoder;
8682         struct dpll clock;
8683         u32 mdiv;
8684         int refclk = 100000;
8685
8686         /* In case of DSI, DPLL will not be used */
8687         if ((pipe_config->dpll_hw_state.dpll & DPLL_VCO_ENABLE) == 0)
8688                 return;
8689
8690         mutex_lock(&dev_priv->sb_lock);
8691         mdiv = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW3(pipe));
8692         mutex_unlock(&dev_priv->sb_lock);
8693
8694         clock.m1 = (mdiv >> DPIO_M1DIV_SHIFT) & 7;
8695         clock.m2 = mdiv & DPIO_M2DIV_MASK;
8696         clock.n = (mdiv >> DPIO_N_SHIFT) & 0xf;
8697         clock.p1 = (mdiv >> DPIO_P1_SHIFT) & 7;
8698         clock.p2 = (mdiv >> DPIO_P2_SHIFT) & 0x1f;
8699
8700         pipe_config->port_clock = vlv_calc_dpll_params(refclk, &clock);
8701 }
8702
8703 static void
8704 i9xx_get_initial_plane_config(struct intel_crtc *crtc,
8705                               struct intel_initial_plane_config *plane_config)
8706 {
8707         struct drm_device *dev = crtc->base.dev;
8708         struct drm_i915_private *dev_priv = to_i915(dev);
8709         u32 val, base, offset;
8710         int pipe = crtc->pipe, plane = crtc->plane;
8711         int fourcc, pixel_format;
8712         unsigned int aligned_height;
8713         struct drm_framebuffer *fb;
8714         struct intel_framebuffer *intel_fb;
8715
8716         val = I915_READ(DSPCNTR(plane));
8717         if (!(val & DISPLAY_PLANE_ENABLE))
8718                 return;
8719
8720         intel_fb = kzalloc(sizeof(*intel_fb), GFP_KERNEL);
8721         if (!intel_fb) {
8722                 DRM_DEBUG_KMS("failed to alloc fb\n");
8723                 return;
8724         }
8725
8726         fb = &intel_fb->base;
8727
8728         if (INTEL_INFO(dev)->gen >= 4) {
8729                 if (val & DISPPLANE_TILED) {
8730                         plane_config->tiling = I915_TILING_X;
8731                         fb->modifier[0] = I915_FORMAT_MOD_X_TILED;
8732                 }
8733         }
8734
8735         pixel_format = val & DISPPLANE_PIXFORMAT_MASK;
8736         fourcc = i9xx_format_to_fourcc(pixel_format);
8737         fb->pixel_format = fourcc;
8738         fb->bits_per_pixel = drm_format_plane_cpp(fourcc, 0) * 8;
8739
8740         if (INTEL_INFO(dev)->gen >= 4) {
8741                 if (plane_config->tiling)
8742                         offset = I915_READ(DSPTILEOFF(plane));
8743                 else
8744                         offset = I915_READ(DSPLINOFF(plane));
8745                 base = I915_READ(DSPSURF(plane)) & 0xfffff000;
8746         } else {
8747                 base = I915_READ(DSPADDR(plane));
8748         }
8749         plane_config->base = base;
8750
8751         val = I915_READ(PIPESRC(pipe));
8752         fb->width = ((val >> 16) & 0xfff) + 1;
8753         fb->height = ((val >> 0) & 0xfff) + 1;
8754
8755         val = I915_READ(DSPSTRIDE(pipe));
8756         fb->pitches[0] = val & 0xffffffc0;
8757
8758         aligned_height = intel_fb_align_height(dev, fb->height,
8759                                                fb->pixel_format,
8760                                                fb->modifier[0]);
8761
8762         plane_config->size = fb->pitches[0] * aligned_height;
8763
8764         DRM_DEBUG_KMS("pipe/plane %c/%d with fb: size=%dx%d@%d, offset=%x, pitch %d, size 0x%x\n",
8765                       pipe_name(pipe), plane, fb->width, fb->height,
8766                       fb->bits_per_pixel, base, fb->pitches[0],
8767                       plane_config->size);
8768
8769         plane_config->fb = intel_fb;
8770 }
8771
8772 static void chv_crtc_clock_get(struct intel_crtc *crtc,
8773                                struct intel_crtc_state *pipe_config)
8774 {
8775         struct drm_device *dev = crtc->base.dev;
8776         struct drm_i915_private *dev_priv = to_i915(dev);
8777         int pipe = pipe_config->cpu_transcoder;
8778         enum dpio_channel port = vlv_pipe_to_channel(pipe);
8779         struct dpll clock;
8780         u32 cmn_dw13, pll_dw0, pll_dw1, pll_dw2, pll_dw3;
8781         int refclk = 100000;
8782
8783         /* In case of DSI, DPLL will not be used */
8784         if ((pipe_config->dpll_hw_state.dpll & DPLL_VCO_ENABLE) == 0)
8785                 return;
8786
8787         mutex_lock(&dev_priv->sb_lock);
8788         cmn_dw13 = vlv_dpio_read(dev_priv, pipe, CHV_CMN_DW13(port));
8789         pll_dw0 = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW0(port));
8790         pll_dw1 = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW1(port));
8791         pll_dw2 = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW2(port));
8792         pll_dw3 = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW3(port));
8793         mutex_unlock(&dev_priv->sb_lock);
8794
8795         clock.m1 = (pll_dw1 & 0x7) == DPIO_CHV_M1_DIV_BY_2 ? 2 : 0;
8796         clock.m2 = (pll_dw0 & 0xff) << 22;
8797         if (pll_dw3 & DPIO_CHV_FRAC_DIV_EN)
8798                 clock.m2 |= pll_dw2 & 0x3fffff;
8799         clock.n = (pll_dw1 >> DPIO_CHV_N_DIV_SHIFT) & 0xf;
8800         clock.p1 = (cmn_dw13 >> DPIO_CHV_P1_DIV_SHIFT) & 0x7;
8801         clock.p2 = (cmn_dw13 >> DPIO_CHV_P2_DIV_SHIFT) & 0x1f;
8802
8803         pipe_config->port_clock = chv_calc_dpll_params(refclk, &clock);
8804 }
8805
8806 static bool i9xx_get_pipe_config(struct intel_crtc *crtc,
8807                                  struct intel_crtc_state *pipe_config)
8808 {
8809         struct drm_device *dev = crtc->base.dev;
8810         struct drm_i915_private *dev_priv = to_i915(dev);
8811         enum intel_display_power_domain power_domain;
8812         uint32_t tmp;
8813         bool ret;
8814
8815         power_domain = POWER_DOMAIN_PIPE(crtc->pipe);
8816         if (!intel_display_power_get_if_enabled(dev_priv, power_domain))
8817                 return false;
8818
8819         pipe_config->cpu_transcoder = (enum transcoder) crtc->pipe;
8820         pipe_config->shared_dpll = NULL;
8821
8822         ret = false;
8823
8824         tmp = I915_READ(PIPECONF(crtc->pipe));
8825         if (!(tmp & PIPECONF_ENABLE))
8826                 goto out;
8827
8828         if (IS_G4X(dev) || IS_VALLEYVIEW(dev) || IS_CHERRYVIEW(dev)) {
8829                 switch (tmp & PIPECONF_BPC_MASK) {
8830                 case PIPECONF_6BPC:
8831                         pipe_config->pipe_bpp = 18;
8832                         break;
8833                 case PIPECONF_8BPC:
8834                         pipe_config->pipe_bpp = 24;
8835                         break;
8836                 case PIPECONF_10BPC:
8837                         pipe_config->pipe_bpp = 30;
8838                         break;
8839                 default:
8840                         break;
8841                 }
8842         }
8843
8844         if ((IS_VALLEYVIEW(dev) || IS_CHERRYVIEW(dev)) &&
8845             (tmp & PIPECONF_COLOR_RANGE_SELECT))
8846                 pipe_config->limited_color_range = true;
8847
8848         if (INTEL_INFO(dev)->gen < 4)
8849                 pipe_config->double_wide = tmp & PIPECONF_DOUBLE_WIDE;
8850
8851         intel_get_pipe_timings(crtc, pipe_config);
8852         intel_get_pipe_src_size(crtc, pipe_config);
8853
8854         i9xx_get_pfit_config(crtc, pipe_config);
8855
8856         if (INTEL_INFO(dev)->gen >= 4) {
8857                 /* No way to read it out on pipes B and C */
8858                 if (IS_CHERRYVIEW(dev) && crtc->pipe != PIPE_A)
8859                         tmp = dev_priv->chv_dpll_md[crtc->pipe];
8860                 else
8861                         tmp = I915_READ(DPLL_MD(crtc->pipe));
8862                 pipe_config->pixel_multiplier =
8863                         ((tmp & DPLL_MD_UDI_MULTIPLIER_MASK)
8864                          >> DPLL_MD_UDI_MULTIPLIER_SHIFT) + 1;
8865                 pipe_config->dpll_hw_state.dpll_md = tmp;
8866         } else if (IS_I945G(dev_priv) || IS_I945GM(dev_priv) ||
8867                    IS_G33(dev_priv)) {
8868                 tmp = I915_READ(DPLL(crtc->pipe));
8869                 pipe_config->pixel_multiplier =
8870                         ((tmp & SDVO_MULTIPLIER_MASK)
8871                          >> SDVO_MULTIPLIER_SHIFT_HIRES) + 1;
8872         } else {
8873                 /* Note that on i915G/GM the pixel multiplier is in the sdvo
8874                  * port and will be fixed up in the encoder->get_config
8875                  * function. */
8876                 pipe_config->pixel_multiplier = 1;
8877         }
8878         pipe_config->dpll_hw_state.dpll = I915_READ(DPLL(crtc->pipe));
8879         if (!IS_VALLEYVIEW(dev) && !IS_CHERRYVIEW(dev)) {
8880                 /*
8881                  * DPLL_DVO_2X_MODE must be enabled for both DPLLs
8882                  * on 830. Filter it out here so that we don't
8883                  * report errors due to that.
8884                  */
8885                 if (IS_I830(dev_priv))
8886                         pipe_config->dpll_hw_state.dpll &= ~DPLL_DVO_2X_MODE;
8887
8888                 pipe_config->dpll_hw_state.fp0 = I915_READ(FP0(crtc->pipe));
8889                 pipe_config->dpll_hw_state.fp1 = I915_READ(FP1(crtc->pipe));
8890         } else {
8891                 /* Mask out read-only status bits. */
8892                 pipe_config->dpll_hw_state.dpll &= ~(DPLL_LOCK_VLV |
8893                                                      DPLL_PORTC_READY_MASK |
8894                                                      DPLL_PORTB_READY_MASK);
8895         }
8896
8897         if (IS_CHERRYVIEW(dev))
8898                 chv_crtc_clock_get(crtc, pipe_config);
8899         else if (IS_VALLEYVIEW(dev))
8900                 vlv_crtc_clock_get(crtc, pipe_config);
8901         else
8902                 i9xx_crtc_clock_get(crtc, pipe_config);
8903
8904         /*
8905          * Normally the dotclock is filled in by the encoder .get_config()
8906          * but in case the pipe is enabled w/o any ports we need a sane
8907          * default.
8908          */
8909         pipe_config->base.adjusted_mode.crtc_clock =
8910                 pipe_config->port_clock / pipe_config->pixel_multiplier;
8911
8912         ret = true;
8913
8914 out:
8915         intel_display_power_put(dev_priv, power_domain);
8916
8917         return ret;
8918 }
8919
8920 static void ironlake_init_pch_refclk(struct drm_device *dev)
8921 {
8922         struct drm_i915_private *dev_priv = to_i915(dev);
8923         struct intel_encoder *encoder;
8924         int i;
8925         u32 val, final;
8926         bool has_lvds = false;
8927         bool has_cpu_edp = false;
8928         bool has_panel = false;
8929         bool has_ck505 = false;
8930         bool can_ssc = false;
8931         bool using_ssc_source = false;
8932
8933         /* We need to take the global config into account */
8934         for_each_intel_encoder(dev, encoder) {
8935                 switch (encoder->type) {
8936                 case INTEL_OUTPUT_LVDS:
8937                         has_panel = true;
8938                         has_lvds = true;
8939                         break;
8940                 case INTEL_OUTPUT_EDP:
8941                         has_panel = true;
8942                         if (enc_to_dig_port(&encoder->base)->port == PORT_A)
8943                                 has_cpu_edp = true;
8944                         break;
8945                 default:
8946                         break;
8947                 }
8948         }
8949
8950         if (HAS_PCH_IBX(dev_priv)) {
8951                 has_ck505 = dev_priv->vbt.display_clock_mode;
8952                 can_ssc = has_ck505;
8953         } else {
8954                 has_ck505 = false;
8955                 can_ssc = true;
8956         }
8957
8958         /* Check if any DPLLs are using the SSC source */
8959         for (i = 0; i < dev_priv->num_shared_dpll; i++) {
8960                 u32 temp = I915_READ(PCH_DPLL(i));
8961
8962                 if (!(temp & DPLL_VCO_ENABLE))
8963                         continue;
8964
8965                 if ((temp & PLL_REF_INPUT_MASK) ==
8966                     PLLB_REF_INPUT_SPREADSPECTRUMIN) {
8967                         using_ssc_source = true;
8968                         break;
8969                 }
8970         }
8971
8972         DRM_DEBUG_KMS("has_panel %d has_lvds %d has_ck505 %d using_ssc_source %d\n",
8973                       has_panel, has_lvds, has_ck505, using_ssc_source);
8974
8975         /* Ironlake: try to setup display ref clock before DPLL
8976          * enabling. This is only under driver's control after
8977          * PCH B stepping, previous chipset stepping should be
8978          * ignoring this setting.
8979          */
8980         val = I915_READ(PCH_DREF_CONTROL);
8981
8982         /* As we must carefully and slowly disable/enable each source in turn,
8983          * compute the final state we want first and check if we need to
8984          * make any changes at all.
8985          */
8986         final = val;
8987         final &= ~DREF_NONSPREAD_SOURCE_MASK;
8988         if (has_ck505)
8989                 final |= DREF_NONSPREAD_CK505_ENABLE;
8990         else
8991                 final |= DREF_NONSPREAD_SOURCE_ENABLE;
8992
8993         final &= ~DREF_SSC_SOURCE_MASK;
8994         final &= ~DREF_CPU_SOURCE_OUTPUT_MASK;
8995         final &= ~DREF_SSC1_ENABLE;
8996
8997         if (has_panel) {
8998                 final |= DREF_SSC_SOURCE_ENABLE;
8999
9000                 if (intel_panel_use_ssc(dev_priv) && can_ssc)
9001                         final |= DREF_SSC1_ENABLE;
9002
9003                 if (has_cpu_edp) {
9004                         if (intel_panel_use_ssc(dev_priv) && can_ssc)
9005                                 final |= DREF_CPU_SOURCE_OUTPUT_DOWNSPREAD;
9006                         else
9007                                 final |= DREF_CPU_SOURCE_OUTPUT_NONSPREAD;
9008                 } else
9009                         final |= DREF_CPU_SOURCE_OUTPUT_DISABLE;
9010         } else if (using_ssc_source) {
9011                 final |= DREF_SSC_SOURCE_ENABLE;
9012                 final |= DREF_SSC1_ENABLE;
9013         }
9014
9015         if (final == val)
9016                 return;
9017
9018         /* Always enable nonspread source */
9019         val &= ~DREF_NONSPREAD_SOURCE_MASK;
9020
9021         if (has_ck505)
9022                 val |= DREF_NONSPREAD_CK505_ENABLE;
9023         else
9024                 val |= DREF_NONSPREAD_SOURCE_ENABLE;
9025
9026         if (has_panel) {
9027                 val &= ~DREF_SSC_SOURCE_MASK;
9028                 val |= DREF_SSC_SOURCE_ENABLE;
9029
9030                 /* SSC must be turned on before enabling the CPU output  */
9031                 if (intel_panel_use_ssc(dev_priv) && can_ssc) {
9032                         DRM_DEBUG_KMS("Using SSC on panel\n");
9033                         val |= DREF_SSC1_ENABLE;
9034                 } else
9035                         val &= ~DREF_SSC1_ENABLE;
9036
9037                 /* Get SSC going before enabling the outputs */
9038                 I915_WRITE(PCH_DREF_CONTROL, val);
9039                 POSTING_READ(PCH_DREF_CONTROL);
9040                 udelay(200);
9041
9042                 val &= ~DREF_CPU_SOURCE_OUTPUT_MASK;
9043
9044                 /* Enable CPU source on CPU attached eDP */
9045                 if (has_cpu_edp) {
9046                         if (intel_panel_use_ssc(dev_priv) && can_ssc) {
9047                                 DRM_DEBUG_KMS("Using SSC on eDP\n");
9048                                 val |= DREF_CPU_SOURCE_OUTPUT_DOWNSPREAD;
9049                         } else
9050                                 val |= DREF_CPU_SOURCE_OUTPUT_NONSPREAD;
9051                 } else
9052                         val |= DREF_CPU_SOURCE_OUTPUT_DISABLE;
9053
9054                 I915_WRITE(PCH_DREF_CONTROL, val);
9055                 POSTING_READ(PCH_DREF_CONTROL);
9056                 udelay(200);
9057         } else {
9058                 DRM_DEBUG_KMS("Disabling CPU source output\n");
9059
9060                 val &= ~DREF_CPU_SOURCE_OUTPUT_MASK;
9061
9062                 /* Turn off CPU output */
9063                 val |= DREF_CPU_SOURCE_OUTPUT_DISABLE;
9064
9065                 I915_WRITE(PCH_DREF_CONTROL, val);
9066                 POSTING_READ(PCH_DREF_CONTROL);
9067                 udelay(200);
9068
9069                 if (!using_ssc_source) {
9070                         DRM_DEBUG_KMS("Disabling SSC source\n");
9071
9072                         /* Turn off the SSC source */
9073                         val &= ~DREF_SSC_SOURCE_MASK;
9074                         val |= DREF_SSC_SOURCE_DISABLE;
9075
9076                         /* Turn off SSC1 */
9077                         val &= ~DREF_SSC1_ENABLE;
9078
9079                         I915_WRITE(PCH_DREF_CONTROL, val);
9080                         POSTING_READ(PCH_DREF_CONTROL);
9081                         udelay(200);
9082                 }
9083         }
9084
9085         BUG_ON(val != final);
9086 }
9087
9088 static void lpt_reset_fdi_mphy(struct drm_i915_private *dev_priv)
9089 {
9090         uint32_t tmp;
9091
9092         tmp = I915_READ(SOUTH_CHICKEN2);
9093         tmp |= FDI_MPHY_IOSFSB_RESET_CTL;
9094         I915_WRITE(SOUTH_CHICKEN2, tmp);
9095
9096         if (wait_for_us(I915_READ(SOUTH_CHICKEN2) &
9097                         FDI_MPHY_IOSFSB_RESET_STATUS, 100))
9098                 DRM_ERROR("FDI mPHY reset assert timeout\n");
9099
9100         tmp = I915_READ(SOUTH_CHICKEN2);
9101         tmp &= ~FDI_MPHY_IOSFSB_RESET_CTL;
9102         I915_WRITE(SOUTH_CHICKEN2, tmp);
9103
9104         if (wait_for_us((I915_READ(SOUTH_CHICKEN2) &
9105                          FDI_MPHY_IOSFSB_RESET_STATUS) == 0, 100))
9106                 DRM_ERROR("FDI mPHY reset de-assert timeout\n");
9107 }
9108
9109 /* WaMPhyProgramming:hsw */
9110 static void lpt_program_fdi_mphy(struct drm_i915_private *dev_priv)
9111 {
9112         uint32_t tmp;
9113
9114         tmp = intel_sbi_read(dev_priv, 0x8008, SBI_MPHY);
9115         tmp &= ~(0xFF << 24);
9116         tmp |= (0x12 << 24);
9117         intel_sbi_write(dev_priv, 0x8008, tmp, SBI_MPHY);
9118
9119         tmp = intel_sbi_read(dev_priv, 0x2008, SBI_MPHY);
9120         tmp |= (1 << 11);
9121         intel_sbi_write(dev_priv, 0x2008, tmp, SBI_MPHY);
9122
9123         tmp = intel_sbi_read(dev_priv, 0x2108, SBI_MPHY);
9124         tmp |= (1 << 11);
9125         intel_sbi_write(dev_priv, 0x2108, tmp, SBI_MPHY);
9126
9127         tmp = intel_sbi_read(dev_priv, 0x206C, SBI_MPHY);
9128         tmp |= (1 << 24) | (1 << 21) | (1 << 18);
9129         intel_sbi_write(dev_priv, 0x206C, tmp, SBI_MPHY);
9130
9131         tmp = intel_sbi_read(dev_priv, 0x216C, SBI_MPHY);
9132         tmp |= (1 << 24) | (1 << 21) | (1 << 18);
9133         intel_sbi_write(dev_priv, 0x216C, tmp, SBI_MPHY);
9134
9135         tmp = intel_sbi_read(dev_priv, 0x2080, SBI_MPHY);
9136         tmp &= ~(7 << 13);
9137         tmp |= (5 << 13);
9138         intel_sbi_write(dev_priv, 0x2080, tmp, SBI_MPHY);
9139
9140         tmp = intel_sbi_read(dev_priv, 0x2180, SBI_MPHY);
9141         tmp &= ~(7 << 13);
9142         tmp |= (5 << 13);
9143         intel_sbi_write(dev_priv, 0x2180, tmp, SBI_MPHY);
9144
9145         tmp = intel_sbi_read(dev_priv, 0x208C, SBI_MPHY);
9146         tmp &= ~0xFF;
9147         tmp |= 0x1C;
9148         intel_sbi_write(dev_priv, 0x208C, tmp, SBI_MPHY);
9149
9150         tmp = intel_sbi_read(dev_priv, 0x218C, SBI_MPHY);
9151         tmp &= ~0xFF;
9152         tmp |= 0x1C;
9153         intel_sbi_write(dev_priv, 0x218C, tmp, SBI_MPHY);
9154
9155         tmp = intel_sbi_read(dev_priv, 0x2098, SBI_MPHY);
9156         tmp &= ~(0xFF << 16);
9157         tmp |= (0x1C << 16);
9158         intel_sbi_write(dev_priv, 0x2098, tmp, SBI_MPHY);
9159
9160         tmp = intel_sbi_read(dev_priv, 0x2198, SBI_MPHY);
9161         tmp &= ~(0xFF << 16);
9162         tmp |= (0x1C << 16);
9163         intel_sbi_write(dev_priv, 0x2198, tmp, SBI_MPHY);
9164
9165         tmp = intel_sbi_read(dev_priv, 0x20C4, SBI_MPHY);
9166         tmp |= (1 << 27);
9167         intel_sbi_write(dev_priv, 0x20C4, tmp, SBI_MPHY);
9168
9169         tmp = intel_sbi_read(dev_priv, 0x21C4, SBI_MPHY);
9170         tmp |= (1 << 27);
9171         intel_sbi_write(dev_priv, 0x21C4, tmp, SBI_MPHY);
9172
9173         tmp = intel_sbi_read(dev_priv, 0x20EC, SBI_MPHY);
9174         tmp &= ~(0xF << 28);
9175         tmp |= (4 << 28);
9176         intel_sbi_write(dev_priv, 0x20EC, tmp, SBI_MPHY);
9177
9178         tmp = intel_sbi_read(dev_priv, 0x21EC, SBI_MPHY);
9179         tmp &= ~(0xF << 28);
9180         tmp |= (4 << 28);
9181         intel_sbi_write(dev_priv, 0x21EC, tmp, SBI_MPHY);
9182 }
9183
9184 /* Implements 3 different sequences from BSpec chapter "Display iCLK
9185  * Programming" based on the parameters passed:
9186  * - Sequence to enable CLKOUT_DP
9187  * - Sequence to enable CLKOUT_DP without spread
9188  * - Sequence to enable CLKOUT_DP for FDI usage and configure PCH FDI I/O
9189  */
9190 static void lpt_enable_clkout_dp(struct drm_device *dev, bool with_spread,
9191                                  bool with_fdi)
9192 {
9193         struct drm_i915_private *dev_priv = to_i915(dev);
9194         uint32_t reg, tmp;
9195
9196         if (WARN(with_fdi && !with_spread, "FDI requires downspread\n"))
9197                 with_spread = true;
9198         if (WARN(HAS_PCH_LPT_LP(dev_priv) &&
9199             with_fdi, "LP PCH doesn't have FDI\n"))
9200                 with_fdi = false;
9201
9202         mutex_lock(&dev_priv->sb_lock);
9203
9204         tmp = intel_sbi_read(dev_priv, SBI_SSCCTL, SBI_ICLK);
9205         tmp &= ~SBI_SSCCTL_DISABLE;
9206         tmp |= SBI_SSCCTL_PATHALT;
9207         intel_sbi_write(dev_priv, SBI_SSCCTL, tmp, SBI_ICLK);
9208
9209         udelay(24);
9210
9211         if (with_spread) {
9212                 tmp = intel_sbi_read(dev_priv, SBI_SSCCTL, SBI_ICLK);
9213                 tmp &= ~SBI_SSCCTL_PATHALT;
9214                 intel_sbi_write(dev_priv, SBI_SSCCTL, tmp, SBI_ICLK);
9215
9216                 if (with_fdi) {
9217                         lpt_reset_fdi_mphy(dev_priv);
9218                         lpt_program_fdi_mphy(dev_priv);
9219                 }
9220         }
9221
9222         reg = HAS_PCH_LPT_LP(dev_priv) ? SBI_GEN0 : SBI_DBUFF0;
9223         tmp = intel_sbi_read(dev_priv, reg, SBI_ICLK);
9224         tmp |= SBI_GEN0_CFG_BUFFENABLE_DISABLE;
9225         intel_sbi_write(dev_priv, reg, tmp, SBI_ICLK);
9226
9227         mutex_unlock(&dev_priv->sb_lock);
9228 }
9229
9230 /* Sequence to disable CLKOUT_DP */
9231 static void lpt_disable_clkout_dp(struct drm_device *dev)
9232 {
9233         struct drm_i915_private *dev_priv = to_i915(dev);
9234         uint32_t reg, tmp;
9235
9236         mutex_lock(&dev_priv->sb_lock);
9237
9238         reg = HAS_PCH_LPT_LP(dev_priv) ? SBI_GEN0 : SBI_DBUFF0;
9239         tmp = intel_sbi_read(dev_priv, reg, SBI_ICLK);
9240         tmp &= ~SBI_GEN0_CFG_BUFFENABLE_DISABLE;
9241         intel_sbi_write(dev_priv, reg, tmp, SBI_ICLK);
9242
9243         tmp = intel_sbi_read(dev_priv, SBI_SSCCTL, SBI_ICLK);
9244         if (!(tmp & SBI_SSCCTL_DISABLE)) {
9245                 if (!(tmp & SBI_SSCCTL_PATHALT)) {
9246                         tmp |= SBI_SSCCTL_PATHALT;
9247                         intel_sbi_write(dev_priv, SBI_SSCCTL, tmp, SBI_ICLK);
9248                         udelay(32);
9249                 }
9250                 tmp |= SBI_SSCCTL_DISABLE;
9251                 intel_sbi_write(dev_priv, SBI_SSCCTL, tmp, SBI_ICLK);
9252         }
9253
9254         mutex_unlock(&dev_priv->sb_lock);
9255 }
9256
9257 #define BEND_IDX(steps) ((50 + (steps)) / 5)
9258
9259 static const uint16_t sscdivintphase[] = {
9260         [BEND_IDX( 50)] = 0x3B23,
9261         [BEND_IDX( 45)] = 0x3B23,
9262         [BEND_IDX( 40)] = 0x3C23,
9263         [BEND_IDX( 35)] = 0x3C23,
9264         [BEND_IDX( 30)] = 0x3D23,
9265         [BEND_IDX( 25)] = 0x3D23,
9266         [BEND_IDX( 20)] = 0x3E23,
9267         [BEND_IDX( 15)] = 0x3E23,
9268         [BEND_IDX( 10)] = 0x3F23,
9269         [BEND_IDX(  5)] = 0x3F23,
9270         [BEND_IDX(  0)] = 0x0025,
9271         [BEND_IDX( -5)] = 0x0025,
9272         [BEND_IDX(-10)] = 0x0125,
9273         [BEND_IDX(-15)] = 0x0125,
9274         [BEND_IDX(-20)] = 0x0225,
9275         [BEND_IDX(-25)] = 0x0225,
9276         [BEND_IDX(-30)] = 0x0325,
9277         [BEND_IDX(-35)] = 0x0325,
9278         [BEND_IDX(-40)] = 0x0425,
9279         [BEND_IDX(-45)] = 0x0425,
9280         [BEND_IDX(-50)] = 0x0525,
9281 };
9282
9283 /*
9284  * Bend CLKOUT_DP
9285  * steps -50 to 50 inclusive, in steps of 5
9286  * < 0 slow down the clock, > 0 speed up the clock, 0 == no bend (135MHz)
9287  * change in clock period = -(steps / 10) * 5.787 ps
9288  */
9289 static void lpt_bend_clkout_dp(struct drm_i915_private *dev_priv, int steps)
9290 {
9291         uint32_t tmp;
9292         int idx = BEND_IDX(steps);
9293
9294         if (WARN_ON(steps % 5 != 0))
9295                 return;
9296
9297         if (WARN_ON(idx >= ARRAY_SIZE(sscdivintphase)))
9298                 return;
9299
9300         mutex_lock(&dev_priv->sb_lock);
9301
9302         if (steps % 10 != 0)
9303                 tmp = 0xAAAAAAAB;
9304         else
9305                 tmp = 0x00000000;
9306         intel_sbi_write(dev_priv, SBI_SSCDITHPHASE, tmp, SBI_ICLK);
9307
9308         tmp = intel_sbi_read(dev_priv, SBI_SSCDIVINTPHASE, SBI_ICLK);
9309         tmp &= 0xffff0000;
9310         tmp |= sscdivintphase[idx];
9311         intel_sbi_write(dev_priv, SBI_SSCDIVINTPHASE, tmp, SBI_ICLK);
9312
9313         mutex_unlock(&dev_priv->sb_lock);
9314 }
9315
9316 #undef BEND_IDX
9317
9318 static void lpt_init_pch_refclk(struct drm_device *dev)
9319 {
9320         struct intel_encoder *encoder;
9321         bool has_vga = false;
9322
9323         for_each_intel_encoder(dev, encoder) {
9324                 switch (encoder->type) {
9325                 case INTEL_OUTPUT_ANALOG:
9326                         has_vga = true;
9327                         break;
9328                 default:
9329                         break;
9330                 }
9331         }
9332
9333         if (has_vga) {
9334                 lpt_bend_clkout_dp(to_i915(dev), 0);
9335                 lpt_enable_clkout_dp(dev, true, true);
9336         } else {
9337                 lpt_disable_clkout_dp(dev);
9338         }
9339 }
9340
9341 /*
9342  * Initialize reference clocks when the driver loads
9343  */
9344 void intel_init_pch_refclk(struct drm_device *dev)
9345 {
9346         struct drm_i915_private *dev_priv = to_i915(dev);
9347
9348         if (HAS_PCH_IBX(dev_priv) || HAS_PCH_CPT(dev_priv))
9349                 ironlake_init_pch_refclk(dev);
9350         else if (HAS_PCH_LPT(dev_priv))
9351                 lpt_init_pch_refclk(dev);
9352 }
9353
9354 static void ironlake_set_pipeconf(struct drm_crtc *crtc)
9355 {
9356         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
9357         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
9358         int pipe = intel_crtc->pipe;
9359         uint32_t val;
9360
9361         val = 0;
9362
9363         switch (intel_crtc->config->pipe_bpp) {
9364         case 18:
9365                 val |= PIPECONF_6BPC;
9366                 break;
9367         case 24:
9368                 val |= PIPECONF_8BPC;
9369                 break;
9370         case 30:
9371                 val |= PIPECONF_10BPC;
9372                 break;
9373         case 36:
9374                 val |= PIPECONF_12BPC;
9375                 break;
9376         default:
9377                 /* Case prevented by intel_choose_pipe_bpp_dither. */
9378                 BUG();
9379         }
9380
9381         if (intel_crtc->config->dither)
9382                 val |= (PIPECONF_DITHER_EN | PIPECONF_DITHER_TYPE_SP);
9383
9384         if (intel_crtc->config->base.adjusted_mode.flags & DRM_MODE_FLAG_INTERLACE)
9385                 val |= PIPECONF_INTERLACED_ILK;
9386         else
9387                 val |= PIPECONF_PROGRESSIVE;
9388
9389         if (intel_crtc->config->limited_color_range)
9390                 val |= PIPECONF_COLOR_RANGE_SELECT;
9391
9392         I915_WRITE(PIPECONF(pipe), val);
9393         POSTING_READ(PIPECONF(pipe));
9394 }
9395
9396 static void haswell_set_pipeconf(struct drm_crtc *crtc)
9397 {
9398         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
9399         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
9400         enum transcoder cpu_transcoder = intel_crtc->config->cpu_transcoder;
9401         u32 val = 0;
9402
9403         if (IS_HASWELL(dev_priv) && intel_crtc->config->dither)
9404                 val |= (PIPECONF_DITHER_EN | PIPECONF_DITHER_TYPE_SP);
9405
9406         if (intel_crtc->config->base.adjusted_mode.flags & DRM_MODE_FLAG_INTERLACE)
9407                 val |= PIPECONF_INTERLACED_ILK;
9408         else
9409                 val |= PIPECONF_PROGRESSIVE;
9410
9411         I915_WRITE(PIPECONF(cpu_transcoder), val);
9412         POSTING_READ(PIPECONF(cpu_transcoder));
9413 }
9414
9415 static void haswell_set_pipemisc(struct drm_crtc *crtc)
9416 {
9417         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
9418         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
9419
9420         if (IS_BROADWELL(dev_priv) || INTEL_INFO(dev_priv)->gen >= 9) {
9421                 u32 val = 0;
9422
9423                 switch (intel_crtc->config->pipe_bpp) {
9424                 case 18:
9425                         val |= PIPEMISC_DITHER_6_BPC;
9426                         break;
9427                 case 24:
9428                         val |= PIPEMISC_DITHER_8_BPC;
9429                         break;
9430                 case 30:
9431                         val |= PIPEMISC_DITHER_10_BPC;
9432                         break;
9433                 case 36:
9434                         val |= PIPEMISC_DITHER_12_BPC;
9435                         break;
9436                 default:
9437                         /* Case prevented by pipe_config_set_bpp. */
9438                         BUG();
9439                 }
9440
9441                 if (intel_crtc->config->dither)
9442                         val |= PIPEMISC_DITHER_ENABLE | PIPEMISC_DITHER_TYPE_SP;
9443
9444                 I915_WRITE(PIPEMISC(intel_crtc->pipe), val);
9445         }
9446 }
9447
9448 int ironlake_get_lanes_required(int target_clock, int link_bw, int bpp)
9449 {
9450         /*
9451          * Account for spread spectrum to avoid
9452          * oversubscribing the link. Max center spread
9453          * is 2.5%; use 5% for safety's sake.
9454          */
9455         u32 bps = target_clock * bpp * 21 / 20;
9456         return DIV_ROUND_UP(bps, link_bw * 8);
9457 }
9458
9459 static bool ironlake_needs_fb_cb_tune(struct dpll *dpll, int factor)
9460 {
9461         return i9xx_dpll_compute_m(dpll) < factor * dpll->n;
9462 }
9463
9464 static void ironlake_compute_dpll(struct intel_crtc *intel_crtc,
9465                                   struct intel_crtc_state *crtc_state,
9466                                   struct dpll *reduced_clock)
9467 {
9468         struct drm_crtc *crtc = &intel_crtc->base;
9469         struct drm_device *dev = crtc->dev;
9470         struct drm_i915_private *dev_priv = to_i915(dev);
9471         u32 dpll, fp, fp2;
9472         int factor;
9473
9474         /* Enable autotuning of the PLL clock (if permissible) */
9475         factor = 21;
9476         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS)) {
9477                 if ((intel_panel_use_ssc(dev_priv) &&
9478                      dev_priv->vbt.lvds_ssc_freq == 100000) ||
9479                     (HAS_PCH_IBX(dev_priv) && intel_is_dual_link_lvds(dev)))
9480                         factor = 25;
9481         } else if (crtc_state->sdvo_tv_clock)
9482                 factor = 20;
9483
9484         fp = i9xx_dpll_compute_fp(&crtc_state->dpll);
9485
9486         if (ironlake_needs_fb_cb_tune(&crtc_state->dpll, factor))
9487                 fp |= FP_CB_TUNE;
9488
9489         if (reduced_clock) {
9490                 fp2 = i9xx_dpll_compute_fp(reduced_clock);
9491
9492                 if (reduced_clock->m < factor * reduced_clock->n)
9493                         fp2 |= FP_CB_TUNE;
9494         } else {
9495                 fp2 = fp;
9496         }
9497
9498         dpll = 0;
9499
9500         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS))
9501                 dpll |= DPLLB_MODE_LVDS;
9502         else
9503                 dpll |= DPLLB_MODE_DAC_SERIAL;
9504
9505         dpll |= (crtc_state->pixel_multiplier - 1)
9506                 << PLL_REF_SDVO_HDMI_MULTIPLIER_SHIFT;
9507
9508         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_SDVO) ||
9509             intel_crtc_has_type(crtc_state, INTEL_OUTPUT_HDMI))
9510                 dpll |= DPLL_SDVO_HIGH_SPEED;
9511
9512         if (intel_crtc_has_dp_encoder(crtc_state))
9513                 dpll |= DPLL_SDVO_HIGH_SPEED;
9514
9515         /*
9516          * The high speed IO clock is only really required for
9517          * SDVO/HDMI/DP, but we also enable it for CRT to make it
9518          * possible to share the DPLL between CRT and HDMI. Enabling
9519          * the clock needlessly does no real harm, except use up a
9520          * bit of power potentially.
9521          *
9522          * We'll limit this to IVB with 3 pipes, since it has only two
9523          * DPLLs and so DPLL sharing is the only way to get three pipes
9524          * driving PCH ports at the same time. On SNB we could do this,
9525          * and potentially avoid enabling the second DPLL, but it's not
9526          * clear if it''s a win or loss power wise. No point in doing
9527          * this on ILK at all since it has a fixed DPLL<->pipe mapping.
9528          */
9529         if (INTEL_INFO(dev_priv)->num_pipes == 3 &&
9530             intel_crtc_has_type(crtc_state, INTEL_OUTPUT_ANALOG))
9531                 dpll |= DPLL_SDVO_HIGH_SPEED;
9532
9533         /* compute bitmask from p1 value */
9534         dpll |= (1 << (crtc_state->dpll.p1 - 1)) << DPLL_FPA01_P1_POST_DIV_SHIFT;
9535         /* also FPA1 */
9536         dpll |= (1 << (crtc_state->dpll.p1 - 1)) << DPLL_FPA1_P1_POST_DIV_SHIFT;
9537
9538         switch (crtc_state->dpll.p2) {
9539         case 5:
9540                 dpll |= DPLL_DAC_SERIAL_P2_CLOCK_DIV_5;
9541                 break;
9542         case 7:
9543                 dpll |= DPLLB_LVDS_P2_CLOCK_DIV_7;
9544                 break;
9545         case 10:
9546                 dpll |= DPLL_DAC_SERIAL_P2_CLOCK_DIV_10;
9547                 break;
9548         case 14:
9549                 dpll |= DPLLB_LVDS_P2_CLOCK_DIV_14;
9550                 break;
9551         }
9552
9553         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS) &&
9554             intel_panel_use_ssc(dev_priv))
9555                 dpll |= PLLB_REF_INPUT_SPREADSPECTRUMIN;
9556         else
9557                 dpll |= PLL_REF_INPUT_DREFCLK;
9558
9559         dpll |= DPLL_VCO_ENABLE;
9560
9561         crtc_state->dpll_hw_state.dpll = dpll;
9562         crtc_state->dpll_hw_state.fp0 = fp;
9563         crtc_state->dpll_hw_state.fp1 = fp2;
9564 }
9565
9566 static int ironlake_crtc_compute_clock(struct intel_crtc *crtc,
9567                                        struct intel_crtc_state *crtc_state)
9568 {
9569         struct drm_device *dev = crtc->base.dev;
9570         struct drm_i915_private *dev_priv = to_i915(dev);
9571         struct dpll reduced_clock;
9572         bool has_reduced_clock = false;
9573         struct intel_shared_dpll *pll;
9574         const struct intel_limit *limit;
9575         int refclk = 120000;
9576
9577         memset(&crtc_state->dpll_hw_state, 0,
9578                sizeof(crtc_state->dpll_hw_state));
9579
9580         crtc->lowfreq_avail = false;
9581
9582         /* CPU eDP is the only output that doesn't need a PCH PLL of its own. */
9583         if (!crtc_state->has_pch_encoder)
9584                 return 0;
9585
9586         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS)) {
9587                 if (intel_panel_use_ssc(dev_priv)) {
9588                         DRM_DEBUG_KMS("using SSC reference clock of %d kHz\n",
9589                                       dev_priv->vbt.lvds_ssc_freq);
9590                         refclk = dev_priv->vbt.lvds_ssc_freq;
9591                 }
9592
9593                 if (intel_is_dual_link_lvds(dev)) {
9594                         if (refclk == 100000)
9595                                 limit = &intel_limits_ironlake_dual_lvds_100m;
9596                         else
9597                                 limit = &intel_limits_ironlake_dual_lvds;
9598                 } else {
9599                         if (refclk == 100000)
9600                                 limit = &intel_limits_ironlake_single_lvds_100m;
9601                         else
9602                                 limit = &intel_limits_ironlake_single_lvds;
9603                 }
9604         } else {
9605                 limit = &intel_limits_ironlake_dac;
9606         }
9607
9608         if (!crtc_state->clock_set &&
9609             !g4x_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
9610                                 refclk, NULL, &crtc_state->dpll)) {
9611                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
9612                 return -EINVAL;
9613         }
9614
9615         ironlake_compute_dpll(crtc, crtc_state,
9616                               has_reduced_clock ? &reduced_clock : NULL);
9617
9618         pll = intel_get_shared_dpll(crtc, crtc_state, NULL);
9619         if (pll == NULL) {
9620                 DRM_DEBUG_DRIVER("failed to find PLL for pipe %c\n",
9621                                  pipe_name(crtc->pipe));
9622                 return -EINVAL;
9623         }
9624
9625         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS) &&
9626             has_reduced_clock)
9627                 crtc->lowfreq_avail = true;
9628
9629         return 0;
9630 }
9631
9632 static void intel_pch_transcoder_get_m_n(struct intel_crtc *crtc,
9633                                          struct intel_link_m_n *m_n)
9634 {
9635         struct drm_device *dev = crtc->base.dev;
9636         struct drm_i915_private *dev_priv = to_i915(dev);
9637         enum pipe pipe = crtc->pipe;
9638
9639         m_n->link_m = I915_READ(PCH_TRANS_LINK_M1(pipe));
9640         m_n->link_n = I915_READ(PCH_TRANS_LINK_N1(pipe));
9641         m_n->gmch_m = I915_READ(PCH_TRANS_DATA_M1(pipe))
9642                 & ~TU_SIZE_MASK;
9643         m_n->gmch_n = I915_READ(PCH_TRANS_DATA_N1(pipe));
9644         m_n->tu = ((I915_READ(PCH_TRANS_DATA_M1(pipe))
9645                     & TU_SIZE_MASK) >> TU_SIZE_SHIFT) + 1;
9646 }
9647
9648 static void intel_cpu_transcoder_get_m_n(struct intel_crtc *crtc,
9649                                          enum transcoder transcoder,
9650                                          struct intel_link_m_n *m_n,
9651                                          struct intel_link_m_n *m2_n2)
9652 {
9653         struct drm_device *dev = crtc->base.dev;
9654         struct drm_i915_private *dev_priv = to_i915(dev);
9655         enum pipe pipe = crtc->pipe;
9656
9657         if (INTEL_INFO(dev)->gen >= 5) {
9658                 m_n->link_m = I915_READ(PIPE_LINK_M1(transcoder));
9659                 m_n->link_n = I915_READ(PIPE_LINK_N1(transcoder));
9660                 m_n->gmch_m = I915_READ(PIPE_DATA_M1(transcoder))
9661                         & ~TU_SIZE_MASK;
9662                 m_n->gmch_n = I915_READ(PIPE_DATA_N1(transcoder));
9663                 m_n->tu = ((I915_READ(PIPE_DATA_M1(transcoder))
9664                             & TU_SIZE_MASK) >> TU_SIZE_SHIFT) + 1;
9665                 /* Read M2_N2 registers only for gen < 8 (M2_N2 available for
9666                  * gen < 8) and if DRRS is supported (to make sure the
9667                  * registers are not unnecessarily read).
9668                  */
9669                 if (m2_n2 && INTEL_INFO(dev)->gen < 8 &&
9670                         crtc->config->has_drrs) {
9671                         m2_n2->link_m = I915_READ(PIPE_LINK_M2(transcoder));
9672                         m2_n2->link_n = I915_READ(PIPE_LINK_N2(transcoder));
9673                         m2_n2->gmch_m = I915_READ(PIPE_DATA_M2(transcoder))
9674                                         & ~TU_SIZE_MASK;
9675                         m2_n2->gmch_n = I915_READ(PIPE_DATA_N2(transcoder));
9676                         m2_n2->tu = ((I915_READ(PIPE_DATA_M2(transcoder))
9677                                         & TU_SIZE_MASK) >> TU_SIZE_SHIFT) + 1;
9678                 }
9679         } else {
9680                 m_n->link_m = I915_READ(PIPE_LINK_M_G4X(pipe));
9681                 m_n->link_n = I915_READ(PIPE_LINK_N_G4X(pipe));
9682                 m_n->gmch_m = I915_READ(PIPE_DATA_M_G4X(pipe))
9683                         & ~TU_SIZE_MASK;
9684                 m_n->gmch_n = I915_READ(PIPE_DATA_N_G4X(pipe));
9685                 m_n->tu = ((I915_READ(PIPE_DATA_M_G4X(pipe))
9686                             & TU_SIZE_MASK) >> TU_SIZE_SHIFT) + 1;
9687         }
9688 }
9689
9690 void intel_dp_get_m_n(struct intel_crtc *crtc,
9691                       struct intel_crtc_state *pipe_config)
9692 {
9693         if (pipe_config->has_pch_encoder)
9694                 intel_pch_transcoder_get_m_n(crtc, &pipe_config->dp_m_n);
9695         else
9696                 intel_cpu_transcoder_get_m_n(crtc, pipe_config->cpu_transcoder,
9697                                              &pipe_config->dp_m_n,
9698                                              &pipe_config->dp_m2_n2);
9699 }
9700
9701 static void ironlake_get_fdi_m_n_config(struct intel_crtc *crtc,
9702                                         struct intel_crtc_state *pipe_config)
9703 {
9704         intel_cpu_transcoder_get_m_n(crtc, pipe_config->cpu_transcoder,
9705                                      &pipe_config->fdi_m_n, NULL);
9706 }
9707
9708 static void skylake_get_pfit_config(struct intel_crtc *crtc,
9709                                     struct intel_crtc_state *pipe_config)
9710 {
9711         struct drm_device *dev = crtc->base.dev;
9712         struct drm_i915_private *dev_priv = to_i915(dev);
9713         struct intel_crtc_scaler_state *scaler_state = &pipe_config->scaler_state;
9714         uint32_t ps_ctrl = 0;
9715         int id = -1;
9716         int i;
9717
9718         /* find scaler attached to this pipe */
9719         for (i = 0; i < crtc->num_scalers; i++) {
9720                 ps_ctrl = I915_READ(SKL_PS_CTRL(crtc->pipe, i));
9721                 if (ps_ctrl & PS_SCALER_EN && !(ps_ctrl & PS_PLANE_SEL_MASK)) {
9722                         id = i;
9723                         pipe_config->pch_pfit.enabled = true;
9724                         pipe_config->pch_pfit.pos = I915_READ(SKL_PS_WIN_POS(crtc->pipe, i));
9725                         pipe_config->pch_pfit.size = I915_READ(SKL_PS_WIN_SZ(crtc->pipe, i));
9726                         break;
9727                 }
9728         }
9729
9730         scaler_state->scaler_id = id;
9731         if (id >= 0) {
9732                 scaler_state->scaler_users |= (1 << SKL_CRTC_INDEX);
9733         } else {
9734                 scaler_state->scaler_users &= ~(1 << SKL_CRTC_INDEX);
9735         }
9736 }
9737
9738 static void
9739 skylake_get_initial_plane_config(struct intel_crtc *crtc,
9740                                  struct intel_initial_plane_config *plane_config)
9741 {
9742         struct drm_device *dev = crtc->base.dev;
9743         struct drm_i915_private *dev_priv = to_i915(dev);
9744         u32 val, base, offset, stride_mult, tiling;
9745         int pipe = crtc->pipe;
9746         int fourcc, pixel_format;
9747         unsigned int aligned_height;
9748         struct drm_framebuffer *fb;
9749         struct intel_framebuffer *intel_fb;
9750
9751         intel_fb = kzalloc(sizeof(*intel_fb), GFP_KERNEL);
9752         if (!intel_fb) {
9753                 DRM_DEBUG_KMS("failed to alloc fb\n");
9754                 return;
9755         }
9756
9757         fb = &intel_fb->base;
9758
9759         val = I915_READ(PLANE_CTL(pipe, 0));
9760         if (!(val & PLANE_CTL_ENABLE))
9761                 goto error;
9762
9763         pixel_format = val & PLANE_CTL_FORMAT_MASK;
9764         fourcc = skl_format_to_fourcc(pixel_format,
9765                                       val & PLANE_CTL_ORDER_RGBX,
9766                                       val & PLANE_CTL_ALPHA_MASK);
9767         fb->pixel_format = fourcc;
9768         fb->bits_per_pixel = drm_format_plane_cpp(fourcc, 0) * 8;
9769
9770         tiling = val & PLANE_CTL_TILED_MASK;
9771         switch (tiling) {
9772         case PLANE_CTL_TILED_LINEAR:
9773                 fb->modifier[0] = DRM_FORMAT_MOD_NONE;
9774                 break;
9775         case PLANE_CTL_TILED_X:
9776                 plane_config->tiling = I915_TILING_X;
9777                 fb->modifier[0] = I915_FORMAT_MOD_X_TILED;
9778                 break;
9779         case PLANE_CTL_TILED_Y:
9780                 fb->modifier[0] = I915_FORMAT_MOD_Y_TILED;
9781                 break;
9782         case PLANE_CTL_TILED_YF:
9783                 fb->modifier[0] = I915_FORMAT_MOD_Yf_TILED;
9784                 break;
9785         default:
9786                 MISSING_CASE(tiling);
9787                 goto error;
9788         }
9789
9790         base = I915_READ(PLANE_SURF(pipe, 0)) & 0xfffff000;
9791         plane_config->base = base;
9792
9793         offset = I915_READ(PLANE_OFFSET(pipe, 0));
9794
9795         val = I915_READ(PLANE_SIZE(pipe, 0));
9796         fb->height = ((val >> 16) & 0xfff) + 1;
9797         fb->width = ((val >> 0) & 0x1fff) + 1;
9798
9799         val = I915_READ(PLANE_STRIDE(pipe, 0));
9800         stride_mult = intel_fb_stride_alignment(dev_priv, fb->modifier[0],
9801                                                 fb->pixel_format);
9802         fb->pitches[0] = (val & 0x3ff) * stride_mult;
9803
9804         aligned_height = intel_fb_align_height(dev, fb->height,
9805                                                fb->pixel_format,
9806                                                fb->modifier[0]);
9807
9808         plane_config->size = fb->pitches[0] * aligned_height;
9809
9810         DRM_DEBUG_KMS("pipe %c with fb: size=%dx%d@%d, offset=%x, pitch %d, size 0x%x\n",
9811                       pipe_name(pipe), fb->width, fb->height,
9812                       fb->bits_per_pixel, base, fb->pitches[0],
9813                       plane_config->size);
9814
9815         plane_config->fb = intel_fb;
9816         return;
9817
9818 error:
9819         kfree(intel_fb);
9820 }
9821
9822 static void ironlake_get_pfit_config(struct intel_crtc *crtc,
9823                                      struct intel_crtc_state *pipe_config)
9824 {
9825         struct drm_device *dev = crtc->base.dev;
9826         struct drm_i915_private *dev_priv = to_i915(dev);
9827         uint32_t tmp;
9828
9829         tmp = I915_READ(PF_CTL(crtc->pipe));
9830
9831         if (tmp & PF_ENABLE) {
9832                 pipe_config->pch_pfit.enabled = true;
9833                 pipe_config->pch_pfit.pos = I915_READ(PF_WIN_POS(crtc->pipe));
9834                 pipe_config->pch_pfit.size = I915_READ(PF_WIN_SZ(crtc->pipe));
9835
9836                 /* We currently do not free assignements of panel fitters on
9837                  * ivb/hsw (since we don't use the higher upscaling modes which
9838                  * differentiates them) so just WARN about this case for now. */
9839                 if (IS_GEN7(dev)) {
9840                         WARN_ON((tmp & PF_PIPE_SEL_MASK_IVB) !=
9841                                 PF_PIPE_SEL_IVB(crtc->pipe));
9842                 }
9843         }
9844 }
9845
9846 static void
9847 ironlake_get_initial_plane_config(struct intel_crtc *crtc,
9848                                   struct intel_initial_plane_config *plane_config)
9849 {
9850         struct drm_device *dev = crtc->base.dev;
9851         struct drm_i915_private *dev_priv = to_i915(dev);
9852         u32 val, base, offset;
9853         int pipe = crtc->pipe;
9854         int fourcc, pixel_format;
9855         unsigned int aligned_height;
9856         struct drm_framebuffer *fb;
9857         struct intel_framebuffer *intel_fb;
9858
9859         val = I915_READ(DSPCNTR(pipe));
9860         if (!(val & DISPLAY_PLANE_ENABLE))
9861                 return;
9862
9863         intel_fb = kzalloc(sizeof(*intel_fb), GFP_KERNEL);
9864         if (!intel_fb) {
9865                 DRM_DEBUG_KMS("failed to alloc fb\n");
9866                 return;
9867         }
9868
9869         fb = &intel_fb->base;
9870
9871         if (INTEL_INFO(dev)->gen >= 4) {
9872                 if (val & DISPPLANE_TILED) {
9873                         plane_config->tiling = I915_TILING_X;
9874                         fb->modifier[0] = I915_FORMAT_MOD_X_TILED;
9875                 }
9876         }
9877
9878         pixel_format = val & DISPPLANE_PIXFORMAT_MASK;
9879         fourcc = i9xx_format_to_fourcc(pixel_format);
9880         fb->pixel_format = fourcc;
9881         fb->bits_per_pixel = drm_format_plane_cpp(fourcc, 0) * 8;
9882
9883         base = I915_READ(DSPSURF(pipe)) & 0xfffff000;
9884         if (IS_HASWELL(dev) || IS_BROADWELL(dev)) {
9885                 offset = I915_READ(DSPOFFSET(pipe));
9886         } else {
9887                 if (plane_config->tiling)
9888                         offset = I915_READ(DSPTILEOFF(pipe));
9889                 else
9890                         offset = I915_READ(DSPLINOFF(pipe));
9891         }
9892         plane_config->base = base;
9893
9894         val = I915_READ(PIPESRC(pipe));
9895         fb->width = ((val >> 16) & 0xfff) + 1;
9896         fb->height = ((val >> 0) & 0xfff) + 1;
9897
9898         val = I915_READ(DSPSTRIDE(pipe));
9899         fb->pitches[0] = val & 0xffffffc0;
9900
9901         aligned_height = intel_fb_align_height(dev, fb->height,
9902                                                fb->pixel_format,
9903                                                fb->modifier[0]);
9904
9905         plane_config->size = fb->pitches[0] * aligned_height;
9906
9907         DRM_DEBUG_KMS("pipe %c with fb: size=%dx%d@%d, offset=%x, pitch %d, size 0x%x\n",
9908                       pipe_name(pipe), fb->width, fb->height,
9909                       fb->bits_per_pixel, base, fb->pitches[0],
9910                       plane_config->size);
9911
9912         plane_config->fb = intel_fb;
9913 }
9914
9915 static bool ironlake_get_pipe_config(struct intel_crtc *crtc,
9916                                      struct intel_crtc_state *pipe_config)
9917 {
9918         struct drm_device *dev = crtc->base.dev;
9919         struct drm_i915_private *dev_priv = to_i915(dev);
9920         enum intel_display_power_domain power_domain;
9921         uint32_t tmp;
9922         bool ret;
9923
9924         power_domain = POWER_DOMAIN_PIPE(crtc->pipe);
9925         if (!intel_display_power_get_if_enabled(dev_priv, power_domain))
9926                 return false;
9927
9928         pipe_config->cpu_transcoder = (enum transcoder) crtc->pipe;
9929         pipe_config->shared_dpll = NULL;
9930
9931         ret = false;
9932         tmp = I915_READ(PIPECONF(crtc->pipe));
9933         if (!(tmp & PIPECONF_ENABLE))
9934                 goto out;
9935
9936         switch (tmp & PIPECONF_BPC_MASK) {
9937         case PIPECONF_6BPC:
9938                 pipe_config->pipe_bpp = 18;
9939                 break;
9940         case PIPECONF_8BPC:
9941                 pipe_config->pipe_bpp = 24;
9942                 break;
9943         case PIPECONF_10BPC:
9944                 pipe_config->pipe_bpp = 30;
9945                 break;
9946         case PIPECONF_12BPC:
9947                 pipe_config->pipe_bpp = 36;
9948                 break;
9949         default:
9950                 break;
9951         }
9952
9953         if (tmp & PIPECONF_COLOR_RANGE_SELECT)
9954                 pipe_config->limited_color_range = true;
9955
9956         if (I915_READ(PCH_TRANSCONF(crtc->pipe)) & TRANS_ENABLE) {
9957                 struct intel_shared_dpll *pll;
9958                 enum intel_dpll_id pll_id;
9959
9960                 pipe_config->has_pch_encoder = true;
9961
9962                 tmp = I915_READ(FDI_RX_CTL(crtc->pipe));
9963                 pipe_config->fdi_lanes = ((FDI_DP_PORT_WIDTH_MASK & tmp) >>
9964                                           FDI_DP_PORT_WIDTH_SHIFT) + 1;
9965
9966                 ironlake_get_fdi_m_n_config(crtc, pipe_config);
9967
9968                 if (HAS_PCH_IBX(dev_priv)) {
9969                         /*
9970                          * The pipe->pch transcoder and pch transcoder->pll
9971                          * mapping is fixed.
9972                          */
9973                         pll_id = (enum intel_dpll_id) crtc->pipe;
9974                 } else {
9975                         tmp = I915_READ(PCH_DPLL_SEL);
9976                         if (tmp & TRANS_DPLLB_SEL(crtc->pipe))
9977                                 pll_id = DPLL_ID_PCH_PLL_B;
9978                         else
9979                                 pll_id= DPLL_ID_PCH_PLL_A;
9980                 }
9981
9982                 pipe_config->shared_dpll =
9983                         intel_get_shared_dpll_by_id(dev_priv, pll_id);
9984                 pll = pipe_config->shared_dpll;
9985
9986                 WARN_ON(!pll->funcs.get_hw_state(dev_priv, pll,
9987                                                  &pipe_config->dpll_hw_state));
9988
9989                 tmp = pipe_config->dpll_hw_state.dpll;
9990                 pipe_config->pixel_multiplier =
9991                         ((tmp & PLL_REF_SDVO_HDMI_MULTIPLIER_MASK)
9992                          >> PLL_REF_SDVO_HDMI_MULTIPLIER_SHIFT) + 1;
9993
9994                 ironlake_pch_clock_get(crtc, pipe_config);
9995         } else {
9996                 pipe_config->pixel_multiplier = 1;
9997         }
9998
9999         intel_get_pipe_timings(crtc, pipe_config);
10000         intel_get_pipe_src_size(crtc, pipe_config);
10001
10002         ironlake_get_pfit_config(crtc, pipe_config);
10003
10004         ret = true;
10005
10006 out:
10007         intel_display_power_put(dev_priv, power_domain);
10008
10009         return ret;
10010 }
10011
10012 static void assert_can_disable_lcpll(struct drm_i915_private *dev_priv)
10013 {
10014         struct drm_device *dev = &dev_priv->drm;
10015         struct intel_crtc *crtc;
10016
10017         for_each_intel_crtc(dev, crtc)
10018                 I915_STATE_WARN(crtc->active, "CRTC for pipe %c enabled\n",
10019                      pipe_name(crtc->pipe));
10020
10021         I915_STATE_WARN(I915_READ(HSW_PWR_WELL_DRIVER), "Power well on\n");
10022         I915_STATE_WARN(I915_READ(SPLL_CTL) & SPLL_PLL_ENABLE, "SPLL enabled\n");
10023         I915_STATE_WARN(I915_READ(WRPLL_CTL(0)) & WRPLL_PLL_ENABLE, "WRPLL1 enabled\n");
10024         I915_STATE_WARN(I915_READ(WRPLL_CTL(1)) & WRPLL_PLL_ENABLE, "WRPLL2 enabled\n");
10025         I915_STATE_WARN(I915_READ(PP_STATUS(0)) & PP_ON, "Panel power on\n");
10026         I915_STATE_WARN(I915_READ(BLC_PWM_CPU_CTL2) & BLM_PWM_ENABLE,
10027              "CPU PWM1 enabled\n");
10028         if (IS_HASWELL(dev))
10029                 I915_STATE_WARN(I915_READ(HSW_BLC_PWM2_CTL) & BLM_PWM_ENABLE,
10030                      "CPU PWM2 enabled\n");
10031         I915_STATE_WARN(I915_READ(BLC_PWM_PCH_CTL1) & BLM_PCH_PWM_ENABLE,
10032              "PCH PWM1 enabled\n");
10033         I915_STATE_WARN(I915_READ(UTIL_PIN_CTL) & UTIL_PIN_ENABLE,
10034              "Utility pin enabled\n");
10035         I915_STATE_WARN(I915_READ(PCH_GTC_CTL) & PCH_GTC_ENABLE, "PCH GTC enabled\n");
10036
10037         /*
10038          * In theory we can still leave IRQs enabled, as long as only the HPD
10039          * interrupts remain enabled. We used to check for that, but since it's
10040          * gen-specific and since we only disable LCPLL after we fully disable
10041          * the interrupts, the check below should be enough.
10042          */
10043         I915_STATE_WARN(intel_irqs_enabled(dev_priv), "IRQs enabled\n");
10044 }
10045
10046 static uint32_t hsw_read_dcomp(struct drm_i915_private *dev_priv)
10047 {
10048         struct drm_device *dev = &dev_priv->drm;
10049
10050         if (IS_HASWELL(dev))
10051                 return I915_READ(D_COMP_HSW);
10052         else
10053                 return I915_READ(D_COMP_BDW);
10054 }
10055
10056 static void hsw_write_dcomp(struct drm_i915_private *dev_priv, uint32_t val)
10057 {
10058         struct drm_device *dev = &dev_priv->drm;
10059
10060         if (IS_HASWELL(dev)) {
10061                 mutex_lock(&dev_priv->rps.hw_lock);
10062                 if (sandybridge_pcode_write(dev_priv, GEN6_PCODE_WRITE_D_COMP,
10063                                             val))
10064                         DRM_DEBUG_KMS("Failed to write to D_COMP\n");
10065                 mutex_unlock(&dev_priv->rps.hw_lock);
10066         } else {
10067                 I915_WRITE(D_COMP_BDW, val);
10068                 POSTING_READ(D_COMP_BDW);
10069         }
10070 }
10071
10072 /*
10073  * This function implements pieces of two sequences from BSpec:
10074  * - Sequence for display software to disable LCPLL
10075  * - Sequence for display software to allow package C8+
10076  * The steps implemented here are just the steps that actually touch the LCPLL
10077  * register. Callers should take care of disabling all the display engine
10078  * functions, doing the mode unset, fixing interrupts, etc.
10079  */
10080 static void hsw_disable_lcpll(struct drm_i915_private *dev_priv,
10081                               bool switch_to_fclk, bool allow_power_down)
10082 {
10083         uint32_t val;
10084
10085         assert_can_disable_lcpll(dev_priv);
10086
10087         val = I915_READ(LCPLL_CTL);
10088
10089         if (switch_to_fclk) {
10090                 val |= LCPLL_CD_SOURCE_FCLK;
10091                 I915_WRITE(LCPLL_CTL, val);
10092
10093                 if (wait_for_us(I915_READ(LCPLL_CTL) &
10094                                 LCPLL_CD_SOURCE_FCLK_DONE, 1))
10095                         DRM_ERROR("Switching to FCLK failed\n");
10096
10097                 val = I915_READ(LCPLL_CTL);
10098         }
10099
10100         val |= LCPLL_PLL_DISABLE;
10101         I915_WRITE(LCPLL_CTL, val);
10102         POSTING_READ(LCPLL_CTL);
10103
10104         if (intel_wait_for_register(dev_priv, LCPLL_CTL, LCPLL_PLL_LOCK, 0, 1))
10105                 DRM_ERROR("LCPLL still locked\n");
10106
10107         val = hsw_read_dcomp(dev_priv);
10108         val |= D_COMP_COMP_DISABLE;
10109         hsw_write_dcomp(dev_priv, val);
10110         ndelay(100);
10111
10112         if (wait_for((hsw_read_dcomp(dev_priv) & D_COMP_RCOMP_IN_PROGRESS) == 0,
10113                      1))
10114                 DRM_ERROR("D_COMP RCOMP still in progress\n");
10115
10116         if (allow_power_down) {
10117                 val = I915_READ(LCPLL_CTL);
10118                 val |= LCPLL_POWER_DOWN_ALLOW;
10119                 I915_WRITE(LCPLL_CTL, val);
10120                 POSTING_READ(LCPLL_CTL);
10121         }
10122 }
10123
10124 /*
10125  * Fully restores LCPLL, disallowing power down and switching back to LCPLL
10126  * source.
10127  */
10128 static void hsw_restore_lcpll(struct drm_i915_private *dev_priv)
10129 {
10130         uint32_t val;
10131
10132         val = I915_READ(LCPLL_CTL);
10133
10134         if ((val & (LCPLL_PLL_LOCK | LCPLL_PLL_DISABLE | LCPLL_CD_SOURCE_FCLK |
10135                     LCPLL_POWER_DOWN_ALLOW)) == LCPLL_PLL_LOCK)
10136                 return;
10137
10138         /*
10139          * Make sure we're not on PC8 state before disabling PC8, otherwise
10140          * we'll hang the machine. To prevent PC8 state, just enable force_wake.
10141          */
10142         intel_uncore_forcewake_get(dev_priv, FORCEWAKE_ALL);
10143
10144         if (val & LCPLL_POWER_DOWN_ALLOW) {
10145                 val &= ~LCPLL_POWER_DOWN_ALLOW;
10146                 I915_WRITE(LCPLL_CTL, val);
10147                 POSTING_READ(LCPLL_CTL);
10148         }
10149
10150         val = hsw_read_dcomp(dev_priv);
10151         val |= D_COMP_COMP_FORCE;
10152         val &= ~D_COMP_COMP_DISABLE;
10153         hsw_write_dcomp(dev_priv, val);
10154
10155         val = I915_READ(LCPLL_CTL);
10156         val &= ~LCPLL_PLL_DISABLE;
10157         I915_WRITE(LCPLL_CTL, val);
10158
10159         if (intel_wait_for_register(dev_priv,
10160                                     LCPLL_CTL, LCPLL_PLL_LOCK, LCPLL_PLL_LOCK,
10161                                     5))
10162                 DRM_ERROR("LCPLL not locked yet\n");
10163
10164         if (val & LCPLL_CD_SOURCE_FCLK) {
10165                 val = I915_READ(LCPLL_CTL);
10166                 val &= ~LCPLL_CD_SOURCE_FCLK;
10167                 I915_WRITE(LCPLL_CTL, val);
10168
10169                 if (wait_for_us((I915_READ(LCPLL_CTL) &
10170                                  LCPLL_CD_SOURCE_FCLK_DONE) == 0, 1))
10171                         DRM_ERROR("Switching back to LCPLL failed\n");
10172         }
10173
10174         intel_uncore_forcewake_put(dev_priv, FORCEWAKE_ALL);
10175         intel_update_cdclk(&dev_priv->drm);
10176 }
10177
10178 /*
10179  * Package states C8 and deeper are really deep PC states that can only be
10180  * reached when all the devices on the system allow it, so even if the graphics
10181  * device allows PC8+, it doesn't mean the system will actually get to these
10182  * states. Our driver only allows PC8+ when going into runtime PM.
10183  *
10184  * The requirements for PC8+ are that all the outputs are disabled, the power
10185  * well is disabled and most interrupts are disabled, and these are also
10186  * requirements for runtime PM. When these conditions are met, we manually do
10187  * the other conditions: disable the interrupts, clocks and switch LCPLL refclk
10188  * to Fclk. If we're in PC8+ and we get an non-hotplug interrupt, we can hard
10189  * hang the machine.
10190  *
10191  * When we really reach PC8 or deeper states (not just when we allow it) we lose
10192  * the state of some registers, so when we come back from PC8+ we need to
10193  * restore this state. We don't get into PC8+ if we're not in RC6, so we don't
10194  * need to take care of the registers kept by RC6. Notice that this happens even
10195  * if we don't put the device in PCI D3 state (which is what currently happens
10196  * because of the runtime PM support).
10197  *
10198  * For more, read "Display Sequences for Package C8" on the hardware
10199  * documentation.
10200  */
10201 void hsw_enable_pc8(struct drm_i915_private *dev_priv)
10202 {
10203         struct drm_device *dev = &dev_priv->drm;
10204         uint32_t val;
10205
10206         DRM_DEBUG_KMS("Enabling package C8+\n");
10207
10208         if (HAS_PCH_LPT_LP(dev_priv)) {
10209                 val = I915_READ(SOUTH_DSPCLK_GATE_D);
10210                 val &= ~PCH_LP_PARTITION_LEVEL_DISABLE;
10211                 I915_WRITE(SOUTH_DSPCLK_GATE_D, val);
10212         }
10213
10214         lpt_disable_clkout_dp(dev);
10215         hsw_disable_lcpll(dev_priv, true, true);
10216 }
10217
10218 void hsw_disable_pc8(struct drm_i915_private *dev_priv)
10219 {
10220         struct drm_device *dev = &dev_priv->drm;
10221         uint32_t val;
10222
10223         DRM_DEBUG_KMS("Disabling package C8+\n");
10224
10225         hsw_restore_lcpll(dev_priv);
10226         lpt_init_pch_refclk(dev);
10227
10228         if (HAS_PCH_LPT_LP(dev_priv)) {
10229                 val = I915_READ(SOUTH_DSPCLK_GATE_D);
10230                 val |= PCH_LP_PARTITION_LEVEL_DISABLE;
10231                 I915_WRITE(SOUTH_DSPCLK_GATE_D, val);
10232         }
10233 }
10234
10235 static void bxt_modeset_commit_cdclk(struct drm_atomic_state *old_state)
10236 {
10237         struct drm_device *dev = old_state->dev;
10238         struct intel_atomic_state *old_intel_state =
10239                 to_intel_atomic_state(old_state);
10240         unsigned int req_cdclk = old_intel_state->dev_cdclk;
10241
10242         bxt_set_cdclk(to_i915(dev), req_cdclk);
10243 }
10244
10245 /* compute the max rate for new configuration */
10246 static int ilk_max_pixel_rate(struct drm_atomic_state *state)
10247 {
10248         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
10249         struct drm_i915_private *dev_priv = to_i915(state->dev);
10250         struct drm_crtc *crtc;
10251         struct drm_crtc_state *cstate;
10252         struct intel_crtc_state *crtc_state;
10253         unsigned max_pixel_rate = 0, i;
10254         enum pipe pipe;
10255
10256         memcpy(intel_state->min_pixclk, dev_priv->min_pixclk,
10257                sizeof(intel_state->min_pixclk));
10258
10259         for_each_crtc_in_state(state, crtc, cstate, i) {
10260                 int pixel_rate;
10261
10262                 crtc_state = to_intel_crtc_state(cstate);
10263                 if (!crtc_state->base.enable) {
10264                         intel_state->min_pixclk[i] = 0;
10265                         continue;
10266                 }
10267
10268                 pixel_rate = ilk_pipe_pixel_rate(crtc_state);
10269
10270                 /* pixel rate mustn't exceed 95% of cdclk with IPS on BDW */
10271                 if (IS_BROADWELL(dev_priv) && crtc_state->ips_enabled)
10272                         pixel_rate = DIV_ROUND_UP(pixel_rate * 100, 95);
10273
10274                 intel_state->min_pixclk[i] = pixel_rate;
10275         }
10276
10277         for_each_pipe(dev_priv, pipe)
10278                 max_pixel_rate = max(intel_state->min_pixclk[pipe], max_pixel_rate);
10279
10280         return max_pixel_rate;
10281 }
10282
10283 static void broadwell_set_cdclk(struct drm_device *dev, int cdclk)
10284 {
10285         struct drm_i915_private *dev_priv = to_i915(dev);
10286         uint32_t val, data;
10287         int ret;
10288
10289         if (WARN((I915_READ(LCPLL_CTL) &
10290                   (LCPLL_PLL_DISABLE | LCPLL_PLL_LOCK |
10291                    LCPLL_CD_CLOCK_DISABLE | LCPLL_ROOT_CD_CLOCK_DISABLE |
10292                    LCPLL_CD2X_CLOCK_DISABLE | LCPLL_POWER_DOWN_ALLOW |
10293                    LCPLL_CD_SOURCE_FCLK)) != LCPLL_PLL_LOCK,
10294                  "trying to change cdclk frequency with cdclk not enabled\n"))
10295                 return;
10296
10297         mutex_lock(&dev_priv->rps.hw_lock);
10298         ret = sandybridge_pcode_write(dev_priv,
10299                                       BDW_PCODE_DISPLAY_FREQ_CHANGE_REQ, 0x0);
10300         mutex_unlock(&dev_priv->rps.hw_lock);
10301         if (ret) {
10302                 DRM_ERROR("failed to inform pcode about cdclk change\n");
10303                 return;
10304         }
10305
10306         val = I915_READ(LCPLL_CTL);
10307         val |= LCPLL_CD_SOURCE_FCLK;
10308         I915_WRITE(LCPLL_CTL, val);
10309
10310         if (wait_for_us(I915_READ(LCPLL_CTL) &
10311                         LCPLL_CD_SOURCE_FCLK_DONE, 1))
10312                 DRM_ERROR("Switching to FCLK failed\n");
10313
10314         val = I915_READ(LCPLL_CTL);
10315         val &= ~LCPLL_CLK_FREQ_MASK;
10316
10317         switch (cdclk) {
10318         case 450000:
10319                 val |= LCPLL_CLK_FREQ_450;
10320                 data = 0;
10321                 break;
10322         case 540000:
10323                 val |= LCPLL_CLK_FREQ_54O_BDW;
10324                 data = 1;
10325                 break;
10326         case 337500:
10327                 val |= LCPLL_CLK_FREQ_337_5_BDW;
10328                 data = 2;
10329                 break;
10330         case 675000:
10331                 val |= LCPLL_CLK_FREQ_675_BDW;
10332                 data = 3;
10333                 break;
10334         default:
10335                 WARN(1, "invalid cdclk frequency\n");
10336                 return;
10337         }
10338
10339         I915_WRITE(LCPLL_CTL, val);
10340
10341         val = I915_READ(LCPLL_CTL);
10342         val &= ~LCPLL_CD_SOURCE_FCLK;
10343         I915_WRITE(LCPLL_CTL, val);
10344
10345         if (wait_for_us((I915_READ(LCPLL_CTL) &
10346                         LCPLL_CD_SOURCE_FCLK_DONE) == 0, 1))
10347                 DRM_ERROR("Switching back to LCPLL failed\n");
10348
10349         mutex_lock(&dev_priv->rps.hw_lock);
10350         sandybridge_pcode_write(dev_priv, HSW_PCODE_DE_WRITE_FREQ_REQ, data);
10351         mutex_unlock(&dev_priv->rps.hw_lock);
10352
10353         I915_WRITE(CDCLK_FREQ, DIV_ROUND_CLOSEST(cdclk, 1000) - 1);
10354
10355         intel_update_cdclk(dev);
10356
10357         WARN(cdclk != dev_priv->cdclk_freq,
10358              "cdclk requested %d kHz but got %d kHz\n",
10359              cdclk, dev_priv->cdclk_freq);
10360 }
10361
10362 static int broadwell_calc_cdclk(int max_pixclk)
10363 {
10364         if (max_pixclk > 540000)
10365                 return 675000;
10366         else if (max_pixclk > 450000)
10367                 return 540000;
10368         else if (max_pixclk > 337500)
10369                 return 450000;
10370         else
10371                 return 337500;
10372 }
10373
10374 static int broadwell_modeset_calc_cdclk(struct drm_atomic_state *state)
10375 {
10376         struct drm_i915_private *dev_priv = to_i915(state->dev);
10377         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
10378         int max_pixclk = ilk_max_pixel_rate(state);
10379         int cdclk;
10380
10381         /*
10382          * FIXME should also account for plane ratio
10383          * once 64bpp pixel formats are supported.
10384          */
10385         cdclk = broadwell_calc_cdclk(max_pixclk);
10386
10387         if (cdclk > dev_priv->max_cdclk_freq) {
10388                 DRM_DEBUG_KMS("requested cdclk (%d kHz) exceeds max (%d kHz)\n",
10389                               cdclk, dev_priv->max_cdclk_freq);
10390                 return -EINVAL;
10391         }
10392
10393         intel_state->cdclk = intel_state->dev_cdclk = cdclk;
10394         if (!intel_state->active_crtcs)
10395                 intel_state->dev_cdclk = broadwell_calc_cdclk(0);
10396
10397         return 0;
10398 }
10399
10400 static void broadwell_modeset_commit_cdclk(struct drm_atomic_state *old_state)
10401 {
10402         struct drm_device *dev = old_state->dev;
10403         struct intel_atomic_state *old_intel_state =
10404                 to_intel_atomic_state(old_state);
10405         unsigned req_cdclk = old_intel_state->dev_cdclk;
10406
10407         broadwell_set_cdclk(dev, req_cdclk);
10408 }
10409
10410 static int skl_modeset_calc_cdclk(struct drm_atomic_state *state)
10411 {
10412         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
10413         struct drm_i915_private *dev_priv = to_i915(state->dev);
10414         const int max_pixclk = ilk_max_pixel_rate(state);
10415         int vco = intel_state->cdclk_pll_vco;
10416         int cdclk;
10417
10418         /*
10419          * FIXME should also account for plane ratio
10420          * once 64bpp pixel formats are supported.
10421          */
10422         cdclk = skl_calc_cdclk(max_pixclk, vco);
10423
10424         /*
10425          * FIXME move the cdclk caclulation to
10426          * compute_config() so we can fail gracegully.
10427          */
10428         if (cdclk > dev_priv->max_cdclk_freq) {
10429                 DRM_ERROR("requested cdclk (%d kHz) exceeds max (%d kHz)\n",
10430                           cdclk, dev_priv->max_cdclk_freq);
10431                 cdclk = dev_priv->max_cdclk_freq;
10432         }
10433
10434         intel_state->cdclk = intel_state->dev_cdclk = cdclk;
10435         if (!intel_state->active_crtcs)
10436                 intel_state->dev_cdclk = skl_calc_cdclk(0, vco);
10437
10438         return 0;
10439 }
10440
10441 static void skl_modeset_commit_cdclk(struct drm_atomic_state *old_state)
10442 {
10443         struct drm_i915_private *dev_priv = to_i915(old_state->dev);
10444         struct intel_atomic_state *intel_state = to_intel_atomic_state(old_state);
10445         unsigned int req_cdclk = intel_state->dev_cdclk;
10446         unsigned int req_vco = intel_state->cdclk_pll_vco;
10447
10448         skl_set_cdclk(dev_priv, req_cdclk, req_vco);
10449 }
10450
10451 static int haswell_crtc_compute_clock(struct intel_crtc *crtc,
10452                                       struct intel_crtc_state *crtc_state)
10453 {
10454         if (!intel_crtc_has_type(crtc_state, INTEL_OUTPUT_DSI)) {
10455                 if (!intel_ddi_pll_select(crtc, crtc_state))
10456                         return -EINVAL;
10457         }
10458
10459         crtc->lowfreq_avail = false;
10460
10461         return 0;
10462 }
10463
10464 static void bxt_get_ddi_pll(struct drm_i915_private *dev_priv,
10465                                 enum port port,
10466                                 struct intel_crtc_state *pipe_config)
10467 {
10468         enum intel_dpll_id id;
10469
10470         switch (port) {
10471         case PORT_A:
10472                 id = DPLL_ID_SKL_DPLL0;
10473                 break;
10474         case PORT_B:
10475                 id = DPLL_ID_SKL_DPLL1;
10476                 break;
10477         case PORT_C:
10478                 id = DPLL_ID_SKL_DPLL2;
10479                 break;
10480         default:
10481                 DRM_ERROR("Incorrect port type\n");
10482                 return;
10483         }
10484
10485         pipe_config->shared_dpll = intel_get_shared_dpll_by_id(dev_priv, id);
10486 }
10487
10488 static void skylake_get_ddi_pll(struct drm_i915_private *dev_priv,
10489                                 enum port port,
10490                                 struct intel_crtc_state *pipe_config)
10491 {
10492         enum intel_dpll_id id;
10493         u32 temp;
10494
10495         temp = I915_READ(DPLL_CTRL2) & DPLL_CTRL2_DDI_CLK_SEL_MASK(port);
10496         id = temp >> (port * 3 + 1);
10497
10498         if (WARN_ON(id < SKL_DPLL0 || id > SKL_DPLL3))
10499                 return;
10500
10501         pipe_config->shared_dpll = intel_get_shared_dpll_by_id(dev_priv, id);
10502 }
10503
10504 static void haswell_get_ddi_pll(struct drm_i915_private *dev_priv,
10505                                 enum port port,
10506                                 struct intel_crtc_state *pipe_config)
10507 {
10508         enum intel_dpll_id id;
10509         uint32_t ddi_pll_sel = I915_READ(PORT_CLK_SEL(port));
10510
10511         switch (ddi_pll_sel) {
10512         case PORT_CLK_SEL_WRPLL1:
10513                 id = DPLL_ID_WRPLL1;
10514                 break;
10515         case PORT_CLK_SEL_WRPLL2:
10516                 id = DPLL_ID_WRPLL2;
10517                 break;
10518         case PORT_CLK_SEL_SPLL:
10519                 id = DPLL_ID_SPLL;
10520                 break;
10521         case PORT_CLK_SEL_LCPLL_810:
10522                 id = DPLL_ID_LCPLL_810;
10523                 break;
10524         case PORT_CLK_SEL_LCPLL_1350:
10525                 id = DPLL_ID_LCPLL_1350;
10526                 break;
10527         case PORT_CLK_SEL_LCPLL_2700:
10528                 id = DPLL_ID_LCPLL_2700;
10529                 break;
10530         default:
10531                 MISSING_CASE(ddi_pll_sel);
10532                 /* fall through */
10533         case PORT_CLK_SEL_NONE:
10534                 return;
10535         }
10536
10537         pipe_config->shared_dpll = intel_get_shared_dpll_by_id(dev_priv, id);
10538 }
10539
10540 static bool hsw_get_transcoder_state(struct intel_crtc *crtc,
10541                                      struct intel_crtc_state *pipe_config,
10542                                      unsigned long *power_domain_mask)
10543 {
10544         struct drm_device *dev = crtc->base.dev;
10545         struct drm_i915_private *dev_priv = to_i915(dev);
10546         enum intel_display_power_domain power_domain;
10547         u32 tmp;
10548
10549         /*
10550          * The pipe->transcoder mapping is fixed with the exception of the eDP
10551          * transcoder handled below.
10552          */
10553         pipe_config->cpu_transcoder = (enum transcoder) crtc->pipe;
10554
10555         /*
10556          * XXX: Do intel_display_power_get_if_enabled before reading this (for
10557          * consistency and less surprising code; it's in always on power).
10558          */
10559         tmp = I915_READ(TRANS_DDI_FUNC_CTL(TRANSCODER_EDP));
10560         if (tmp & TRANS_DDI_FUNC_ENABLE) {
10561                 enum pipe trans_edp_pipe;
10562                 switch (tmp & TRANS_DDI_EDP_INPUT_MASK) {
10563                 default:
10564                         WARN(1, "unknown pipe linked to edp transcoder\n");
10565                 case TRANS_DDI_EDP_INPUT_A_ONOFF:
10566                 case TRANS_DDI_EDP_INPUT_A_ON:
10567                         trans_edp_pipe = PIPE_A;
10568                         break;
10569                 case TRANS_DDI_EDP_INPUT_B_ONOFF:
10570                         trans_edp_pipe = PIPE_B;
10571                         break;
10572                 case TRANS_DDI_EDP_INPUT_C_ONOFF:
10573                         trans_edp_pipe = PIPE_C;
10574                         break;
10575                 }
10576
10577                 if (trans_edp_pipe == crtc->pipe)
10578                         pipe_config->cpu_transcoder = TRANSCODER_EDP;
10579         }
10580
10581         power_domain = POWER_DOMAIN_TRANSCODER(pipe_config->cpu_transcoder);
10582         if (!intel_display_power_get_if_enabled(dev_priv, power_domain))
10583                 return false;
10584         *power_domain_mask |= BIT(power_domain);
10585
10586         tmp = I915_READ(PIPECONF(pipe_config->cpu_transcoder));
10587
10588         return tmp & PIPECONF_ENABLE;
10589 }
10590
10591 static bool bxt_get_dsi_transcoder_state(struct intel_crtc *crtc,
10592                                          struct intel_crtc_state *pipe_config,
10593                                          unsigned long *power_domain_mask)
10594 {
10595         struct drm_device *dev = crtc->base.dev;
10596         struct drm_i915_private *dev_priv = to_i915(dev);
10597         enum intel_display_power_domain power_domain;
10598         enum port port;
10599         enum transcoder cpu_transcoder;
10600         u32 tmp;
10601
10602         for_each_port_masked(port, BIT(PORT_A) | BIT(PORT_C)) {
10603                 if (port == PORT_A)
10604                         cpu_transcoder = TRANSCODER_DSI_A;
10605                 else
10606                         cpu_transcoder = TRANSCODER_DSI_C;
10607
10608                 power_domain = POWER_DOMAIN_TRANSCODER(cpu_transcoder);
10609                 if (!intel_display_power_get_if_enabled(dev_priv, power_domain))
10610                         continue;
10611                 *power_domain_mask |= BIT(power_domain);
10612
10613                 /*
10614                  * The PLL needs to be enabled with a valid divider
10615                  * configuration, otherwise accessing DSI registers will hang
10616                  * the machine. See BSpec North Display Engine
10617                  * registers/MIPI[BXT]. We can break out here early, since we
10618                  * need the same DSI PLL to be enabled for both DSI ports.
10619                  */
10620                 if (!intel_dsi_pll_is_enabled(dev_priv))
10621                         break;
10622
10623                 /* XXX: this works for video mode only */
10624                 tmp = I915_READ(BXT_MIPI_PORT_CTRL(port));
10625                 if (!(tmp & DPI_ENABLE))
10626                         continue;
10627
10628                 tmp = I915_READ(MIPI_CTRL(port));
10629                 if ((tmp & BXT_PIPE_SELECT_MASK) != BXT_PIPE_SELECT(crtc->pipe))
10630                         continue;
10631
10632                 pipe_config->cpu_transcoder = cpu_transcoder;
10633                 break;
10634         }
10635
10636         return transcoder_is_dsi(pipe_config->cpu_transcoder);
10637 }
10638
10639 static void haswell_get_ddi_port_state(struct intel_crtc *crtc,
10640                                        struct intel_crtc_state *pipe_config)
10641 {
10642         struct drm_device *dev = crtc->base.dev;
10643         struct drm_i915_private *dev_priv = to_i915(dev);
10644         struct intel_shared_dpll *pll;
10645         enum port port;
10646         uint32_t tmp;
10647
10648         tmp = I915_READ(TRANS_DDI_FUNC_CTL(pipe_config->cpu_transcoder));
10649
10650         port = (tmp & TRANS_DDI_PORT_MASK) >> TRANS_DDI_PORT_SHIFT;
10651
10652         if (IS_SKYLAKE(dev) || IS_KABYLAKE(dev))
10653                 skylake_get_ddi_pll(dev_priv, port, pipe_config);
10654         else if (IS_BROXTON(dev))
10655                 bxt_get_ddi_pll(dev_priv, port, pipe_config);
10656         else
10657                 haswell_get_ddi_pll(dev_priv, port, pipe_config);
10658
10659         pll = pipe_config->shared_dpll;
10660         if (pll) {
10661                 WARN_ON(!pll->funcs.get_hw_state(dev_priv, pll,
10662                                                  &pipe_config->dpll_hw_state));
10663         }
10664
10665         /*
10666          * Haswell has only FDI/PCH transcoder A. It is which is connected to
10667          * DDI E. So just check whether this pipe is wired to DDI E and whether
10668          * the PCH transcoder is on.
10669          */
10670         if (INTEL_INFO(dev)->gen < 9 &&
10671             (port == PORT_E) && I915_READ(LPT_TRANSCONF) & TRANS_ENABLE) {
10672                 pipe_config->has_pch_encoder = true;
10673
10674                 tmp = I915_READ(FDI_RX_CTL(PIPE_A));
10675                 pipe_config->fdi_lanes = ((FDI_DP_PORT_WIDTH_MASK & tmp) >>
10676                                           FDI_DP_PORT_WIDTH_SHIFT) + 1;
10677
10678                 ironlake_get_fdi_m_n_config(crtc, pipe_config);
10679         }
10680 }
10681
10682 static bool haswell_get_pipe_config(struct intel_crtc *crtc,
10683                                     struct intel_crtc_state *pipe_config)
10684 {
10685         struct drm_device *dev = crtc->base.dev;
10686         struct drm_i915_private *dev_priv = to_i915(dev);
10687         enum intel_display_power_domain power_domain;
10688         unsigned long power_domain_mask;
10689         bool active;
10690
10691         power_domain = POWER_DOMAIN_PIPE(crtc->pipe);
10692         if (!intel_display_power_get_if_enabled(dev_priv, power_domain))
10693                 return false;
10694         power_domain_mask = BIT(power_domain);
10695
10696         pipe_config->shared_dpll = NULL;
10697
10698         active = hsw_get_transcoder_state(crtc, pipe_config, &power_domain_mask);
10699
10700         if (IS_BROXTON(dev_priv) &&
10701             bxt_get_dsi_transcoder_state(crtc, pipe_config, &power_domain_mask)) {
10702                 WARN_ON(active);
10703                 active = true;
10704         }
10705
10706         if (!active)
10707                 goto out;
10708
10709         if (!transcoder_is_dsi(pipe_config->cpu_transcoder)) {
10710                 haswell_get_ddi_port_state(crtc, pipe_config);
10711                 intel_get_pipe_timings(crtc, pipe_config);
10712         }
10713
10714         intel_get_pipe_src_size(crtc, pipe_config);
10715
10716         pipe_config->gamma_mode =
10717                 I915_READ(GAMMA_MODE(crtc->pipe)) & GAMMA_MODE_MODE_MASK;
10718
10719         if (INTEL_INFO(dev)->gen >= 9) {
10720                 skl_init_scalers(dev, crtc, pipe_config);
10721         }
10722
10723         if (INTEL_INFO(dev)->gen >= 9) {
10724                 pipe_config->scaler_state.scaler_id = -1;
10725                 pipe_config->scaler_state.scaler_users &= ~(1 << SKL_CRTC_INDEX);
10726         }
10727
10728         power_domain = POWER_DOMAIN_PIPE_PANEL_FITTER(crtc->pipe);
10729         if (intel_display_power_get_if_enabled(dev_priv, power_domain)) {
10730                 power_domain_mask |= BIT(power_domain);
10731                 if (INTEL_INFO(dev)->gen >= 9)
10732                         skylake_get_pfit_config(crtc, pipe_config);
10733                 else
10734                         ironlake_get_pfit_config(crtc, pipe_config);
10735         }
10736
10737         if (IS_HASWELL(dev))
10738                 pipe_config->ips_enabled = hsw_crtc_supports_ips(crtc) &&
10739                         (I915_READ(IPS_CTL) & IPS_ENABLE);
10740
10741         if (pipe_config->cpu_transcoder != TRANSCODER_EDP &&
10742             !transcoder_is_dsi(pipe_config->cpu_transcoder)) {
10743                 pipe_config->pixel_multiplier =
10744                         I915_READ(PIPE_MULT(pipe_config->cpu_transcoder)) + 1;
10745         } else {
10746                 pipe_config->pixel_multiplier = 1;
10747         }
10748
10749 out:
10750         for_each_power_domain(power_domain, power_domain_mask)
10751                 intel_display_power_put(dev_priv, power_domain);
10752
10753         return active;
10754 }
10755
10756 static void i845_update_cursor(struct drm_crtc *crtc, u32 base,
10757                                const struct intel_plane_state *plane_state)
10758 {
10759         struct drm_device *dev = crtc->dev;
10760         struct drm_i915_private *dev_priv = to_i915(dev);
10761         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
10762         uint32_t cntl = 0, size = 0;
10763
10764         if (plane_state && plane_state->base.visible) {
10765                 unsigned int width = plane_state->base.crtc_w;
10766                 unsigned int height = plane_state->base.crtc_h;
10767                 unsigned int stride = roundup_pow_of_two(width) * 4;
10768
10769                 switch (stride) {
10770                 default:
10771                         WARN_ONCE(1, "Invalid cursor width/stride, width=%u, stride=%u\n",
10772                                   width, stride);
10773                         stride = 256;
10774                         /* fallthrough */
10775                 case 256:
10776                 case 512:
10777                 case 1024:
10778                 case 2048:
10779                         break;
10780                 }
10781
10782                 cntl |= CURSOR_ENABLE |
10783                         CURSOR_GAMMA_ENABLE |
10784                         CURSOR_FORMAT_ARGB |
10785                         CURSOR_STRIDE(stride);
10786
10787                 size = (height << 12) | width;
10788         }
10789
10790         if (intel_crtc->cursor_cntl != 0 &&
10791             (intel_crtc->cursor_base != base ||
10792              intel_crtc->cursor_size != size ||
10793              intel_crtc->cursor_cntl != cntl)) {
10794                 /* On these chipsets we can only modify the base/size/stride
10795                  * whilst the cursor is disabled.
10796                  */
10797                 I915_WRITE(CURCNTR(PIPE_A), 0);
10798                 POSTING_READ(CURCNTR(PIPE_A));
10799                 intel_crtc->cursor_cntl = 0;
10800         }
10801
10802         if (intel_crtc->cursor_base != base) {
10803                 I915_WRITE(CURBASE(PIPE_A), base);
10804                 intel_crtc->cursor_base = base;
10805         }
10806
10807         if (intel_crtc->cursor_size != size) {
10808                 I915_WRITE(CURSIZE, size);
10809                 intel_crtc->cursor_size = size;
10810         }
10811
10812         if (intel_crtc->cursor_cntl != cntl) {
10813                 I915_WRITE(CURCNTR(PIPE_A), cntl);
10814                 POSTING_READ(CURCNTR(PIPE_A));
10815                 intel_crtc->cursor_cntl = cntl;
10816         }
10817 }
10818
10819 static void i9xx_update_cursor(struct drm_crtc *crtc, u32 base,
10820                                const struct intel_plane_state *plane_state)
10821 {
10822         struct drm_device *dev = crtc->dev;
10823         struct drm_i915_private *dev_priv = to_i915(dev);
10824         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
10825         const struct skl_wm_values *wm = &dev_priv->wm.skl_results;
10826         int pipe = intel_crtc->pipe;
10827         uint32_t cntl = 0;
10828
10829         if (INTEL_GEN(dev_priv) >= 9 && wm->dirty_pipes & drm_crtc_mask(crtc))
10830                 skl_write_cursor_wm(intel_crtc, wm);
10831
10832         if (plane_state && plane_state->base.visible) {
10833                 cntl = MCURSOR_GAMMA_ENABLE;
10834                 switch (plane_state->base.crtc_w) {
10835                         case 64:
10836                                 cntl |= CURSOR_MODE_64_ARGB_AX;
10837                                 break;
10838                         case 128:
10839                                 cntl |= CURSOR_MODE_128_ARGB_AX;
10840                                 break;
10841                         case 256:
10842                                 cntl |= CURSOR_MODE_256_ARGB_AX;
10843                                 break;
10844                         default:
10845                                 MISSING_CASE(plane_state->base.crtc_w);
10846                                 return;
10847                 }
10848                 cntl |= pipe << 28; /* Connect to correct pipe */
10849
10850                 if (HAS_DDI(dev_priv))
10851                         cntl |= CURSOR_PIPE_CSC_ENABLE;
10852
10853                 if (plane_state->base.rotation == DRM_ROTATE_180)
10854                         cntl |= CURSOR_ROTATE_180;
10855         }
10856
10857         if (intel_crtc->cursor_cntl != cntl) {
10858                 I915_WRITE(CURCNTR(pipe), cntl);
10859                 POSTING_READ(CURCNTR(pipe));
10860                 intel_crtc->cursor_cntl = cntl;
10861         }
10862
10863         /* and commit changes on next vblank */
10864         I915_WRITE(CURBASE(pipe), base);
10865         POSTING_READ(CURBASE(pipe));
10866
10867         intel_crtc->cursor_base = base;
10868 }
10869
10870 /* If no-part of the cursor is visible on the framebuffer, then the GPU may hang... */
10871 static void intel_crtc_update_cursor(struct drm_crtc *crtc,
10872                                      const struct intel_plane_state *plane_state)
10873 {
10874         struct drm_device *dev = crtc->dev;
10875         struct drm_i915_private *dev_priv = to_i915(dev);
10876         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
10877         int pipe = intel_crtc->pipe;
10878         u32 base = intel_crtc->cursor_addr;
10879         u32 pos = 0;
10880
10881         if (plane_state) {
10882                 int x = plane_state->base.crtc_x;
10883                 int y = plane_state->base.crtc_y;
10884
10885                 if (x < 0) {
10886                         pos |= CURSOR_POS_SIGN << CURSOR_X_SHIFT;
10887                         x = -x;
10888                 }
10889                 pos |= x << CURSOR_X_SHIFT;
10890
10891                 if (y < 0) {
10892                         pos |= CURSOR_POS_SIGN << CURSOR_Y_SHIFT;
10893                         y = -y;
10894                 }
10895                 pos |= y << CURSOR_Y_SHIFT;
10896
10897                 /* ILK+ do this automagically */
10898                 if (HAS_GMCH_DISPLAY(dev_priv) &&
10899                     plane_state->base.rotation == DRM_ROTATE_180) {
10900                         base += (plane_state->base.crtc_h *
10901                                  plane_state->base.crtc_w - 1) * 4;
10902                 }
10903         }
10904
10905         I915_WRITE(CURPOS(pipe), pos);
10906
10907         if (IS_845G(dev_priv) || IS_I865G(dev_priv))
10908                 i845_update_cursor(crtc, base, plane_state);
10909         else
10910                 i9xx_update_cursor(crtc, base, plane_state);
10911 }
10912
10913 static bool cursor_size_ok(struct drm_i915_private *dev_priv,
10914                            uint32_t width, uint32_t height)
10915 {
10916         if (width == 0 || height == 0)
10917                 return false;
10918
10919         /*
10920          * 845g/865g are special in that they are only limited by
10921          * the width of their cursors, the height is arbitrary up to
10922          * the precision of the register. Everything else requires
10923          * square cursors, limited to a few power-of-two sizes.
10924          */
10925         if (IS_845G(dev_priv) || IS_I865G(dev_priv)) {
10926                 if ((width & 63) != 0)
10927                         return false;
10928
10929                 if (width > (IS_845G(dev_priv) ? 64 : 512))
10930                         return false;
10931
10932                 if (height > 1023)
10933                         return false;
10934         } else {
10935                 switch (width | height) {
10936                 case 256:
10937                 case 128:
10938                         if (IS_GEN2(dev_priv))
10939                                 return false;
10940                 case 64:
10941                         break;
10942                 default:
10943                         return false;
10944                 }
10945         }
10946
10947         return true;
10948 }
10949
10950 /* VESA 640x480x72Hz mode to set on the pipe */
10951 static struct drm_display_mode load_detect_mode = {
10952         DRM_MODE("640x480", DRM_MODE_TYPE_DEFAULT, 31500, 640, 664,
10953                  704, 832, 0, 480, 489, 491, 520, 0, DRM_MODE_FLAG_NHSYNC | DRM_MODE_FLAG_NVSYNC),
10954 };
10955
10956 struct drm_framebuffer *
10957 __intel_framebuffer_create(struct drm_device *dev,
10958                            struct drm_mode_fb_cmd2 *mode_cmd,
10959                            struct drm_i915_gem_object *obj)
10960 {
10961         struct intel_framebuffer *intel_fb;
10962         int ret;
10963
10964         intel_fb = kzalloc(sizeof(*intel_fb), GFP_KERNEL);
10965         if (!intel_fb)
10966                 return ERR_PTR(-ENOMEM);
10967
10968         ret = intel_framebuffer_init(dev, intel_fb, mode_cmd, obj);
10969         if (ret)
10970                 goto err;
10971
10972         return &intel_fb->base;
10973
10974 err:
10975         kfree(intel_fb);
10976         return ERR_PTR(ret);
10977 }
10978
10979 static struct drm_framebuffer *
10980 intel_framebuffer_create(struct drm_device *dev,
10981                          struct drm_mode_fb_cmd2 *mode_cmd,
10982                          struct drm_i915_gem_object *obj)
10983 {
10984         struct drm_framebuffer *fb;
10985         int ret;
10986
10987         ret = i915_mutex_lock_interruptible(dev);
10988         if (ret)
10989                 return ERR_PTR(ret);
10990         fb = __intel_framebuffer_create(dev, mode_cmd, obj);
10991         mutex_unlock(&dev->struct_mutex);
10992
10993         return fb;
10994 }
10995
10996 static u32
10997 intel_framebuffer_pitch_for_width(int width, int bpp)
10998 {
10999         u32 pitch = DIV_ROUND_UP(width * bpp, 8);
11000         return ALIGN(pitch, 64);
11001 }
11002
11003 static u32
11004 intel_framebuffer_size_for_mode(struct drm_display_mode *mode, int bpp)
11005 {
11006         u32 pitch = intel_framebuffer_pitch_for_width(mode->hdisplay, bpp);
11007         return PAGE_ALIGN(pitch * mode->vdisplay);
11008 }
11009
11010 static struct drm_framebuffer *
11011 intel_framebuffer_create_for_mode(struct drm_device *dev,
11012                                   struct drm_display_mode *mode,
11013                                   int depth, int bpp)
11014 {
11015         struct drm_framebuffer *fb;
11016         struct drm_i915_gem_object *obj;
11017         struct drm_mode_fb_cmd2 mode_cmd = { 0 };
11018
11019         obj = i915_gem_object_create(dev,
11020                                     intel_framebuffer_size_for_mode(mode, bpp));
11021         if (IS_ERR(obj))
11022                 return ERR_CAST(obj);
11023
11024         mode_cmd.width = mode->hdisplay;
11025         mode_cmd.height = mode->vdisplay;
11026         mode_cmd.pitches[0] = intel_framebuffer_pitch_for_width(mode_cmd.width,
11027                                                                 bpp);
11028         mode_cmd.pixel_format = drm_mode_legacy_fb_format(bpp, depth);
11029
11030         fb = intel_framebuffer_create(dev, &mode_cmd, obj);
11031         if (IS_ERR(fb))
11032                 i915_gem_object_put_unlocked(obj);
11033
11034         return fb;
11035 }
11036
11037 static struct drm_framebuffer *
11038 mode_fits_in_fbdev(struct drm_device *dev,
11039                    struct drm_display_mode *mode)
11040 {
11041 #ifdef CONFIG_DRM_FBDEV_EMULATION
11042         struct drm_i915_private *dev_priv = to_i915(dev);
11043         struct drm_i915_gem_object *obj;
11044         struct drm_framebuffer *fb;
11045
11046         if (!dev_priv->fbdev)
11047                 return NULL;
11048
11049         if (!dev_priv->fbdev->fb)
11050                 return NULL;
11051
11052         obj = dev_priv->fbdev->fb->obj;
11053         BUG_ON(!obj);
11054
11055         fb = &dev_priv->fbdev->fb->base;
11056         if (fb->pitches[0] < intel_framebuffer_pitch_for_width(mode->hdisplay,
11057                                                                fb->bits_per_pixel))
11058                 return NULL;
11059
11060         if (obj->base.size < mode->vdisplay * fb->pitches[0])
11061                 return NULL;
11062
11063         drm_framebuffer_reference(fb);
11064         return fb;
11065 #else
11066         return NULL;
11067 #endif
11068 }
11069
11070 static int intel_modeset_setup_plane_state(struct drm_atomic_state *state,
11071                                            struct drm_crtc *crtc,
11072                                            struct drm_display_mode *mode,
11073                                            struct drm_framebuffer *fb,
11074                                            int x, int y)
11075 {
11076         struct drm_plane_state *plane_state;
11077         int hdisplay, vdisplay;
11078         int ret;
11079
11080         plane_state = drm_atomic_get_plane_state(state, crtc->primary);
11081         if (IS_ERR(plane_state))
11082                 return PTR_ERR(plane_state);
11083
11084         if (mode)
11085                 drm_crtc_get_hv_timing(mode, &hdisplay, &vdisplay);
11086         else
11087                 hdisplay = vdisplay = 0;
11088
11089         ret = drm_atomic_set_crtc_for_plane(plane_state, fb ? crtc : NULL);
11090         if (ret)
11091                 return ret;
11092         drm_atomic_set_fb_for_plane(plane_state, fb);
11093         plane_state->crtc_x = 0;
11094         plane_state->crtc_y = 0;
11095         plane_state->crtc_w = hdisplay;
11096         plane_state->crtc_h = vdisplay;
11097         plane_state->src_x = x << 16;
11098         plane_state->src_y = y << 16;
11099         plane_state->src_w = hdisplay << 16;
11100         plane_state->src_h = vdisplay << 16;
11101
11102         return 0;
11103 }
11104
11105 bool intel_get_load_detect_pipe(struct drm_connector *connector,
11106                                 struct drm_display_mode *mode,
11107                                 struct intel_load_detect_pipe *old,
11108                                 struct drm_modeset_acquire_ctx *ctx)
11109 {
11110         struct intel_crtc *intel_crtc;
11111         struct intel_encoder *intel_encoder =
11112                 intel_attached_encoder(connector);
11113         struct drm_crtc *possible_crtc;
11114         struct drm_encoder *encoder = &intel_encoder->base;
11115         struct drm_crtc *crtc = NULL;
11116         struct drm_device *dev = encoder->dev;
11117         struct drm_framebuffer *fb;
11118         struct drm_mode_config *config = &dev->mode_config;
11119         struct drm_atomic_state *state = NULL, *restore_state = NULL;
11120         struct drm_connector_state *connector_state;
11121         struct intel_crtc_state *crtc_state;
11122         int ret, i = -1;
11123
11124         DRM_DEBUG_KMS("[CONNECTOR:%d:%s], [ENCODER:%d:%s]\n",
11125                       connector->base.id, connector->name,
11126                       encoder->base.id, encoder->name);
11127
11128         old->restore_state = NULL;
11129
11130 retry:
11131         ret = drm_modeset_lock(&config->connection_mutex, ctx);
11132         if (ret)
11133                 goto fail;
11134
11135         /*
11136          * Algorithm gets a little messy:
11137          *
11138          *   - if the connector already has an assigned crtc, use it (but make
11139          *     sure it's on first)
11140          *
11141          *   - try to find the first unused crtc that can drive this connector,
11142          *     and use that if we find one
11143          */
11144
11145         /* See if we already have a CRTC for this connector */
11146         if (connector->state->crtc) {
11147                 crtc = connector->state->crtc;
11148
11149                 ret = drm_modeset_lock(&crtc->mutex, ctx);
11150                 if (ret)
11151                         goto fail;
11152
11153                 /* Make sure the crtc and connector are running */
11154                 goto found;
11155         }
11156
11157         /* Find an unused one (if possible) */
11158         for_each_crtc(dev, possible_crtc) {
11159                 i++;
11160                 if (!(encoder->possible_crtcs & (1 << i)))
11161                         continue;
11162
11163                 ret = drm_modeset_lock(&possible_crtc->mutex, ctx);
11164                 if (ret)
11165                         goto fail;
11166
11167                 if (possible_crtc->state->enable) {
11168                         drm_modeset_unlock(&possible_crtc->mutex);
11169                         continue;
11170                 }
11171
11172                 crtc = possible_crtc;
11173                 break;
11174         }
11175
11176         /*
11177          * If we didn't find an unused CRTC, don't use any.
11178          */
11179         if (!crtc) {
11180                 DRM_DEBUG_KMS("no pipe available for load-detect\n");
11181                 goto fail;
11182         }
11183
11184 found:
11185         intel_crtc = to_intel_crtc(crtc);
11186
11187         ret = drm_modeset_lock(&crtc->primary->mutex, ctx);
11188         if (ret)
11189                 goto fail;
11190
11191         state = drm_atomic_state_alloc(dev);
11192         restore_state = drm_atomic_state_alloc(dev);
11193         if (!state || !restore_state) {
11194                 ret = -ENOMEM;
11195                 goto fail;
11196         }
11197
11198         state->acquire_ctx = ctx;
11199         restore_state->acquire_ctx = ctx;
11200
11201         connector_state = drm_atomic_get_connector_state(state, connector);
11202         if (IS_ERR(connector_state)) {
11203                 ret = PTR_ERR(connector_state);
11204                 goto fail;
11205         }
11206
11207         ret = drm_atomic_set_crtc_for_connector(connector_state, crtc);
11208         if (ret)
11209                 goto fail;
11210
11211         crtc_state = intel_atomic_get_crtc_state(state, intel_crtc);
11212         if (IS_ERR(crtc_state)) {
11213                 ret = PTR_ERR(crtc_state);
11214                 goto fail;
11215         }
11216
11217         crtc_state->base.active = crtc_state->base.enable = true;
11218
11219         if (!mode)
11220                 mode = &load_detect_mode;
11221
11222         /* We need a framebuffer large enough to accommodate all accesses
11223          * that the plane may generate whilst we perform load detection.
11224          * We can not rely on the fbcon either being present (we get called
11225          * during its initialisation to detect all boot displays, or it may
11226          * not even exist) or that it is large enough to satisfy the
11227          * requested mode.
11228          */
11229         fb = mode_fits_in_fbdev(dev, mode);
11230         if (fb == NULL) {
11231                 DRM_DEBUG_KMS("creating tmp fb for load-detection\n");
11232                 fb = intel_framebuffer_create_for_mode(dev, mode, 24, 32);
11233         } else
11234                 DRM_DEBUG_KMS("reusing fbdev for load-detection framebuffer\n");
11235         if (IS_ERR(fb)) {
11236                 DRM_DEBUG_KMS("failed to allocate framebuffer for load-detection\n");
11237                 goto fail;
11238         }
11239
11240         ret = intel_modeset_setup_plane_state(state, crtc, mode, fb, 0, 0);
11241         if (ret)
11242                 goto fail;
11243
11244         drm_framebuffer_unreference(fb);
11245
11246         ret = drm_atomic_set_mode_for_crtc(&crtc_state->base, mode);
11247         if (ret)
11248                 goto fail;
11249
11250         ret = PTR_ERR_OR_ZERO(drm_atomic_get_connector_state(restore_state, connector));
11251         if (!ret)
11252                 ret = PTR_ERR_OR_ZERO(drm_atomic_get_crtc_state(restore_state, crtc));
11253         if (!ret)
11254                 ret = PTR_ERR_OR_ZERO(drm_atomic_get_plane_state(restore_state, crtc->primary));
11255         if (ret) {
11256                 DRM_DEBUG_KMS("Failed to create a copy of old state to restore: %i\n", ret);
11257                 goto fail;
11258         }
11259
11260         ret = drm_atomic_commit(state);
11261         if (ret) {
11262                 DRM_DEBUG_KMS("failed to set mode on load-detect pipe\n");
11263                 goto fail;
11264         }
11265
11266         old->restore_state = restore_state;
11267
11268         /* let the connector get through one full cycle before testing */
11269         intel_wait_for_vblank(dev, intel_crtc->pipe);
11270         return true;
11271
11272 fail:
11273         drm_atomic_state_free(state);
11274         drm_atomic_state_free(restore_state);
11275         restore_state = state = NULL;
11276
11277         if (ret == -EDEADLK) {
11278                 drm_modeset_backoff(ctx);
11279                 goto retry;
11280         }
11281
11282         return false;
11283 }
11284
11285 void intel_release_load_detect_pipe(struct drm_connector *connector,
11286                                     struct intel_load_detect_pipe *old,
11287                                     struct drm_modeset_acquire_ctx *ctx)
11288 {
11289         struct intel_encoder *intel_encoder =
11290                 intel_attached_encoder(connector);
11291         struct drm_encoder *encoder = &intel_encoder->base;
11292         struct drm_atomic_state *state = old->restore_state;
11293         int ret;
11294
11295         DRM_DEBUG_KMS("[CONNECTOR:%d:%s], [ENCODER:%d:%s]\n",
11296                       connector->base.id, connector->name,
11297                       encoder->base.id, encoder->name);
11298
11299         if (!state)
11300                 return;
11301
11302         ret = drm_atomic_commit(state);
11303         if (ret) {
11304                 DRM_DEBUG_KMS("Couldn't release load detect pipe: %i\n", ret);
11305                 drm_atomic_state_free(state);
11306         }
11307 }
11308
11309 static int i9xx_pll_refclk(struct drm_device *dev,
11310                            const struct intel_crtc_state *pipe_config)
11311 {
11312         struct drm_i915_private *dev_priv = to_i915(dev);
11313         u32 dpll = pipe_config->dpll_hw_state.dpll;
11314
11315         if ((dpll & PLL_REF_INPUT_MASK) == PLLB_REF_INPUT_SPREADSPECTRUMIN)
11316                 return dev_priv->vbt.lvds_ssc_freq;
11317         else if (HAS_PCH_SPLIT(dev_priv))
11318                 return 120000;
11319         else if (!IS_GEN2(dev))
11320                 return 96000;
11321         else
11322                 return 48000;
11323 }
11324
11325 /* Returns the clock of the currently programmed mode of the given pipe. */
11326 static void i9xx_crtc_clock_get(struct intel_crtc *crtc,
11327                                 struct intel_crtc_state *pipe_config)
11328 {
11329         struct drm_device *dev = crtc->base.dev;
11330         struct drm_i915_private *dev_priv = to_i915(dev);
11331         int pipe = pipe_config->cpu_transcoder;
11332         u32 dpll = pipe_config->dpll_hw_state.dpll;
11333         u32 fp;
11334         struct dpll clock;
11335         int port_clock;
11336         int refclk = i9xx_pll_refclk(dev, pipe_config);
11337
11338         if ((dpll & DISPLAY_RATE_SELECT_FPA1) == 0)
11339                 fp = pipe_config->dpll_hw_state.fp0;
11340         else
11341                 fp = pipe_config->dpll_hw_state.fp1;
11342
11343         clock.m1 = (fp & FP_M1_DIV_MASK) >> FP_M1_DIV_SHIFT;
11344         if (IS_PINEVIEW(dev)) {
11345                 clock.n = ffs((fp & FP_N_PINEVIEW_DIV_MASK) >> FP_N_DIV_SHIFT) - 1;
11346                 clock.m2 = (fp & FP_M2_PINEVIEW_DIV_MASK) >> FP_M2_DIV_SHIFT;
11347         } else {
11348                 clock.n = (fp & FP_N_DIV_MASK) >> FP_N_DIV_SHIFT;
11349                 clock.m2 = (fp & FP_M2_DIV_MASK) >> FP_M2_DIV_SHIFT;
11350         }
11351
11352         if (!IS_GEN2(dev)) {
11353                 if (IS_PINEVIEW(dev))
11354                         clock.p1 = ffs((dpll & DPLL_FPA01_P1_POST_DIV_MASK_PINEVIEW) >>
11355                                 DPLL_FPA01_P1_POST_DIV_SHIFT_PINEVIEW);
11356                 else
11357                         clock.p1 = ffs((dpll & DPLL_FPA01_P1_POST_DIV_MASK) >>
11358                                DPLL_FPA01_P1_POST_DIV_SHIFT);
11359
11360                 switch (dpll & DPLL_MODE_MASK) {
11361                 case DPLLB_MODE_DAC_SERIAL:
11362                         clock.p2 = dpll & DPLL_DAC_SERIAL_P2_CLOCK_DIV_5 ?
11363                                 5 : 10;
11364                         break;
11365                 case DPLLB_MODE_LVDS:
11366                         clock.p2 = dpll & DPLLB_LVDS_P2_CLOCK_DIV_7 ?
11367                                 7 : 14;
11368                         break;
11369                 default:
11370                         DRM_DEBUG_KMS("Unknown DPLL mode %08x in programmed "
11371                                   "mode\n", (int)(dpll & DPLL_MODE_MASK));
11372                         return;
11373                 }
11374
11375                 if (IS_PINEVIEW(dev))
11376                         port_clock = pnv_calc_dpll_params(refclk, &clock);
11377                 else
11378                         port_clock = i9xx_calc_dpll_params(refclk, &clock);
11379         } else {
11380                 u32 lvds = IS_I830(dev_priv) ? 0 : I915_READ(LVDS);
11381                 bool is_lvds = (pipe == 1) && (lvds & LVDS_PORT_EN);
11382
11383                 if (is_lvds) {
11384                         clock.p1 = ffs((dpll & DPLL_FPA01_P1_POST_DIV_MASK_I830_LVDS) >>
11385                                        DPLL_FPA01_P1_POST_DIV_SHIFT);
11386
11387                         if (lvds & LVDS_CLKB_POWER_UP)
11388                                 clock.p2 = 7;
11389                         else
11390                                 clock.p2 = 14;
11391                 } else {
11392                         if (dpll & PLL_P1_DIVIDE_BY_TWO)
11393                                 clock.p1 = 2;
11394                         else {
11395                                 clock.p1 = ((dpll & DPLL_FPA01_P1_POST_DIV_MASK_I830) >>
11396                                             DPLL_FPA01_P1_POST_DIV_SHIFT) + 2;
11397                         }
11398                         if (dpll & PLL_P2_DIVIDE_BY_4)
11399                                 clock.p2 = 4;
11400                         else
11401                                 clock.p2 = 2;
11402                 }
11403
11404                 port_clock = i9xx_calc_dpll_params(refclk, &clock);
11405         }
11406
11407         /*
11408          * This value includes pixel_multiplier. We will use
11409          * port_clock to compute adjusted_mode.crtc_clock in the
11410          * encoder's get_config() function.
11411          */
11412         pipe_config->port_clock = port_clock;
11413 }
11414
11415 int intel_dotclock_calculate(int link_freq,
11416                              const struct intel_link_m_n *m_n)
11417 {
11418         /*
11419          * The calculation for the data clock is:
11420          * pixel_clock = ((m/n)*(link_clock * nr_lanes))/bpp
11421          * But we want to avoid losing precison if possible, so:
11422          * pixel_clock = ((m * link_clock * nr_lanes)/(n*bpp))
11423          *
11424          * and the link clock is simpler:
11425          * link_clock = (m * link_clock) / n
11426          */
11427
11428         if (!m_n->link_n)
11429                 return 0;
11430
11431         return div_u64((u64)m_n->link_m * link_freq, m_n->link_n);
11432 }
11433
11434 static void ironlake_pch_clock_get(struct intel_crtc *crtc,
11435                                    struct intel_crtc_state *pipe_config)
11436 {
11437         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
11438
11439         /* read out port_clock from the DPLL */
11440         i9xx_crtc_clock_get(crtc, pipe_config);
11441
11442         /*
11443          * In case there is an active pipe without active ports,
11444          * we may need some idea for the dotclock anyway.
11445          * Calculate one based on the FDI configuration.
11446          */
11447         pipe_config->base.adjusted_mode.crtc_clock =
11448                 intel_dotclock_calculate(intel_fdi_link_freq(dev_priv, pipe_config),
11449                                          &pipe_config->fdi_m_n);
11450 }
11451
11452 /** Returns the currently programmed mode of the given pipe. */
11453 struct drm_display_mode *intel_crtc_mode_get(struct drm_device *dev,
11454                                              struct drm_crtc *crtc)
11455 {
11456         struct drm_i915_private *dev_priv = to_i915(dev);
11457         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
11458         enum transcoder cpu_transcoder = intel_crtc->config->cpu_transcoder;
11459         struct drm_display_mode *mode;
11460         struct intel_crtc_state *pipe_config;
11461         int htot = I915_READ(HTOTAL(cpu_transcoder));
11462         int hsync = I915_READ(HSYNC(cpu_transcoder));
11463         int vtot = I915_READ(VTOTAL(cpu_transcoder));
11464         int vsync = I915_READ(VSYNC(cpu_transcoder));
11465         enum pipe pipe = intel_crtc->pipe;
11466
11467         mode = kzalloc(sizeof(*mode), GFP_KERNEL);
11468         if (!mode)
11469                 return NULL;
11470
11471         pipe_config = kzalloc(sizeof(*pipe_config), GFP_KERNEL);
11472         if (!pipe_config) {
11473                 kfree(mode);
11474                 return NULL;
11475         }
11476
11477         /*
11478          * Construct a pipe_config sufficient for getting the clock info
11479          * back out of crtc_clock_get.
11480          *
11481          * Note, if LVDS ever uses a non-1 pixel multiplier, we'll need
11482          * to use a real value here instead.
11483          */
11484         pipe_config->cpu_transcoder = (enum transcoder) pipe;
11485         pipe_config->pixel_multiplier = 1;
11486         pipe_config->dpll_hw_state.dpll = I915_READ(DPLL(pipe));
11487         pipe_config->dpll_hw_state.fp0 = I915_READ(FP0(pipe));
11488         pipe_config->dpll_hw_state.fp1 = I915_READ(FP1(pipe));
11489         i9xx_crtc_clock_get(intel_crtc, pipe_config);
11490
11491         mode->clock = pipe_config->port_clock / pipe_config->pixel_multiplier;
11492         mode->hdisplay = (htot & 0xffff) + 1;
11493         mode->htotal = ((htot & 0xffff0000) >> 16) + 1;
11494         mode->hsync_start = (hsync & 0xffff) + 1;
11495         mode->hsync_end = ((hsync & 0xffff0000) >> 16) + 1;
11496         mode->vdisplay = (vtot & 0xffff) + 1;
11497         mode->vtotal = ((vtot & 0xffff0000) >> 16) + 1;
11498         mode->vsync_start = (vsync & 0xffff) + 1;
11499         mode->vsync_end = ((vsync & 0xffff0000) >> 16) + 1;
11500
11501         drm_mode_set_name(mode);
11502
11503         kfree(pipe_config);
11504
11505         return mode;
11506 }
11507
11508 static void intel_crtc_destroy(struct drm_crtc *crtc)
11509 {
11510         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
11511         struct drm_device *dev = crtc->dev;
11512         struct intel_flip_work *work;
11513
11514         spin_lock_irq(&dev->event_lock);
11515         work = intel_crtc->flip_work;
11516         intel_crtc->flip_work = NULL;
11517         spin_unlock_irq(&dev->event_lock);
11518
11519         if (work) {
11520                 cancel_work_sync(&work->mmio_work);
11521                 cancel_work_sync(&work->unpin_work);
11522                 kfree(work);
11523         }
11524
11525         drm_crtc_cleanup(crtc);
11526
11527         kfree(intel_crtc);
11528 }
11529
11530 static void intel_unpin_work_fn(struct work_struct *__work)
11531 {
11532         struct intel_flip_work *work =
11533                 container_of(__work, struct intel_flip_work, unpin_work);
11534         struct intel_crtc *crtc = to_intel_crtc(work->crtc);
11535         struct drm_device *dev = crtc->base.dev;
11536         struct drm_plane *primary = crtc->base.primary;
11537
11538         if (is_mmio_work(work))
11539                 flush_work(&work->mmio_work);
11540
11541         mutex_lock(&dev->struct_mutex);
11542         intel_unpin_fb_obj(work->old_fb, primary->state->rotation);
11543         i915_gem_object_put(work->pending_flip_obj);
11544         mutex_unlock(&dev->struct_mutex);
11545
11546         i915_gem_request_put(work->flip_queued_req);
11547
11548         intel_frontbuffer_flip_complete(to_i915(dev),
11549                                         to_intel_plane(primary)->frontbuffer_bit);
11550         intel_fbc_post_update(crtc);
11551         drm_framebuffer_unreference(work->old_fb);
11552
11553         BUG_ON(atomic_read(&crtc->unpin_work_count) == 0);
11554         atomic_dec(&crtc->unpin_work_count);
11555
11556         kfree(work);
11557 }
11558
11559 /* Is 'a' after or equal to 'b'? */
11560 static bool g4x_flip_count_after_eq(u32 a, u32 b)
11561 {
11562         return !((a - b) & 0x80000000);
11563 }
11564
11565 static bool __pageflip_finished_cs(struct intel_crtc *crtc,
11566                                    struct intel_flip_work *work)
11567 {
11568         struct drm_device *dev = crtc->base.dev;
11569         struct drm_i915_private *dev_priv = to_i915(dev);
11570
11571         if (abort_flip_on_reset(crtc))
11572                 return true;
11573
11574         /*
11575          * The relevant registers doen't exist on pre-ctg.
11576          * As the flip done interrupt doesn't trigger for mmio
11577          * flips on gmch platforms, a flip count check isn't
11578          * really needed there. But since ctg has the registers,
11579          * include it in the check anyway.
11580          */
11581         if (INTEL_INFO(dev)->gen < 5 && !IS_G4X(dev))
11582                 return true;
11583
11584         /*
11585          * BDW signals flip done immediately if the plane
11586          * is disabled, even if the plane enable is already
11587          * armed to occur at the next vblank :(
11588          */
11589
11590         /*
11591          * A DSPSURFLIVE check isn't enough in case the mmio and CS flips
11592          * used the same base address. In that case the mmio flip might
11593          * have completed, but the CS hasn't even executed the flip yet.
11594          *
11595          * A flip count check isn't enough as the CS might have updated
11596          * the base address just after start of vblank, but before we
11597          * managed to process the interrupt. This means we'd complete the
11598          * CS flip too soon.
11599          *
11600          * Combining both checks should get us a good enough result. It may
11601          * still happen that the CS flip has been executed, but has not
11602          * yet actually completed. But in case the base address is the same
11603          * anyway, we don't really care.
11604          */
11605         return (I915_READ(DSPSURFLIVE(crtc->plane)) & ~0xfff) ==
11606                 crtc->flip_work->gtt_offset &&
11607                 g4x_flip_count_after_eq(I915_READ(PIPE_FLIPCOUNT_G4X(crtc->pipe)),
11608                                     crtc->flip_work->flip_count);
11609 }
11610
11611 static bool
11612 __pageflip_finished_mmio(struct intel_crtc *crtc,
11613                                struct intel_flip_work *work)
11614 {
11615         /*
11616          * MMIO work completes when vblank is different from
11617          * flip_queued_vblank.
11618          *
11619          * Reset counter value doesn't matter, this is handled by
11620          * i915_wait_request finishing early, so no need to handle
11621          * reset here.
11622          */
11623         return intel_crtc_get_vblank_counter(crtc) != work->flip_queued_vblank;
11624 }
11625
11626
11627 static bool pageflip_finished(struct intel_crtc *crtc,
11628                               struct intel_flip_work *work)
11629 {
11630         if (!atomic_read(&work->pending))
11631                 return false;
11632
11633         smp_rmb();
11634
11635         if (is_mmio_work(work))
11636                 return __pageflip_finished_mmio(crtc, work);
11637         else
11638                 return __pageflip_finished_cs(crtc, work);
11639 }
11640
11641 void intel_finish_page_flip_cs(struct drm_i915_private *dev_priv, int pipe)
11642 {
11643         struct drm_device *dev = &dev_priv->drm;
11644         struct drm_crtc *crtc = dev_priv->pipe_to_crtc_mapping[pipe];
11645         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
11646         struct intel_flip_work *work;
11647         unsigned long flags;
11648
11649         /* Ignore early vblank irqs */
11650         if (!crtc)
11651                 return;
11652
11653         /*
11654          * This is called both by irq handlers and the reset code (to complete
11655          * lost pageflips) so needs the full irqsave spinlocks.
11656          */
11657         spin_lock_irqsave(&dev->event_lock, flags);
11658         work = intel_crtc->flip_work;
11659
11660         if (work != NULL &&
11661             !is_mmio_work(work) &&
11662             pageflip_finished(intel_crtc, work))
11663                 page_flip_completed(intel_crtc);
11664
11665         spin_unlock_irqrestore(&dev->event_lock, flags);
11666 }
11667
11668 void intel_finish_page_flip_mmio(struct drm_i915_private *dev_priv, int pipe)
11669 {
11670         struct drm_device *dev = &dev_priv->drm;
11671         struct drm_crtc *crtc = dev_priv->pipe_to_crtc_mapping[pipe];
11672         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
11673         struct intel_flip_work *work;
11674         unsigned long flags;
11675
11676         /* Ignore early vblank irqs */
11677         if (!crtc)
11678                 return;
11679
11680         /*
11681          * This is called both by irq handlers and the reset code (to complete
11682          * lost pageflips) so needs the full irqsave spinlocks.
11683          */
11684         spin_lock_irqsave(&dev->event_lock, flags);
11685         work = intel_crtc->flip_work;
11686
11687         if (work != NULL &&
11688             is_mmio_work(work) &&
11689             pageflip_finished(intel_crtc, work))
11690                 page_flip_completed(intel_crtc);
11691
11692         spin_unlock_irqrestore(&dev->event_lock, flags);
11693 }
11694
11695 static inline void intel_mark_page_flip_active(struct intel_crtc *crtc,
11696                                                struct intel_flip_work *work)
11697 {
11698         work->flip_queued_vblank = intel_crtc_get_vblank_counter(crtc);
11699
11700         /* Ensure that the work item is consistent when activating it ... */
11701         smp_mb__before_atomic();
11702         atomic_set(&work->pending, 1);
11703 }
11704
11705 static int intel_gen2_queue_flip(struct drm_device *dev,
11706                                  struct drm_crtc *crtc,
11707                                  struct drm_framebuffer *fb,
11708                                  struct drm_i915_gem_object *obj,
11709                                  struct drm_i915_gem_request *req,
11710                                  uint32_t flags)
11711 {
11712         struct intel_ring *ring = req->ring;
11713         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
11714         u32 flip_mask;
11715         int ret;
11716
11717         ret = intel_ring_begin(req, 6);
11718         if (ret)
11719                 return ret;
11720
11721         /* Can't queue multiple flips, so wait for the previous
11722          * one to finish before executing the next.
11723          */
11724         if (intel_crtc->plane)
11725                 flip_mask = MI_WAIT_FOR_PLANE_B_FLIP;
11726         else
11727                 flip_mask = MI_WAIT_FOR_PLANE_A_FLIP;
11728         intel_ring_emit(ring, MI_WAIT_FOR_EVENT | flip_mask);
11729         intel_ring_emit(ring, MI_NOOP);
11730         intel_ring_emit(ring, MI_DISPLAY_FLIP |
11731                         MI_DISPLAY_FLIP_PLANE(intel_crtc->plane));
11732         intel_ring_emit(ring, fb->pitches[0]);
11733         intel_ring_emit(ring, intel_crtc->flip_work->gtt_offset);
11734         intel_ring_emit(ring, 0); /* aux display base address, unused */
11735
11736         return 0;
11737 }
11738
11739 static int intel_gen3_queue_flip(struct drm_device *dev,
11740                                  struct drm_crtc *crtc,
11741                                  struct drm_framebuffer *fb,
11742                                  struct drm_i915_gem_object *obj,
11743                                  struct drm_i915_gem_request *req,
11744                                  uint32_t flags)
11745 {
11746         struct intel_ring *ring = req->ring;
11747         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
11748         u32 flip_mask;
11749         int ret;
11750
11751         ret = intel_ring_begin(req, 6);
11752         if (ret)
11753                 return ret;
11754
11755         if (intel_crtc->plane)
11756                 flip_mask = MI_WAIT_FOR_PLANE_B_FLIP;
11757         else
11758                 flip_mask = MI_WAIT_FOR_PLANE_A_FLIP;
11759         intel_ring_emit(ring, MI_WAIT_FOR_EVENT | flip_mask);
11760         intel_ring_emit(ring, MI_NOOP);
11761         intel_ring_emit(ring, MI_DISPLAY_FLIP_I915 |
11762                         MI_DISPLAY_FLIP_PLANE(intel_crtc->plane));
11763         intel_ring_emit(ring, fb->pitches[0]);
11764         intel_ring_emit(ring, intel_crtc->flip_work->gtt_offset);
11765         intel_ring_emit(ring, MI_NOOP);
11766
11767         return 0;
11768 }
11769
11770 static int intel_gen4_queue_flip(struct drm_device *dev,
11771                                  struct drm_crtc *crtc,
11772                                  struct drm_framebuffer *fb,
11773                                  struct drm_i915_gem_object *obj,
11774                                  struct drm_i915_gem_request *req,
11775                                  uint32_t flags)
11776 {
11777         struct intel_ring *ring = req->ring;
11778         struct drm_i915_private *dev_priv = to_i915(dev);
11779         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
11780         uint32_t pf, pipesrc;
11781         int ret;
11782
11783         ret = intel_ring_begin(req, 4);
11784         if (ret)
11785                 return ret;
11786
11787         /* i965+ uses the linear or tiled offsets from the
11788          * Display Registers (which do not change across a page-flip)
11789          * so we need only reprogram the base address.
11790          */
11791         intel_ring_emit(ring, MI_DISPLAY_FLIP |
11792                         MI_DISPLAY_FLIP_PLANE(intel_crtc->plane));
11793         intel_ring_emit(ring, fb->pitches[0]);
11794         intel_ring_emit(ring, intel_crtc->flip_work->gtt_offset |
11795                         intel_fb_modifier_to_tiling(fb->modifier[0]));
11796
11797         /* XXX Enabling the panel-fitter across page-flip is so far
11798          * untested on non-native modes, so ignore it for now.
11799          * pf = I915_READ(pipe == 0 ? PFA_CTL_1 : PFB_CTL_1) & PF_ENABLE;
11800          */
11801         pf = 0;
11802         pipesrc = I915_READ(PIPESRC(intel_crtc->pipe)) & 0x0fff0fff;
11803         intel_ring_emit(ring, pf | pipesrc);
11804
11805         return 0;
11806 }
11807
11808 static int intel_gen6_queue_flip(struct drm_device *dev,
11809                                  struct drm_crtc *crtc,
11810                                  struct drm_framebuffer *fb,
11811                                  struct drm_i915_gem_object *obj,
11812                                  struct drm_i915_gem_request *req,
11813                                  uint32_t flags)
11814 {
11815         struct intel_ring *ring = req->ring;
11816         struct drm_i915_private *dev_priv = to_i915(dev);
11817         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
11818         uint32_t pf, pipesrc;
11819         int ret;
11820
11821         ret = intel_ring_begin(req, 4);
11822         if (ret)
11823                 return ret;
11824
11825         intel_ring_emit(ring, MI_DISPLAY_FLIP |
11826                         MI_DISPLAY_FLIP_PLANE(intel_crtc->plane));
11827         intel_ring_emit(ring, fb->pitches[0] |
11828                         intel_fb_modifier_to_tiling(fb->modifier[0]));
11829         intel_ring_emit(ring, intel_crtc->flip_work->gtt_offset);
11830
11831         /* Contrary to the suggestions in the documentation,
11832          * "Enable Panel Fitter" does not seem to be required when page
11833          * flipping with a non-native mode, and worse causes a normal
11834          * modeset to fail.
11835          * pf = I915_READ(PF_CTL(intel_crtc->pipe)) & PF_ENABLE;
11836          */
11837         pf = 0;
11838         pipesrc = I915_READ(PIPESRC(intel_crtc->pipe)) & 0x0fff0fff;
11839         intel_ring_emit(ring, pf | pipesrc);
11840
11841         return 0;
11842 }
11843
11844 static int intel_gen7_queue_flip(struct drm_device *dev,
11845                                  struct drm_crtc *crtc,
11846                                  struct drm_framebuffer *fb,
11847                                  struct drm_i915_gem_object *obj,
11848                                  struct drm_i915_gem_request *req,
11849                                  uint32_t flags)
11850 {
11851         struct intel_ring *ring = req->ring;
11852         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
11853         uint32_t plane_bit = 0;
11854         int len, ret;
11855
11856         switch (intel_crtc->plane) {
11857         case PLANE_A:
11858                 plane_bit = MI_DISPLAY_FLIP_IVB_PLANE_A;
11859                 break;
11860         case PLANE_B:
11861                 plane_bit = MI_DISPLAY_FLIP_IVB_PLANE_B;
11862                 break;
11863         case PLANE_C:
11864                 plane_bit = MI_DISPLAY_FLIP_IVB_PLANE_C;
11865                 break;
11866         default:
11867                 WARN_ONCE(1, "unknown plane in flip command\n");
11868                 return -ENODEV;
11869         }
11870
11871         len = 4;
11872         if (req->engine->id == RCS) {
11873                 len += 6;
11874                 /*
11875                  * On Gen 8, SRM is now taking an extra dword to accommodate
11876                  * 48bits addresses, and we need a NOOP for the batch size to
11877                  * stay even.
11878                  */
11879                 if (IS_GEN8(dev))
11880                         len += 2;
11881         }
11882
11883         /*
11884          * BSpec MI_DISPLAY_FLIP for IVB:
11885          * "The full packet must be contained within the same cache line."
11886          *
11887          * Currently the LRI+SRM+MI_DISPLAY_FLIP all fit within the same
11888          * cacheline, if we ever start emitting more commands before
11889          * the MI_DISPLAY_FLIP we may need to first emit everything else,
11890          * then do the cacheline alignment, and finally emit the
11891          * MI_DISPLAY_FLIP.
11892          */
11893         ret = intel_ring_cacheline_align(req);
11894         if (ret)
11895                 return ret;
11896
11897         ret = intel_ring_begin(req, len);
11898         if (ret)
11899                 return ret;
11900
11901         /* Unmask the flip-done completion message. Note that the bspec says that
11902          * we should do this for both the BCS and RCS, and that we must not unmask
11903          * more than one flip event at any time (or ensure that one flip message
11904          * can be sent by waiting for flip-done prior to queueing new flips).
11905          * Experimentation says that BCS works despite DERRMR masking all
11906          * flip-done completion events and that unmasking all planes at once
11907          * for the RCS also doesn't appear to drop events. Setting the DERRMR
11908          * to zero does lead to lockups within MI_DISPLAY_FLIP.
11909          */
11910         if (req->engine->id == RCS) {
11911                 intel_ring_emit(ring, MI_LOAD_REGISTER_IMM(1));
11912                 intel_ring_emit_reg(ring, DERRMR);
11913                 intel_ring_emit(ring, ~(DERRMR_PIPEA_PRI_FLIP_DONE |
11914                                           DERRMR_PIPEB_PRI_FLIP_DONE |
11915                                           DERRMR_PIPEC_PRI_FLIP_DONE));
11916                 if (IS_GEN8(dev))
11917                         intel_ring_emit(ring, MI_STORE_REGISTER_MEM_GEN8 |
11918                                               MI_SRM_LRM_GLOBAL_GTT);
11919                 else
11920                         intel_ring_emit(ring, MI_STORE_REGISTER_MEM |
11921                                               MI_SRM_LRM_GLOBAL_GTT);
11922                 intel_ring_emit_reg(ring, DERRMR);
11923                 intel_ring_emit(ring,
11924                                 i915_ggtt_offset(req->engine->scratch) + 256);
11925                 if (IS_GEN8(dev)) {
11926                         intel_ring_emit(ring, 0);
11927                         intel_ring_emit(ring, MI_NOOP);
11928                 }
11929         }
11930
11931         intel_ring_emit(ring, MI_DISPLAY_FLIP_I915 | plane_bit);
11932         intel_ring_emit(ring, fb->pitches[0] |
11933                         intel_fb_modifier_to_tiling(fb->modifier[0]));
11934         intel_ring_emit(ring, intel_crtc->flip_work->gtt_offset);
11935         intel_ring_emit(ring, (MI_NOOP));
11936
11937         return 0;
11938 }
11939
11940 static bool use_mmio_flip(struct intel_engine_cs *engine,
11941                           struct drm_i915_gem_object *obj)
11942 {
11943         struct reservation_object *resv;
11944
11945         /*
11946          * This is not being used for older platforms, because
11947          * non-availability of flip done interrupt forces us to use
11948          * CS flips. Older platforms derive flip done using some clever
11949          * tricks involving the flip_pending status bits and vblank irqs.
11950          * So using MMIO flips there would disrupt this mechanism.
11951          */
11952
11953         if (engine == NULL)
11954                 return true;
11955
11956         if (INTEL_GEN(engine->i915) < 5)
11957                 return false;
11958
11959         if (i915.use_mmio_flip < 0)
11960                 return false;
11961         else if (i915.use_mmio_flip > 0)
11962                 return true;
11963         else if (i915.enable_execlists)
11964                 return true;
11965
11966         resv = i915_gem_object_get_dmabuf_resv(obj);
11967         if (resv && !reservation_object_test_signaled_rcu(resv, false))
11968                 return true;
11969
11970         return engine != i915_gem_active_get_engine(&obj->last_write,
11971                                                     &obj->base.dev->struct_mutex);
11972 }
11973
11974 static void skl_do_mmio_flip(struct intel_crtc *intel_crtc,
11975                              unsigned int rotation,
11976                              struct intel_flip_work *work)
11977 {
11978         struct drm_device *dev = intel_crtc->base.dev;
11979         struct drm_i915_private *dev_priv = to_i915(dev);
11980         struct drm_framebuffer *fb = intel_crtc->base.primary->fb;
11981         const enum pipe pipe = intel_crtc->pipe;
11982         u32 ctl, stride = skl_plane_stride(fb, 0, rotation);
11983
11984         ctl = I915_READ(PLANE_CTL(pipe, 0));
11985         ctl &= ~PLANE_CTL_TILED_MASK;
11986         switch (fb->modifier[0]) {
11987         case DRM_FORMAT_MOD_NONE:
11988                 break;
11989         case I915_FORMAT_MOD_X_TILED:
11990                 ctl |= PLANE_CTL_TILED_X;
11991                 break;
11992         case I915_FORMAT_MOD_Y_TILED:
11993                 ctl |= PLANE_CTL_TILED_Y;
11994                 break;
11995         case I915_FORMAT_MOD_Yf_TILED:
11996                 ctl |= PLANE_CTL_TILED_YF;
11997                 break;
11998         default:
11999                 MISSING_CASE(fb->modifier[0]);
12000         }
12001
12002         /*
12003          * Both PLANE_CTL and PLANE_STRIDE are not updated on vblank but on
12004          * PLANE_SURF updates, the update is then guaranteed to be atomic.
12005          */
12006         I915_WRITE(PLANE_CTL(pipe, 0), ctl);
12007         I915_WRITE(PLANE_STRIDE(pipe, 0), stride);
12008
12009         I915_WRITE(PLANE_SURF(pipe, 0), work->gtt_offset);
12010         POSTING_READ(PLANE_SURF(pipe, 0));
12011 }
12012
12013 static void ilk_do_mmio_flip(struct intel_crtc *intel_crtc,
12014                              struct intel_flip_work *work)
12015 {
12016         struct drm_device *dev = intel_crtc->base.dev;
12017         struct drm_i915_private *dev_priv = to_i915(dev);
12018         struct drm_framebuffer *fb = intel_crtc->base.primary->fb;
12019         i915_reg_t reg = DSPCNTR(intel_crtc->plane);
12020         u32 dspcntr;
12021
12022         dspcntr = I915_READ(reg);
12023
12024         if (fb->modifier[0] == I915_FORMAT_MOD_X_TILED)
12025                 dspcntr |= DISPPLANE_TILED;
12026         else
12027                 dspcntr &= ~DISPPLANE_TILED;
12028
12029         I915_WRITE(reg, dspcntr);
12030
12031         I915_WRITE(DSPSURF(intel_crtc->plane), work->gtt_offset);
12032         POSTING_READ(DSPSURF(intel_crtc->plane));
12033 }
12034
12035 static void intel_mmio_flip_work_func(struct work_struct *w)
12036 {
12037         struct intel_flip_work *work =
12038                 container_of(w, struct intel_flip_work, mmio_work);
12039         struct intel_crtc *crtc = to_intel_crtc(work->crtc);
12040         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
12041         struct intel_framebuffer *intel_fb =
12042                 to_intel_framebuffer(crtc->base.primary->fb);
12043         struct drm_i915_gem_object *obj = intel_fb->obj;
12044         struct reservation_object *resv;
12045
12046         if (work->flip_queued_req)
12047                 WARN_ON(i915_wait_request(work->flip_queued_req,
12048                                           0, NULL, NO_WAITBOOST));
12049
12050         /* For framebuffer backed by dmabuf, wait for fence */
12051         resv = i915_gem_object_get_dmabuf_resv(obj);
12052         if (resv)
12053                 WARN_ON(reservation_object_wait_timeout_rcu(resv, false, false,
12054                                                             MAX_SCHEDULE_TIMEOUT) < 0);
12055
12056         intel_pipe_update_start(crtc);
12057
12058         if (INTEL_GEN(dev_priv) >= 9)
12059                 skl_do_mmio_flip(crtc, work->rotation, work);
12060         else
12061                 /* use_mmio_flip() retricts MMIO flips to ilk+ */
12062                 ilk_do_mmio_flip(crtc, work);
12063
12064         intel_pipe_update_end(crtc, work);
12065 }
12066
12067 static int intel_default_queue_flip(struct drm_device *dev,
12068                                     struct drm_crtc *crtc,
12069                                     struct drm_framebuffer *fb,
12070                                     struct drm_i915_gem_object *obj,
12071                                     struct drm_i915_gem_request *req,
12072                                     uint32_t flags)
12073 {
12074         return -ENODEV;
12075 }
12076
12077 static bool __pageflip_stall_check_cs(struct drm_i915_private *dev_priv,
12078                                       struct intel_crtc *intel_crtc,
12079                                       struct intel_flip_work *work)
12080 {
12081         u32 addr, vblank;
12082
12083         if (!atomic_read(&work->pending))
12084                 return false;
12085
12086         smp_rmb();
12087
12088         vblank = intel_crtc_get_vblank_counter(intel_crtc);
12089         if (work->flip_ready_vblank == 0) {
12090                 if (work->flip_queued_req &&
12091                     !i915_gem_request_completed(work->flip_queued_req))
12092                         return false;
12093
12094                 work->flip_ready_vblank = vblank;
12095         }
12096
12097         if (vblank - work->flip_ready_vblank < 3)
12098                 return false;
12099
12100         /* Potential stall - if we see that the flip has happened,
12101          * assume a missed interrupt. */
12102         if (INTEL_GEN(dev_priv) >= 4)
12103                 addr = I915_HI_DISPBASE(I915_READ(DSPSURF(intel_crtc->plane)));
12104         else
12105                 addr = I915_READ(DSPADDR(intel_crtc->plane));
12106
12107         /* There is a potential issue here with a false positive after a flip
12108          * to the same address. We could address this by checking for a
12109          * non-incrementing frame counter.
12110          */
12111         return addr == work->gtt_offset;
12112 }
12113
12114 void intel_check_page_flip(struct drm_i915_private *dev_priv, int pipe)
12115 {
12116         struct drm_device *dev = &dev_priv->drm;
12117         struct drm_crtc *crtc = dev_priv->pipe_to_crtc_mapping[pipe];
12118         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
12119         struct intel_flip_work *work;
12120
12121         WARN_ON(!in_interrupt());
12122
12123         if (crtc == NULL)
12124                 return;
12125
12126         spin_lock(&dev->event_lock);
12127         work = intel_crtc->flip_work;
12128
12129         if (work != NULL && !is_mmio_work(work) &&
12130             __pageflip_stall_check_cs(dev_priv, intel_crtc, work)) {
12131                 WARN_ONCE(1,
12132                           "Kicking stuck page flip: queued at %d, now %d\n",
12133                         work->flip_queued_vblank, intel_crtc_get_vblank_counter(intel_crtc));
12134                 page_flip_completed(intel_crtc);
12135                 work = NULL;
12136         }
12137
12138         if (work != NULL && !is_mmio_work(work) &&
12139             intel_crtc_get_vblank_counter(intel_crtc) - work->flip_queued_vblank > 1)
12140                 intel_queue_rps_boost_for_request(work->flip_queued_req);
12141         spin_unlock(&dev->event_lock);
12142 }
12143
12144 static int intel_crtc_page_flip(struct drm_crtc *crtc,
12145                                 struct drm_framebuffer *fb,
12146                                 struct drm_pending_vblank_event *event,
12147                                 uint32_t page_flip_flags)
12148 {
12149         struct drm_device *dev = crtc->dev;
12150         struct drm_i915_private *dev_priv = to_i915(dev);
12151         struct drm_framebuffer *old_fb = crtc->primary->fb;
12152         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
12153         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
12154         struct drm_plane *primary = crtc->primary;
12155         enum pipe pipe = intel_crtc->pipe;
12156         struct intel_flip_work *work;
12157         struct intel_engine_cs *engine;
12158         bool mmio_flip;
12159         struct drm_i915_gem_request *request;
12160         struct i915_vma *vma;
12161         int ret;
12162
12163         /*
12164          * drm_mode_page_flip_ioctl() should already catch this, but double
12165          * check to be safe.  In the future we may enable pageflipping from
12166          * a disabled primary plane.
12167          */
12168         if (WARN_ON(intel_fb_obj(old_fb) == NULL))
12169                 return -EBUSY;
12170
12171         /* Can't change pixel format via MI display flips. */
12172         if (fb->pixel_format != crtc->primary->fb->pixel_format)
12173                 return -EINVAL;
12174
12175         /*
12176          * TILEOFF/LINOFF registers can't be changed via MI display flips.
12177          * Note that pitch changes could also affect these register.
12178          */
12179         if (INTEL_INFO(dev)->gen > 3 &&
12180             (fb->offsets[0] != crtc->primary->fb->offsets[0] ||
12181              fb->pitches[0] != crtc->primary->fb->pitches[0]))
12182                 return -EINVAL;
12183
12184         if (i915_terminally_wedged(&dev_priv->gpu_error))
12185                 goto out_hang;
12186
12187         work = kzalloc(sizeof(*work), GFP_KERNEL);
12188         if (work == NULL)
12189                 return -ENOMEM;
12190
12191         work->event = event;
12192         work->crtc = crtc;
12193         work->old_fb = old_fb;
12194         INIT_WORK(&work->unpin_work, intel_unpin_work_fn);
12195
12196         ret = drm_crtc_vblank_get(crtc);
12197         if (ret)
12198                 goto free_work;
12199
12200         /* We borrow the event spin lock for protecting flip_work */
12201         spin_lock_irq(&dev->event_lock);
12202         if (intel_crtc->flip_work) {
12203                 /* Before declaring the flip queue wedged, check if
12204                  * the hardware completed the operation behind our backs.
12205                  */
12206                 if (pageflip_finished(intel_crtc, intel_crtc->flip_work)) {
12207                         DRM_DEBUG_DRIVER("flip queue: previous flip completed, continuing\n");
12208                         page_flip_completed(intel_crtc);
12209                 } else {
12210                         DRM_DEBUG_DRIVER("flip queue: crtc already busy\n");
12211                         spin_unlock_irq(&dev->event_lock);
12212
12213                         drm_crtc_vblank_put(crtc);
12214                         kfree(work);
12215                         return -EBUSY;
12216                 }
12217         }
12218         intel_crtc->flip_work = work;
12219         spin_unlock_irq(&dev->event_lock);
12220
12221         if (atomic_read(&intel_crtc->unpin_work_count) >= 2)
12222                 flush_workqueue(dev_priv->wq);
12223
12224         /* Reference the objects for the scheduled work. */
12225         drm_framebuffer_reference(work->old_fb);
12226
12227         crtc->primary->fb = fb;
12228         update_state_fb(crtc->primary);
12229
12230         work->pending_flip_obj = i915_gem_object_get(obj);
12231
12232         ret = i915_mutex_lock_interruptible(dev);
12233         if (ret)
12234                 goto cleanup;
12235
12236         intel_crtc->reset_count = i915_reset_count(&dev_priv->gpu_error);
12237         if (i915_reset_in_progress_or_wedged(&dev_priv->gpu_error)) {
12238                 ret = -EIO;
12239                 goto cleanup;
12240         }
12241
12242         atomic_inc(&intel_crtc->unpin_work_count);
12243
12244         if (INTEL_INFO(dev)->gen >= 5 || IS_G4X(dev))
12245                 work->flip_count = I915_READ(PIPE_FLIPCOUNT_G4X(pipe)) + 1;
12246
12247         if (IS_VALLEYVIEW(dev) || IS_CHERRYVIEW(dev)) {
12248                 engine = dev_priv->engine[BCS];
12249                 if (fb->modifier[0] != old_fb->modifier[0])
12250                         /* vlv: DISPLAY_FLIP fails to change tiling */
12251                         engine = NULL;
12252         } else if (IS_IVYBRIDGE(dev_priv) || IS_HASWELL(dev_priv)) {
12253                 engine = dev_priv->engine[BCS];
12254         } else if (INTEL_INFO(dev)->gen >= 7) {
12255                 engine = i915_gem_active_get_engine(&obj->last_write,
12256                                                     &obj->base.dev->struct_mutex);
12257                 if (engine == NULL || engine->id != RCS)
12258                         engine = dev_priv->engine[BCS];
12259         } else {
12260                 engine = dev_priv->engine[RCS];
12261         }
12262
12263         mmio_flip = use_mmio_flip(engine, obj);
12264
12265         vma = intel_pin_and_fence_fb_obj(fb, primary->state->rotation);
12266         if (IS_ERR(vma)) {
12267                 ret = PTR_ERR(vma);
12268                 goto cleanup_pending;
12269         }
12270
12271         work->gtt_offset = intel_fb_gtt_offset(fb, primary->state->rotation);
12272         work->gtt_offset += intel_crtc->dspaddr_offset;
12273         work->rotation = crtc->primary->state->rotation;
12274
12275         /*
12276          * There's the potential that the next frame will not be compatible with
12277          * FBC, so we want to call pre_update() before the actual page flip.
12278          * The problem is that pre_update() caches some information about the fb
12279          * object, so we want to do this only after the object is pinned. Let's
12280          * be on the safe side and do this immediately before scheduling the
12281          * flip.
12282          */
12283         intel_fbc_pre_update(intel_crtc, intel_crtc->config,
12284                              to_intel_plane_state(primary->state));
12285
12286         if (mmio_flip) {
12287                 INIT_WORK(&work->mmio_work, intel_mmio_flip_work_func);
12288
12289                 work->flip_queued_req = i915_gem_active_get(&obj->last_write,
12290                                                             &obj->base.dev->struct_mutex);
12291                 queue_work(system_unbound_wq, &work->mmio_work);
12292         } else {
12293                 request = i915_gem_request_alloc(engine, engine->last_context);
12294                 if (IS_ERR(request)) {
12295                         ret = PTR_ERR(request);
12296                         goto cleanup_unpin;
12297                 }
12298
12299                 ret = i915_gem_request_await_object(request, obj, false);
12300                 if (ret)
12301                         goto cleanup_request;
12302
12303                 ret = dev_priv->display.queue_flip(dev, crtc, fb, obj, request,
12304                                                    page_flip_flags);
12305                 if (ret)
12306                         goto cleanup_request;
12307
12308                 intel_mark_page_flip_active(intel_crtc, work);
12309
12310                 work->flip_queued_req = i915_gem_request_get(request);
12311                 i915_add_request_no_flush(request);
12312         }
12313
12314         i915_gem_track_fb(intel_fb_obj(old_fb), obj,
12315                           to_intel_plane(primary)->frontbuffer_bit);
12316         mutex_unlock(&dev->struct_mutex);
12317
12318         intel_frontbuffer_flip_prepare(to_i915(dev),
12319                                        to_intel_plane(primary)->frontbuffer_bit);
12320
12321         trace_i915_flip_request(intel_crtc->plane, obj);
12322
12323         return 0;
12324
12325 cleanup_request:
12326         i915_add_request_no_flush(request);
12327 cleanup_unpin:
12328         intel_unpin_fb_obj(fb, crtc->primary->state->rotation);
12329 cleanup_pending:
12330         atomic_dec(&intel_crtc->unpin_work_count);
12331         mutex_unlock(&dev->struct_mutex);
12332 cleanup:
12333         crtc->primary->fb = old_fb;
12334         update_state_fb(crtc->primary);
12335
12336         i915_gem_object_put_unlocked(obj);
12337         drm_framebuffer_unreference(work->old_fb);
12338
12339         spin_lock_irq(&dev->event_lock);
12340         intel_crtc->flip_work = NULL;
12341         spin_unlock_irq(&dev->event_lock);
12342
12343         drm_crtc_vblank_put(crtc);
12344 free_work:
12345         kfree(work);
12346
12347         if (ret == -EIO) {
12348                 struct drm_atomic_state *state;
12349                 struct drm_plane_state *plane_state;
12350
12351 out_hang:
12352                 state = drm_atomic_state_alloc(dev);
12353                 if (!state)
12354                         return -ENOMEM;
12355                 state->acquire_ctx = drm_modeset_legacy_acquire_ctx(crtc);
12356
12357 retry:
12358                 plane_state = drm_atomic_get_plane_state(state, primary);
12359                 ret = PTR_ERR_OR_ZERO(plane_state);
12360                 if (!ret) {
12361                         drm_atomic_set_fb_for_plane(plane_state, fb);
12362
12363                         ret = drm_atomic_set_crtc_for_plane(plane_state, crtc);
12364                         if (!ret)
12365                                 ret = drm_atomic_commit(state);
12366                 }
12367
12368                 if (ret == -EDEADLK) {
12369                         drm_modeset_backoff(state->acquire_ctx);
12370                         drm_atomic_state_clear(state);
12371                         goto retry;
12372                 }
12373
12374                 if (ret)
12375                         drm_atomic_state_free(state);
12376
12377                 if (ret == 0 && event) {
12378                         spin_lock_irq(&dev->event_lock);
12379                         drm_crtc_send_vblank_event(crtc, event);
12380                         spin_unlock_irq(&dev->event_lock);
12381                 }
12382         }
12383         return ret;
12384 }
12385
12386
12387 /**
12388  * intel_wm_need_update - Check whether watermarks need updating
12389  * @plane: drm plane
12390  * @state: new plane state
12391  *
12392  * Check current plane state versus the new one to determine whether
12393  * watermarks need to be recalculated.
12394  *
12395  * Returns true or false.
12396  */
12397 static bool intel_wm_need_update(struct drm_plane *plane,
12398                                  struct drm_plane_state *state)
12399 {
12400         struct intel_plane_state *new = to_intel_plane_state(state);
12401         struct intel_plane_state *cur = to_intel_plane_state(plane->state);
12402
12403         /* Update watermarks on tiling or size changes. */
12404         if (new->base.visible != cur->base.visible)
12405                 return true;
12406
12407         if (!cur->base.fb || !new->base.fb)
12408                 return false;
12409
12410         if (cur->base.fb->modifier[0] != new->base.fb->modifier[0] ||
12411             cur->base.rotation != new->base.rotation ||
12412             drm_rect_width(&new->base.src) != drm_rect_width(&cur->base.src) ||
12413             drm_rect_height(&new->base.src) != drm_rect_height(&cur->base.src) ||
12414             drm_rect_width(&new->base.dst) != drm_rect_width(&cur->base.dst) ||
12415             drm_rect_height(&new->base.dst) != drm_rect_height(&cur->base.dst))
12416                 return true;
12417
12418         return false;
12419 }
12420
12421 static bool needs_scaling(struct intel_plane_state *state)
12422 {
12423         int src_w = drm_rect_width(&state->base.src) >> 16;
12424         int src_h = drm_rect_height(&state->base.src) >> 16;
12425         int dst_w = drm_rect_width(&state->base.dst);
12426         int dst_h = drm_rect_height(&state->base.dst);
12427
12428         return (src_w != dst_w || src_h != dst_h);
12429 }
12430
12431 int intel_plane_atomic_calc_changes(struct drm_crtc_state *crtc_state,
12432                                     struct drm_plane_state *plane_state)
12433 {
12434         struct intel_crtc_state *pipe_config = to_intel_crtc_state(crtc_state);
12435         struct drm_crtc *crtc = crtc_state->crtc;
12436         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
12437         struct drm_plane *plane = plane_state->plane;
12438         struct drm_device *dev = crtc->dev;
12439         struct drm_i915_private *dev_priv = to_i915(dev);
12440         struct intel_plane_state *old_plane_state =
12441                 to_intel_plane_state(plane->state);
12442         bool mode_changed = needs_modeset(crtc_state);
12443         bool was_crtc_enabled = crtc->state->active;
12444         bool is_crtc_enabled = crtc_state->active;
12445         bool turn_off, turn_on, visible, was_visible;
12446         struct drm_framebuffer *fb = plane_state->fb;
12447         int ret;
12448
12449         if (INTEL_GEN(dev) >= 9 && plane->type != DRM_PLANE_TYPE_CURSOR) {
12450                 ret = skl_update_scaler_plane(
12451                         to_intel_crtc_state(crtc_state),
12452                         to_intel_plane_state(plane_state));
12453                 if (ret)
12454                         return ret;
12455         }
12456
12457         was_visible = old_plane_state->base.visible;
12458         visible = to_intel_plane_state(plane_state)->base.visible;
12459
12460         if (!was_crtc_enabled && WARN_ON(was_visible))
12461                 was_visible = false;
12462
12463         /*
12464          * Visibility is calculated as if the crtc was on, but
12465          * after scaler setup everything depends on it being off
12466          * when the crtc isn't active.
12467          *
12468          * FIXME this is wrong for watermarks. Watermarks should also
12469          * be computed as if the pipe would be active. Perhaps move
12470          * per-plane wm computation to the .check_plane() hook, and
12471          * only combine the results from all planes in the current place?
12472          */
12473         if (!is_crtc_enabled)
12474                 to_intel_plane_state(plane_state)->base.visible = visible = false;
12475
12476         if (!was_visible && !visible)
12477                 return 0;
12478
12479         if (fb != old_plane_state->base.fb)
12480                 pipe_config->fb_changed = true;
12481
12482         turn_off = was_visible && (!visible || mode_changed);
12483         turn_on = visible && (!was_visible || mode_changed);
12484
12485         DRM_DEBUG_ATOMIC("[CRTC:%d:%s] has [PLANE:%d:%s] with fb %i\n",
12486                          intel_crtc->base.base.id,
12487                          intel_crtc->base.name,
12488                          plane->base.id, plane->name,
12489                          fb ? fb->base.id : -1);
12490
12491         DRM_DEBUG_ATOMIC("[PLANE:%d:%s] visible %i -> %i, off %i, on %i, ms %i\n",
12492                          plane->base.id, plane->name,
12493                          was_visible, visible,
12494                          turn_off, turn_on, mode_changed);
12495
12496         if (turn_on) {
12497                 pipe_config->update_wm_pre = true;
12498
12499                 /* must disable cxsr around plane enable/disable */
12500                 if (plane->type != DRM_PLANE_TYPE_CURSOR)
12501                         pipe_config->disable_cxsr = true;
12502         } else if (turn_off) {
12503                 pipe_config->update_wm_post = true;
12504
12505                 /* must disable cxsr around plane enable/disable */
12506                 if (plane->type != DRM_PLANE_TYPE_CURSOR)
12507                         pipe_config->disable_cxsr = true;
12508         } else if (intel_wm_need_update(plane, plane_state)) {
12509                 /* FIXME bollocks */
12510                 pipe_config->update_wm_pre = true;
12511                 pipe_config->update_wm_post = true;
12512         }
12513
12514         /* Pre-gen9 platforms need two-step watermark updates */
12515         if ((pipe_config->update_wm_pre || pipe_config->update_wm_post) &&
12516             INTEL_INFO(dev)->gen < 9 && dev_priv->display.optimize_watermarks)
12517                 to_intel_crtc_state(crtc_state)->wm.need_postvbl_update = true;
12518
12519         if (visible || was_visible)
12520                 pipe_config->fb_bits |= to_intel_plane(plane)->frontbuffer_bit;
12521
12522         /*
12523          * WaCxSRDisabledForSpriteScaling:ivb
12524          *
12525          * cstate->update_wm was already set above, so this flag will
12526          * take effect when we commit and program watermarks.
12527          */
12528         if (plane->type == DRM_PLANE_TYPE_OVERLAY && IS_IVYBRIDGE(dev_priv) &&
12529             needs_scaling(to_intel_plane_state(plane_state)) &&
12530             !needs_scaling(old_plane_state))
12531                 pipe_config->disable_lp_wm = true;
12532
12533         return 0;
12534 }
12535
12536 static bool encoders_cloneable(const struct intel_encoder *a,
12537                                const struct intel_encoder *b)
12538 {
12539         /* masks could be asymmetric, so check both ways */
12540         return a == b || (a->cloneable & (1 << b->type) &&
12541                           b->cloneable & (1 << a->type));
12542 }
12543
12544 static bool check_single_encoder_cloning(struct drm_atomic_state *state,
12545                                          struct intel_crtc *crtc,
12546                                          struct intel_encoder *encoder)
12547 {
12548         struct intel_encoder *source_encoder;
12549         struct drm_connector *connector;
12550         struct drm_connector_state *connector_state;
12551         int i;
12552
12553         for_each_connector_in_state(state, connector, connector_state, i) {
12554                 if (connector_state->crtc != &crtc->base)
12555                         continue;
12556
12557                 source_encoder =
12558                         to_intel_encoder(connector_state->best_encoder);
12559                 if (!encoders_cloneable(encoder, source_encoder))
12560                         return false;
12561         }
12562
12563         return true;
12564 }
12565
12566 static int intel_crtc_atomic_check(struct drm_crtc *crtc,
12567                                    struct drm_crtc_state *crtc_state)
12568 {
12569         struct drm_device *dev = crtc->dev;
12570         struct drm_i915_private *dev_priv = to_i915(dev);
12571         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
12572         struct intel_crtc_state *pipe_config =
12573                 to_intel_crtc_state(crtc_state);
12574         struct drm_atomic_state *state = crtc_state->state;
12575         int ret;
12576         bool mode_changed = needs_modeset(crtc_state);
12577
12578         if (mode_changed && !crtc_state->active)
12579                 pipe_config->update_wm_post = true;
12580
12581         if (mode_changed && crtc_state->enable &&
12582             dev_priv->display.crtc_compute_clock &&
12583             !WARN_ON(pipe_config->shared_dpll)) {
12584                 ret = dev_priv->display.crtc_compute_clock(intel_crtc,
12585                                                            pipe_config);
12586                 if (ret)
12587                         return ret;
12588         }
12589
12590         if (crtc_state->color_mgmt_changed) {
12591                 ret = intel_color_check(crtc, crtc_state);
12592                 if (ret)
12593                         return ret;
12594
12595                 /*
12596                  * Changing color management on Intel hardware is
12597                  * handled as part of planes update.
12598                  */
12599                 crtc_state->planes_changed = true;
12600         }
12601
12602         ret = 0;
12603         if (dev_priv->display.compute_pipe_wm) {
12604                 ret = dev_priv->display.compute_pipe_wm(pipe_config);
12605                 if (ret) {
12606                         DRM_DEBUG_KMS("Target pipe watermarks are invalid\n");
12607                         return ret;
12608                 }
12609         }
12610
12611         if (dev_priv->display.compute_intermediate_wm &&
12612             !to_intel_atomic_state(state)->skip_intermediate_wm) {
12613                 if (WARN_ON(!dev_priv->display.compute_pipe_wm))
12614                         return 0;
12615
12616                 /*
12617                  * Calculate 'intermediate' watermarks that satisfy both the
12618                  * old state and the new state.  We can program these
12619                  * immediately.
12620                  */
12621                 ret = dev_priv->display.compute_intermediate_wm(crtc->dev,
12622                                                                 intel_crtc,
12623                                                                 pipe_config);
12624                 if (ret) {
12625                         DRM_DEBUG_KMS("No valid intermediate pipe watermarks are possible\n");
12626                         return ret;
12627                 }
12628         } else if (dev_priv->display.compute_intermediate_wm) {
12629                 if (HAS_PCH_SPLIT(dev_priv) && INTEL_GEN(dev_priv) < 9)
12630                         pipe_config->wm.ilk.intermediate = pipe_config->wm.ilk.optimal;
12631         }
12632
12633         if (INTEL_INFO(dev)->gen >= 9) {
12634                 if (mode_changed)
12635                         ret = skl_update_scaler_crtc(pipe_config);
12636
12637                 if (!ret)
12638                         ret = intel_atomic_setup_scalers(dev, intel_crtc,
12639                                                          pipe_config);
12640         }
12641
12642         return ret;
12643 }
12644
12645 static const struct drm_crtc_helper_funcs intel_helper_funcs = {
12646         .mode_set_base_atomic = intel_pipe_set_base_atomic,
12647         .atomic_begin = intel_begin_crtc_commit,
12648         .atomic_flush = intel_finish_crtc_commit,
12649         .atomic_check = intel_crtc_atomic_check,
12650 };
12651
12652 static void intel_modeset_update_connector_atomic_state(struct drm_device *dev)
12653 {
12654         struct intel_connector *connector;
12655
12656         for_each_intel_connector(dev, connector) {
12657                 if (connector->base.state->crtc)
12658                         drm_connector_unreference(&connector->base);
12659
12660                 if (connector->base.encoder) {
12661                         connector->base.state->best_encoder =
12662                                 connector->base.encoder;
12663                         connector->base.state->crtc =
12664                                 connector->base.encoder->crtc;
12665
12666                         drm_connector_reference(&connector->base);
12667                 } else {
12668                         connector->base.state->best_encoder = NULL;
12669                         connector->base.state->crtc = NULL;
12670                 }
12671         }
12672 }
12673
12674 static void
12675 connected_sink_compute_bpp(struct intel_connector *connector,
12676                            struct intel_crtc_state *pipe_config)
12677 {
12678         const struct drm_display_info *info = &connector->base.display_info;
12679         int bpp = pipe_config->pipe_bpp;
12680
12681         DRM_DEBUG_KMS("[CONNECTOR:%d:%s] checking for sink bpp constrains\n",
12682                       connector->base.base.id,
12683                       connector->base.name);
12684
12685         /* Don't use an invalid EDID bpc value */
12686         if (info->bpc != 0 && info->bpc * 3 < bpp) {
12687                 DRM_DEBUG_KMS("clamping display bpp (was %d) to EDID reported max of %d\n",
12688                               bpp, info->bpc * 3);
12689                 pipe_config->pipe_bpp = info->bpc * 3;
12690         }
12691
12692         /* Clamp bpp to 8 on screens without EDID 1.4 */
12693         if (info->bpc == 0 && bpp > 24) {
12694                 DRM_DEBUG_KMS("clamping display bpp (was %d) to default limit of 24\n",
12695                               bpp);
12696                 pipe_config->pipe_bpp = 24;
12697         }
12698 }
12699
12700 static int
12701 compute_baseline_pipe_bpp(struct intel_crtc *crtc,
12702                           struct intel_crtc_state *pipe_config)
12703 {
12704         struct drm_device *dev = crtc->base.dev;
12705         struct drm_atomic_state *state;
12706         struct drm_connector *connector;
12707         struct drm_connector_state *connector_state;
12708         int bpp, i;
12709
12710         if ((IS_G4X(dev) || IS_VALLEYVIEW(dev) || IS_CHERRYVIEW(dev)))
12711                 bpp = 10*3;
12712         else if (INTEL_INFO(dev)->gen >= 5)
12713                 bpp = 12*3;
12714         else
12715                 bpp = 8*3;
12716
12717
12718         pipe_config->pipe_bpp = bpp;
12719
12720         state = pipe_config->base.state;
12721
12722         /* Clamp display bpp to EDID value */
12723         for_each_connector_in_state(state, connector, connector_state, i) {
12724                 if (connector_state->crtc != &crtc->base)
12725                         continue;
12726
12727                 connected_sink_compute_bpp(to_intel_connector(connector),
12728                                            pipe_config);
12729         }
12730
12731         return bpp;
12732 }
12733
12734 static void intel_dump_crtc_timings(const struct drm_display_mode *mode)
12735 {
12736         DRM_DEBUG_KMS("crtc timings: %d %d %d %d %d %d %d %d %d, "
12737                         "type: 0x%x flags: 0x%x\n",
12738                 mode->crtc_clock,
12739                 mode->crtc_hdisplay, mode->crtc_hsync_start,
12740                 mode->crtc_hsync_end, mode->crtc_htotal,
12741                 mode->crtc_vdisplay, mode->crtc_vsync_start,
12742                 mode->crtc_vsync_end, mode->crtc_vtotal, mode->type, mode->flags);
12743 }
12744
12745 static void intel_dump_pipe_config(struct intel_crtc *crtc,
12746                                    struct intel_crtc_state *pipe_config,
12747                                    const char *context)
12748 {
12749         struct drm_device *dev = crtc->base.dev;
12750         struct drm_i915_private *dev_priv = to_i915(dev);
12751         struct drm_plane *plane;
12752         struct intel_plane *intel_plane;
12753         struct intel_plane_state *state;
12754         struct drm_framebuffer *fb;
12755
12756         DRM_DEBUG_KMS("[CRTC:%d:%s]%s config %p for pipe %c\n",
12757                       crtc->base.base.id, crtc->base.name,
12758                       context, pipe_config, pipe_name(crtc->pipe));
12759
12760         DRM_DEBUG_KMS("cpu_transcoder: %s\n", transcoder_name(pipe_config->cpu_transcoder));
12761         DRM_DEBUG_KMS("pipe bpp: %i, dithering: %i\n",
12762                       pipe_config->pipe_bpp, pipe_config->dither);
12763         DRM_DEBUG_KMS("fdi/pch: %i, lanes: %i, gmch_m: %u, gmch_n: %u, link_m: %u, link_n: %u, tu: %u\n",
12764                       pipe_config->has_pch_encoder,
12765                       pipe_config->fdi_lanes,
12766                       pipe_config->fdi_m_n.gmch_m, pipe_config->fdi_m_n.gmch_n,
12767                       pipe_config->fdi_m_n.link_m, pipe_config->fdi_m_n.link_n,
12768                       pipe_config->fdi_m_n.tu);
12769         DRM_DEBUG_KMS("dp: %i, lanes: %i, gmch_m: %u, gmch_n: %u, link_m: %u, link_n: %u, tu: %u\n",
12770                       intel_crtc_has_dp_encoder(pipe_config),
12771                       pipe_config->lane_count,
12772                       pipe_config->dp_m_n.gmch_m, pipe_config->dp_m_n.gmch_n,
12773                       pipe_config->dp_m_n.link_m, pipe_config->dp_m_n.link_n,
12774                       pipe_config->dp_m_n.tu);
12775
12776         DRM_DEBUG_KMS("dp: %i, lanes: %i, gmch_m2: %u, gmch_n2: %u, link_m2: %u, link_n2: %u, tu2: %u\n",
12777                       intel_crtc_has_dp_encoder(pipe_config),
12778                       pipe_config->lane_count,
12779                       pipe_config->dp_m2_n2.gmch_m,
12780                       pipe_config->dp_m2_n2.gmch_n,
12781                       pipe_config->dp_m2_n2.link_m,
12782                       pipe_config->dp_m2_n2.link_n,
12783                       pipe_config->dp_m2_n2.tu);
12784
12785         DRM_DEBUG_KMS("audio: %i, infoframes: %i\n",
12786                       pipe_config->has_audio,
12787                       pipe_config->has_infoframe);
12788
12789         DRM_DEBUG_KMS("requested mode:\n");
12790         drm_mode_debug_printmodeline(&pipe_config->base.mode);
12791         DRM_DEBUG_KMS("adjusted mode:\n");
12792         drm_mode_debug_printmodeline(&pipe_config->base.adjusted_mode);
12793         intel_dump_crtc_timings(&pipe_config->base.adjusted_mode);
12794         DRM_DEBUG_KMS("port clock: %d\n", pipe_config->port_clock);
12795         DRM_DEBUG_KMS("pipe src size: %dx%d\n",
12796                       pipe_config->pipe_src_w, pipe_config->pipe_src_h);
12797         DRM_DEBUG_KMS("num_scalers: %d, scaler_users: 0x%x, scaler_id: %d\n",
12798                       crtc->num_scalers,
12799                       pipe_config->scaler_state.scaler_users,
12800                       pipe_config->scaler_state.scaler_id);
12801         DRM_DEBUG_KMS("gmch pfit: control: 0x%08x, ratios: 0x%08x, lvds border: 0x%08x\n",
12802                       pipe_config->gmch_pfit.control,
12803                       pipe_config->gmch_pfit.pgm_ratios,
12804                       pipe_config->gmch_pfit.lvds_border_bits);
12805         DRM_DEBUG_KMS("pch pfit: pos: 0x%08x, size: 0x%08x, %s\n",
12806                       pipe_config->pch_pfit.pos,
12807                       pipe_config->pch_pfit.size,
12808                       pipe_config->pch_pfit.enabled ? "enabled" : "disabled");
12809         DRM_DEBUG_KMS("ips: %i\n", pipe_config->ips_enabled);
12810         DRM_DEBUG_KMS("double wide: %i\n", pipe_config->double_wide);
12811
12812         if (IS_BROXTON(dev)) {
12813                 DRM_DEBUG_KMS("dpll_hw_state: ebb0: 0x%x, ebb4: 0x%x,"
12814                               "pll0: 0x%x, pll1: 0x%x, pll2: 0x%x, pll3: 0x%x, "
12815                               "pll6: 0x%x, pll8: 0x%x, pll9: 0x%x, pll10: 0x%x, pcsdw12: 0x%x\n",
12816                               pipe_config->dpll_hw_state.ebb0,
12817                               pipe_config->dpll_hw_state.ebb4,
12818                               pipe_config->dpll_hw_state.pll0,
12819                               pipe_config->dpll_hw_state.pll1,
12820                               pipe_config->dpll_hw_state.pll2,
12821                               pipe_config->dpll_hw_state.pll3,
12822                               pipe_config->dpll_hw_state.pll6,
12823                               pipe_config->dpll_hw_state.pll8,
12824                               pipe_config->dpll_hw_state.pll9,
12825                               pipe_config->dpll_hw_state.pll10,
12826                               pipe_config->dpll_hw_state.pcsdw12);
12827         } else if (IS_SKYLAKE(dev) || IS_KABYLAKE(dev)) {
12828                 DRM_DEBUG_KMS("dpll_hw_state: "
12829                               "ctrl1: 0x%x, cfgcr1: 0x%x, cfgcr2: 0x%x\n",
12830                               pipe_config->dpll_hw_state.ctrl1,
12831                               pipe_config->dpll_hw_state.cfgcr1,
12832                               pipe_config->dpll_hw_state.cfgcr2);
12833         } else if (HAS_DDI(dev_priv)) {
12834                 DRM_DEBUG_KMS("dpll_hw_state: wrpll: 0x%x spll: 0x%x\n",
12835                               pipe_config->dpll_hw_state.wrpll,
12836                               pipe_config->dpll_hw_state.spll);
12837         } else {
12838                 DRM_DEBUG_KMS("dpll_hw_state: dpll: 0x%x, dpll_md: 0x%x, "
12839                               "fp0: 0x%x, fp1: 0x%x\n",
12840                               pipe_config->dpll_hw_state.dpll,
12841                               pipe_config->dpll_hw_state.dpll_md,
12842                               pipe_config->dpll_hw_state.fp0,
12843                               pipe_config->dpll_hw_state.fp1);
12844         }
12845
12846         DRM_DEBUG_KMS("planes on this crtc\n");
12847         list_for_each_entry(plane, &dev->mode_config.plane_list, head) {
12848                 char *format_name;
12849                 intel_plane = to_intel_plane(plane);
12850                 if (intel_plane->pipe != crtc->pipe)
12851                         continue;
12852
12853                 state = to_intel_plane_state(plane->state);
12854                 fb = state->base.fb;
12855                 if (!fb) {
12856                         DRM_DEBUG_KMS("[PLANE:%d:%s] disabled, scaler_id = %d\n",
12857                                       plane->base.id, plane->name, state->scaler_id);
12858                         continue;
12859                 }
12860
12861                 format_name = drm_get_format_name(fb->pixel_format);
12862
12863                 DRM_DEBUG_KMS("[PLANE:%d:%s] enabled",
12864                               plane->base.id, plane->name);
12865                 DRM_DEBUG_KMS("\tFB:%d, fb = %ux%u format = %s",
12866                               fb->base.id, fb->width, fb->height, format_name);
12867                 DRM_DEBUG_KMS("\tscaler:%d src %dx%d+%d+%d dst %dx%d+%d+%d\n",
12868                               state->scaler_id,
12869                               state->base.src.x1 >> 16,
12870                               state->base.src.y1 >> 16,
12871                               drm_rect_width(&state->base.src) >> 16,
12872                               drm_rect_height(&state->base.src) >> 16,
12873                               state->base.dst.x1, state->base.dst.y1,
12874                               drm_rect_width(&state->base.dst),
12875                               drm_rect_height(&state->base.dst));
12876
12877                 kfree(format_name);
12878         }
12879 }
12880
12881 static bool check_digital_port_conflicts(struct drm_atomic_state *state)
12882 {
12883         struct drm_device *dev = state->dev;
12884         struct drm_connector *connector;
12885         unsigned int used_ports = 0;
12886         unsigned int used_mst_ports = 0;
12887
12888         /*
12889          * Walk the connector list instead of the encoder
12890          * list to detect the problem on ddi platforms
12891          * where there's just one encoder per digital port.
12892          */
12893         drm_for_each_connector(connector, dev) {
12894                 struct drm_connector_state *connector_state;
12895                 struct intel_encoder *encoder;
12896
12897                 connector_state = drm_atomic_get_existing_connector_state(state, connector);
12898                 if (!connector_state)
12899                         connector_state = connector->state;
12900
12901                 if (!connector_state->best_encoder)
12902                         continue;
12903
12904                 encoder = to_intel_encoder(connector_state->best_encoder);
12905
12906                 WARN_ON(!connector_state->crtc);
12907
12908                 switch (encoder->type) {
12909                         unsigned int port_mask;
12910                 case INTEL_OUTPUT_UNKNOWN:
12911                         if (WARN_ON(!HAS_DDI(to_i915(dev))))
12912                                 break;
12913                 case INTEL_OUTPUT_DP:
12914                 case INTEL_OUTPUT_HDMI:
12915                 case INTEL_OUTPUT_EDP:
12916                         port_mask = 1 << enc_to_dig_port(&encoder->base)->port;
12917
12918                         /* the same port mustn't appear more than once */
12919                         if (used_ports & port_mask)
12920                                 return false;
12921
12922                         used_ports |= port_mask;
12923                         break;
12924                 case INTEL_OUTPUT_DP_MST:
12925                         used_mst_ports |=
12926                                 1 << enc_to_mst(&encoder->base)->primary->port;
12927                         break;
12928                 default:
12929                         break;
12930                 }
12931         }
12932
12933         /* can't mix MST and SST/HDMI on the same port */
12934         if (used_ports & used_mst_ports)
12935                 return false;
12936
12937         return true;
12938 }
12939
12940 static void
12941 clear_intel_crtc_state(struct intel_crtc_state *crtc_state)
12942 {
12943         struct drm_crtc_state tmp_state;
12944         struct intel_crtc_scaler_state scaler_state;
12945         struct intel_dpll_hw_state dpll_hw_state;
12946         struct intel_shared_dpll *shared_dpll;
12947         bool force_thru;
12948
12949         /* FIXME: before the switch to atomic started, a new pipe_config was
12950          * kzalloc'd. Code that depends on any field being zero should be
12951          * fixed, so that the crtc_state can be safely duplicated. For now,
12952          * only fields that are know to not cause problems are preserved. */
12953
12954         tmp_state = crtc_state->base;
12955         scaler_state = crtc_state->scaler_state;
12956         shared_dpll = crtc_state->shared_dpll;
12957         dpll_hw_state = crtc_state->dpll_hw_state;
12958         force_thru = crtc_state->pch_pfit.force_thru;
12959
12960         memset(crtc_state, 0, sizeof *crtc_state);
12961
12962         crtc_state->base = tmp_state;
12963         crtc_state->scaler_state = scaler_state;
12964         crtc_state->shared_dpll = shared_dpll;
12965         crtc_state->dpll_hw_state = dpll_hw_state;
12966         crtc_state->pch_pfit.force_thru = force_thru;
12967 }
12968
12969 static int
12970 intel_modeset_pipe_config(struct drm_crtc *crtc,
12971                           struct intel_crtc_state *pipe_config)
12972 {
12973         struct drm_atomic_state *state = pipe_config->base.state;
12974         struct intel_encoder *encoder;
12975         struct drm_connector *connector;
12976         struct drm_connector_state *connector_state;
12977         int base_bpp, ret = -EINVAL;
12978         int i;
12979         bool retry = true;
12980
12981         clear_intel_crtc_state(pipe_config);
12982
12983         pipe_config->cpu_transcoder =
12984                 (enum transcoder) to_intel_crtc(crtc)->pipe;
12985
12986         /*
12987          * Sanitize sync polarity flags based on requested ones. If neither
12988          * positive or negative polarity is requested, treat this as meaning
12989          * negative polarity.
12990          */
12991         if (!(pipe_config->base.adjusted_mode.flags &
12992               (DRM_MODE_FLAG_PHSYNC | DRM_MODE_FLAG_NHSYNC)))
12993                 pipe_config->base.adjusted_mode.flags |= DRM_MODE_FLAG_NHSYNC;
12994
12995         if (!(pipe_config->base.adjusted_mode.flags &
12996               (DRM_MODE_FLAG_PVSYNC | DRM_MODE_FLAG_NVSYNC)))
12997                 pipe_config->base.adjusted_mode.flags |= DRM_MODE_FLAG_NVSYNC;
12998
12999         base_bpp = compute_baseline_pipe_bpp(to_intel_crtc(crtc),
13000                                              pipe_config);
13001         if (base_bpp < 0)
13002                 goto fail;
13003
13004         /*
13005          * Determine the real pipe dimensions. Note that stereo modes can
13006          * increase the actual pipe size due to the frame doubling and
13007          * insertion of additional space for blanks between the frame. This
13008          * is stored in the crtc timings. We use the requested mode to do this
13009          * computation to clearly distinguish it from the adjusted mode, which
13010          * can be changed by the connectors in the below retry loop.
13011          */
13012         drm_crtc_get_hv_timing(&pipe_config->base.mode,
13013                                &pipe_config->pipe_src_w,
13014                                &pipe_config->pipe_src_h);
13015
13016         for_each_connector_in_state(state, connector, connector_state, i) {
13017                 if (connector_state->crtc != crtc)
13018                         continue;
13019
13020                 encoder = to_intel_encoder(connector_state->best_encoder);
13021
13022                 if (!check_single_encoder_cloning(state, to_intel_crtc(crtc), encoder)) {
13023                         DRM_DEBUG_KMS("rejecting invalid cloning configuration\n");
13024                         goto fail;
13025                 }
13026
13027                 /*
13028                  * Determine output_types before calling the .compute_config()
13029                  * hooks so that the hooks can use this information safely.
13030                  */
13031                 pipe_config->output_types |= 1 << encoder->type;
13032         }
13033
13034 encoder_retry:
13035         /* Ensure the port clock defaults are reset when retrying. */
13036         pipe_config->port_clock = 0;
13037         pipe_config->pixel_multiplier = 1;
13038
13039         /* Fill in default crtc timings, allow encoders to overwrite them. */
13040         drm_mode_set_crtcinfo(&pipe_config->base.adjusted_mode,
13041                               CRTC_STEREO_DOUBLE);
13042
13043         /* Pass our mode to the connectors and the CRTC to give them a chance to
13044          * adjust it according to limitations or connector properties, and also
13045          * a chance to reject the mode entirely.
13046          */
13047         for_each_connector_in_state(state, connector, connector_state, i) {
13048                 if (connector_state->crtc != crtc)
13049                         continue;
13050
13051                 encoder = to_intel_encoder(connector_state->best_encoder);
13052
13053                 if (!(encoder->compute_config(encoder, pipe_config, connector_state))) {
13054                         DRM_DEBUG_KMS("Encoder config failure\n");
13055                         goto fail;
13056                 }
13057         }
13058
13059         /* Set default port clock if not overwritten by the encoder. Needs to be
13060          * done afterwards in case the encoder adjusts the mode. */
13061         if (!pipe_config->port_clock)
13062                 pipe_config->port_clock = pipe_config->base.adjusted_mode.crtc_clock
13063                         * pipe_config->pixel_multiplier;
13064
13065         ret = intel_crtc_compute_config(to_intel_crtc(crtc), pipe_config);
13066         if (ret < 0) {
13067                 DRM_DEBUG_KMS("CRTC fixup failed\n");
13068                 goto fail;
13069         }
13070
13071         if (ret == RETRY) {
13072                 if (WARN(!retry, "loop in pipe configuration computation\n")) {
13073                         ret = -EINVAL;
13074                         goto fail;
13075                 }
13076
13077                 DRM_DEBUG_KMS("CRTC bw constrained, retrying\n");
13078                 retry = false;
13079                 goto encoder_retry;
13080         }
13081
13082         /* Dithering seems to not pass-through bits correctly when it should, so
13083          * only enable it on 6bpc panels. */
13084         pipe_config->dither = pipe_config->pipe_bpp == 6*3;
13085         DRM_DEBUG_KMS("hw max bpp: %i, pipe bpp: %i, dithering: %i\n",
13086                       base_bpp, pipe_config->pipe_bpp, pipe_config->dither);
13087
13088 fail:
13089         return ret;
13090 }
13091
13092 static void
13093 intel_modeset_update_crtc_state(struct drm_atomic_state *state)
13094 {
13095         struct drm_crtc *crtc;
13096         struct drm_crtc_state *crtc_state;
13097         int i;
13098
13099         /* Double check state. */
13100         for_each_crtc_in_state(state, crtc, crtc_state, i) {
13101                 to_intel_crtc(crtc)->config = to_intel_crtc_state(crtc->state);
13102
13103                 /* Update hwmode for vblank functions */
13104                 if (crtc->state->active)
13105                         crtc->hwmode = crtc->state->adjusted_mode;
13106                 else
13107                         crtc->hwmode.crtc_clock = 0;
13108
13109                 /*
13110                  * Update legacy state to satisfy fbc code. This can
13111                  * be removed when fbc uses the atomic state.
13112                  */
13113                 if (drm_atomic_get_existing_plane_state(state, crtc->primary)) {
13114                         struct drm_plane_state *plane_state = crtc->primary->state;
13115
13116                         crtc->primary->fb = plane_state->fb;
13117                         crtc->x = plane_state->src_x >> 16;
13118                         crtc->y = plane_state->src_y >> 16;
13119                 }
13120         }
13121 }
13122
13123 static bool intel_fuzzy_clock_check(int clock1, int clock2)
13124 {
13125         int diff;
13126
13127         if (clock1 == clock2)
13128                 return true;
13129
13130         if (!clock1 || !clock2)
13131                 return false;
13132
13133         diff = abs(clock1 - clock2);
13134
13135         if (((((diff + clock1 + clock2) * 100)) / (clock1 + clock2)) < 105)
13136                 return true;
13137
13138         return false;
13139 }
13140
13141 static bool
13142 intel_compare_m_n(unsigned int m, unsigned int n,
13143                   unsigned int m2, unsigned int n2,
13144                   bool exact)
13145 {
13146         if (m == m2 && n == n2)
13147                 return true;
13148
13149         if (exact || !m || !n || !m2 || !n2)
13150                 return false;
13151
13152         BUILD_BUG_ON(DATA_LINK_M_N_MASK > INT_MAX);
13153
13154         if (n > n2) {
13155                 while (n > n2) {
13156                         m2 <<= 1;
13157                         n2 <<= 1;
13158                 }
13159         } else if (n < n2) {
13160                 while (n < n2) {
13161                         m <<= 1;
13162                         n <<= 1;
13163                 }
13164         }
13165
13166         if (n != n2)
13167                 return false;
13168
13169         return intel_fuzzy_clock_check(m, m2);
13170 }
13171
13172 static bool
13173 intel_compare_link_m_n(const struct intel_link_m_n *m_n,
13174                        struct intel_link_m_n *m2_n2,
13175                        bool adjust)
13176 {
13177         if (m_n->tu == m2_n2->tu &&
13178             intel_compare_m_n(m_n->gmch_m, m_n->gmch_n,
13179                               m2_n2->gmch_m, m2_n2->gmch_n, !adjust) &&
13180             intel_compare_m_n(m_n->link_m, m_n->link_n,
13181                               m2_n2->link_m, m2_n2->link_n, !adjust)) {
13182                 if (adjust)
13183                         *m2_n2 = *m_n;
13184
13185                 return true;
13186         }
13187
13188         return false;
13189 }
13190
13191 static bool
13192 intel_pipe_config_compare(struct drm_device *dev,
13193                           struct intel_crtc_state *current_config,
13194                           struct intel_crtc_state *pipe_config,
13195                           bool adjust)
13196 {
13197         bool ret = true;
13198
13199 #define INTEL_ERR_OR_DBG_KMS(fmt, ...) \
13200         do { \
13201                 if (!adjust) \
13202                         DRM_ERROR(fmt, ##__VA_ARGS__); \
13203                 else \
13204                         DRM_DEBUG_KMS(fmt, ##__VA_ARGS__); \
13205         } while (0)
13206
13207 #define PIPE_CONF_CHECK_X(name) \
13208         if (current_config->name != pipe_config->name) { \
13209                 INTEL_ERR_OR_DBG_KMS("mismatch in " #name " " \
13210                           "(expected 0x%08x, found 0x%08x)\n", \
13211                           current_config->name, \
13212                           pipe_config->name); \
13213                 ret = false; \
13214         }
13215
13216 #define PIPE_CONF_CHECK_I(name) \
13217         if (current_config->name != pipe_config->name) { \
13218                 INTEL_ERR_OR_DBG_KMS("mismatch in " #name " " \
13219                           "(expected %i, found %i)\n", \
13220                           current_config->name, \
13221                           pipe_config->name); \
13222                 ret = false; \
13223         }
13224
13225 #define PIPE_CONF_CHECK_P(name) \
13226         if (current_config->name != pipe_config->name) { \
13227                 INTEL_ERR_OR_DBG_KMS("mismatch in " #name " " \
13228                           "(expected %p, found %p)\n", \
13229                           current_config->name, \
13230                           pipe_config->name); \
13231                 ret = false; \
13232         }
13233
13234 #define PIPE_CONF_CHECK_M_N(name) \
13235         if (!intel_compare_link_m_n(&current_config->name, \
13236                                     &pipe_config->name,\
13237                                     adjust)) { \
13238                 INTEL_ERR_OR_DBG_KMS("mismatch in " #name " " \
13239                           "(expected tu %i gmch %i/%i link %i/%i, " \
13240                           "found tu %i, gmch %i/%i link %i/%i)\n", \
13241                           current_config->name.tu, \
13242                           current_config->name.gmch_m, \
13243                           current_config->name.gmch_n, \
13244                           current_config->name.link_m, \
13245                           current_config->name.link_n, \
13246                           pipe_config->name.tu, \
13247                           pipe_config->name.gmch_m, \
13248                           pipe_config->name.gmch_n, \
13249                           pipe_config->name.link_m, \
13250                           pipe_config->name.link_n); \
13251                 ret = false; \
13252         }
13253
13254 /* This is required for BDW+ where there is only one set of registers for
13255  * switching between high and low RR.
13256  * This macro can be used whenever a comparison has to be made between one
13257  * hw state and multiple sw state variables.
13258  */
13259 #define PIPE_CONF_CHECK_M_N_ALT(name, alt_name) \
13260         if (!intel_compare_link_m_n(&current_config->name, \
13261                                     &pipe_config->name, adjust) && \
13262             !intel_compare_link_m_n(&current_config->alt_name, \
13263                                     &pipe_config->name, adjust)) { \
13264                 INTEL_ERR_OR_DBG_KMS("mismatch in " #name " " \
13265                           "(expected tu %i gmch %i/%i link %i/%i, " \
13266                           "or tu %i gmch %i/%i link %i/%i, " \
13267                           "found tu %i, gmch %i/%i link %i/%i)\n", \
13268                           current_config->name.tu, \
13269                           current_config->name.gmch_m, \
13270                           current_config->name.gmch_n, \
13271                           current_config->name.link_m, \
13272                           current_config->name.link_n, \
13273                           current_config->alt_name.tu, \
13274                           current_config->alt_name.gmch_m, \
13275                           current_config->alt_name.gmch_n, \
13276                           current_config->alt_name.link_m, \
13277                           current_config->alt_name.link_n, \
13278                           pipe_config->name.tu, \
13279                           pipe_config->name.gmch_m, \
13280                           pipe_config->name.gmch_n, \
13281                           pipe_config->name.link_m, \
13282                           pipe_config->name.link_n); \
13283                 ret = false; \
13284         }
13285
13286 #define PIPE_CONF_CHECK_FLAGS(name, mask)       \
13287         if ((current_config->name ^ pipe_config->name) & (mask)) { \
13288                 INTEL_ERR_OR_DBG_KMS("mismatch in " #name "(" #mask ") " \
13289                           "(expected %i, found %i)\n", \
13290                           current_config->name & (mask), \
13291                           pipe_config->name & (mask)); \
13292                 ret = false; \
13293         }
13294
13295 #define PIPE_CONF_CHECK_CLOCK_FUZZY(name) \
13296         if (!intel_fuzzy_clock_check(current_config->name, pipe_config->name)) { \
13297                 INTEL_ERR_OR_DBG_KMS("mismatch in " #name " " \
13298                           "(expected %i, found %i)\n", \
13299                           current_config->name, \
13300                           pipe_config->name); \
13301                 ret = false; \
13302         }
13303
13304 #define PIPE_CONF_QUIRK(quirk)  \
13305         ((current_config->quirks | pipe_config->quirks) & (quirk))
13306
13307         PIPE_CONF_CHECK_I(cpu_transcoder);
13308
13309         PIPE_CONF_CHECK_I(has_pch_encoder);
13310         PIPE_CONF_CHECK_I(fdi_lanes);
13311         PIPE_CONF_CHECK_M_N(fdi_m_n);
13312
13313         PIPE_CONF_CHECK_I(lane_count);
13314         PIPE_CONF_CHECK_X(lane_lat_optim_mask);
13315
13316         if (INTEL_INFO(dev)->gen < 8) {
13317                 PIPE_CONF_CHECK_M_N(dp_m_n);
13318
13319                 if (current_config->has_drrs)
13320                         PIPE_CONF_CHECK_M_N(dp_m2_n2);
13321         } else
13322                 PIPE_CONF_CHECK_M_N_ALT(dp_m_n, dp_m2_n2);
13323
13324         PIPE_CONF_CHECK_X(output_types);
13325
13326         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hdisplay);
13327         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_htotal);
13328         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hblank_start);
13329         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hblank_end);
13330         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hsync_start);
13331         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hsync_end);
13332
13333         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vdisplay);
13334         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vtotal);
13335         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vblank_start);
13336         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vblank_end);
13337         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vsync_start);
13338         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vsync_end);
13339
13340         PIPE_CONF_CHECK_I(pixel_multiplier);
13341         PIPE_CONF_CHECK_I(has_hdmi_sink);
13342         if ((INTEL_INFO(dev)->gen < 8 && !IS_HASWELL(dev)) ||
13343             IS_VALLEYVIEW(dev) || IS_CHERRYVIEW(dev))
13344                 PIPE_CONF_CHECK_I(limited_color_range);
13345         PIPE_CONF_CHECK_I(has_infoframe);
13346
13347         PIPE_CONF_CHECK_I(has_audio);
13348
13349         PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
13350                               DRM_MODE_FLAG_INTERLACE);
13351
13352         if (!PIPE_CONF_QUIRK(PIPE_CONFIG_QUIRK_MODE_SYNC_FLAGS)) {
13353                 PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
13354                                       DRM_MODE_FLAG_PHSYNC);
13355                 PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
13356                                       DRM_MODE_FLAG_NHSYNC);
13357                 PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
13358                                       DRM_MODE_FLAG_PVSYNC);
13359                 PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
13360                                       DRM_MODE_FLAG_NVSYNC);
13361         }
13362
13363         PIPE_CONF_CHECK_X(gmch_pfit.control);
13364         /* pfit ratios are autocomputed by the hw on gen4+ */
13365         if (INTEL_INFO(dev)->gen < 4)
13366                 PIPE_CONF_CHECK_X(gmch_pfit.pgm_ratios);
13367         PIPE_CONF_CHECK_X(gmch_pfit.lvds_border_bits);
13368
13369         if (!adjust) {
13370                 PIPE_CONF_CHECK_I(pipe_src_w);
13371                 PIPE_CONF_CHECK_I(pipe_src_h);
13372
13373                 PIPE_CONF_CHECK_I(pch_pfit.enabled);
13374                 if (current_config->pch_pfit.enabled) {
13375                         PIPE_CONF_CHECK_X(pch_pfit.pos);
13376                         PIPE_CONF_CHECK_X(pch_pfit.size);
13377                 }
13378
13379                 PIPE_CONF_CHECK_I(scaler_state.scaler_id);
13380         }
13381
13382         /* BDW+ don't expose a synchronous way to read the state */
13383         if (IS_HASWELL(dev))
13384                 PIPE_CONF_CHECK_I(ips_enabled);
13385
13386         PIPE_CONF_CHECK_I(double_wide);
13387
13388         PIPE_CONF_CHECK_P(shared_dpll);
13389         PIPE_CONF_CHECK_X(dpll_hw_state.dpll);
13390         PIPE_CONF_CHECK_X(dpll_hw_state.dpll_md);
13391         PIPE_CONF_CHECK_X(dpll_hw_state.fp0);
13392         PIPE_CONF_CHECK_X(dpll_hw_state.fp1);
13393         PIPE_CONF_CHECK_X(dpll_hw_state.wrpll);
13394         PIPE_CONF_CHECK_X(dpll_hw_state.spll);
13395         PIPE_CONF_CHECK_X(dpll_hw_state.ctrl1);
13396         PIPE_CONF_CHECK_X(dpll_hw_state.cfgcr1);
13397         PIPE_CONF_CHECK_X(dpll_hw_state.cfgcr2);
13398
13399         PIPE_CONF_CHECK_X(dsi_pll.ctrl);
13400         PIPE_CONF_CHECK_X(dsi_pll.div);
13401
13402         if (IS_G4X(dev) || INTEL_INFO(dev)->gen >= 5)
13403                 PIPE_CONF_CHECK_I(pipe_bpp);
13404
13405         PIPE_CONF_CHECK_CLOCK_FUZZY(base.adjusted_mode.crtc_clock);
13406         PIPE_CONF_CHECK_CLOCK_FUZZY(port_clock);
13407
13408 #undef PIPE_CONF_CHECK_X
13409 #undef PIPE_CONF_CHECK_I
13410 #undef PIPE_CONF_CHECK_P
13411 #undef PIPE_CONF_CHECK_FLAGS
13412 #undef PIPE_CONF_CHECK_CLOCK_FUZZY
13413 #undef PIPE_CONF_QUIRK
13414 #undef INTEL_ERR_OR_DBG_KMS
13415
13416         return ret;
13417 }
13418
13419 static void intel_pipe_config_sanity_check(struct drm_i915_private *dev_priv,
13420                                            const struct intel_crtc_state *pipe_config)
13421 {
13422         if (pipe_config->has_pch_encoder) {
13423                 int fdi_dotclock = intel_dotclock_calculate(intel_fdi_link_freq(dev_priv, pipe_config),
13424                                                             &pipe_config->fdi_m_n);
13425                 int dotclock = pipe_config->base.adjusted_mode.crtc_clock;
13426
13427                 /*
13428                  * FDI already provided one idea for the dotclock.
13429                  * Yell if the encoder disagrees.
13430                  */
13431                 WARN(!intel_fuzzy_clock_check(fdi_dotclock, dotclock),
13432                      "FDI dotclock and encoder dotclock mismatch, fdi: %i, encoder: %i\n",
13433                      fdi_dotclock, dotclock);
13434         }
13435 }
13436
13437 static void verify_wm_state(struct drm_crtc *crtc,
13438                             struct drm_crtc_state *new_state)
13439 {
13440         struct drm_device *dev = crtc->dev;
13441         struct drm_i915_private *dev_priv = to_i915(dev);
13442         struct skl_ddb_allocation hw_ddb, *sw_ddb;
13443         struct skl_ddb_entry *hw_entry, *sw_entry;
13444         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
13445         const enum pipe pipe = intel_crtc->pipe;
13446         int plane;
13447
13448         if (INTEL_INFO(dev)->gen < 9 || !new_state->active)
13449                 return;
13450
13451         skl_ddb_get_hw_state(dev_priv, &hw_ddb);
13452         sw_ddb = &dev_priv->wm.skl_hw.ddb;
13453
13454         /* planes */
13455         for_each_plane(dev_priv, pipe, plane) {
13456                 hw_entry = &hw_ddb.plane[pipe][plane];
13457                 sw_entry = &sw_ddb->plane[pipe][plane];
13458
13459                 if (skl_ddb_entry_equal(hw_entry, sw_entry))
13460                         continue;
13461
13462                 DRM_ERROR("mismatch in DDB state pipe %c plane %d "
13463                           "(expected (%u,%u), found (%u,%u))\n",
13464                           pipe_name(pipe), plane + 1,
13465                           sw_entry->start, sw_entry->end,
13466                           hw_entry->start, hw_entry->end);
13467         }
13468
13469         /*
13470          * cursor
13471          * If the cursor plane isn't active, we may not have updated it's ddb
13472          * allocation. In that case since the ddb allocation will be updated
13473          * once the plane becomes visible, we can skip this check
13474          */
13475         if (intel_crtc->cursor_addr) {
13476                 hw_entry = &hw_ddb.plane[pipe][PLANE_CURSOR];
13477                 sw_entry = &sw_ddb->plane[pipe][PLANE_CURSOR];
13478
13479                 if (!skl_ddb_entry_equal(hw_entry, sw_entry)) {
13480                         DRM_ERROR("mismatch in DDB state pipe %c cursor "
13481                                   "(expected (%u,%u), found (%u,%u))\n",
13482                                   pipe_name(pipe),
13483                                   sw_entry->start, sw_entry->end,
13484                                   hw_entry->start, hw_entry->end);
13485                 }
13486         }
13487 }
13488
13489 static void
13490 verify_connector_state(struct drm_device *dev, struct drm_crtc *crtc)
13491 {
13492         struct drm_connector *connector;
13493
13494         drm_for_each_connector(connector, dev) {
13495                 struct drm_encoder *encoder = connector->encoder;
13496                 struct drm_connector_state *state = connector->state;
13497
13498                 if (state->crtc != crtc)
13499                         continue;
13500
13501                 intel_connector_verify_state(to_intel_connector(connector));
13502
13503                 I915_STATE_WARN(state->best_encoder != encoder,
13504                      "connector's atomic encoder doesn't match legacy encoder\n");
13505         }
13506 }
13507
13508 static void
13509 verify_encoder_state(struct drm_device *dev)
13510 {
13511         struct intel_encoder *encoder;
13512         struct intel_connector *connector;
13513
13514         for_each_intel_encoder(dev, encoder) {
13515                 bool enabled = false;
13516                 enum pipe pipe;
13517
13518                 DRM_DEBUG_KMS("[ENCODER:%d:%s]\n",
13519                               encoder->base.base.id,
13520                               encoder->base.name);
13521
13522                 for_each_intel_connector(dev, connector) {
13523                         if (connector->base.state->best_encoder != &encoder->base)
13524                                 continue;
13525                         enabled = true;
13526
13527                         I915_STATE_WARN(connector->base.state->crtc !=
13528                                         encoder->base.crtc,
13529                              "connector's crtc doesn't match encoder crtc\n");
13530                 }
13531
13532                 I915_STATE_WARN(!!encoder->base.crtc != enabled,
13533                      "encoder's enabled state mismatch "
13534                      "(expected %i, found %i)\n",
13535                      !!encoder->base.crtc, enabled);
13536
13537                 if (!encoder->base.crtc) {
13538                         bool active;
13539
13540                         active = encoder->get_hw_state(encoder, &pipe);
13541                         I915_STATE_WARN(active,
13542                              "encoder detached but still enabled on pipe %c.\n",
13543                              pipe_name(pipe));
13544                 }
13545         }
13546 }
13547
13548 static void
13549 verify_crtc_state(struct drm_crtc *crtc,
13550                   struct drm_crtc_state *old_crtc_state,
13551                   struct drm_crtc_state *new_crtc_state)
13552 {
13553         struct drm_device *dev = crtc->dev;
13554         struct drm_i915_private *dev_priv = to_i915(dev);
13555         struct intel_encoder *encoder;
13556         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
13557         struct intel_crtc_state *pipe_config, *sw_config;
13558         struct drm_atomic_state *old_state;
13559         bool active;
13560
13561         old_state = old_crtc_state->state;
13562         __drm_atomic_helper_crtc_destroy_state(old_crtc_state);
13563         pipe_config = to_intel_crtc_state(old_crtc_state);
13564         memset(pipe_config, 0, sizeof(*pipe_config));
13565         pipe_config->base.crtc = crtc;
13566         pipe_config->base.state = old_state;
13567
13568         DRM_DEBUG_KMS("[CRTC:%d:%s]\n", crtc->base.id, crtc->name);
13569
13570         active = dev_priv->display.get_pipe_config(intel_crtc, pipe_config);
13571
13572         /* hw state is inconsistent with the pipe quirk */
13573         if ((intel_crtc->pipe == PIPE_A && dev_priv->quirks & QUIRK_PIPEA_FORCE) ||
13574             (intel_crtc->pipe == PIPE_B && dev_priv->quirks & QUIRK_PIPEB_FORCE))
13575                 active = new_crtc_state->active;
13576
13577         I915_STATE_WARN(new_crtc_state->active != active,
13578              "crtc active state doesn't match with hw state "
13579              "(expected %i, found %i)\n", new_crtc_state->active, active);
13580
13581         I915_STATE_WARN(intel_crtc->active != new_crtc_state->active,
13582              "transitional active state does not match atomic hw state "
13583              "(expected %i, found %i)\n", new_crtc_state->active, intel_crtc->active);
13584
13585         for_each_encoder_on_crtc(dev, crtc, encoder) {
13586                 enum pipe pipe;
13587
13588                 active = encoder->get_hw_state(encoder, &pipe);
13589                 I915_STATE_WARN(active != new_crtc_state->active,
13590                         "[ENCODER:%i] active %i with crtc active %i\n",
13591                         encoder->base.base.id, active, new_crtc_state->active);
13592
13593                 I915_STATE_WARN(active && intel_crtc->pipe != pipe,
13594                                 "Encoder connected to wrong pipe %c\n",
13595                                 pipe_name(pipe));
13596
13597                 if (active) {
13598                         pipe_config->output_types |= 1 << encoder->type;
13599                         encoder->get_config(encoder, pipe_config);
13600                 }
13601         }
13602
13603         if (!new_crtc_state->active)
13604                 return;
13605
13606         intel_pipe_config_sanity_check(dev_priv, pipe_config);
13607
13608         sw_config = to_intel_crtc_state(crtc->state);
13609         if (!intel_pipe_config_compare(dev, sw_config,
13610                                        pipe_config, false)) {
13611                 I915_STATE_WARN(1, "pipe state doesn't match!\n");
13612                 intel_dump_pipe_config(intel_crtc, pipe_config,
13613                                        "[hw state]");
13614                 intel_dump_pipe_config(intel_crtc, sw_config,
13615                                        "[sw state]");
13616         }
13617 }
13618
13619 static void
13620 verify_single_dpll_state(struct drm_i915_private *dev_priv,
13621                          struct intel_shared_dpll *pll,
13622                          struct drm_crtc *crtc,
13623                          struct drm_crtc_state *new_state)
13624 {
13625         struct intel_dpll_hw_state dpll_hw_state;
13626         unsigned crtc_mask;
13627         bool active;
13628
13629         memset(&dpll_hw_state, 0, sizeof(dpll_hw_state));
13630
13631         DRM_DEBUG_KMS("%s\n", pll->name);
13632
13633         active = pll->funcs.get_hw_state(dev_priv, pll, &dpll_hw_state);
13634
13635         if (!(pll->flags & INTEL_DPLL_ALWAYS_ON)) {
13636                 I915_STATE_WARN(!pll->on && pll->active_mask,
13637                      "pll in active use but not on in sw tracking\n");
13638                 I915_STATE_WARN(pll->on && !pll->active_mask,
13639                      "pll is on but not used by any active crtc\n");
13640                 I915_STATE_WARN(pll->on != active,
13641                      "pll on state mismatch (expected %i, found %i)\n",
13642                      pll->on, active);
13643         }
13644
13645         if (!crtc) {
13646                 I915_STATE_WARN(pll->active_mask & ~pll->config.crtc_mask,
13647                                 "more active pll users than references: %x vs %x\n",
13648                                 pll->active_mask, pll->config.crtc_mask);
13649
13650                 return;
13651         }
13652
13653         crtc_mask = 1 << drm_crtc_index(crtc);
13654
13655         if (new_state->active)
13656                 I915_STATE_WARN(!(pll->active_mask & crtc_mask),
13657                                 "pll active mismatch (expected pipe %c in active mask 0x%02x)\n",
13658                                 pipe_name(drm_crtc_index(crtc)), pll->active_mask);
13659         else
13660                 I915_STATE_WARN(pll->active_mask & crtc_mask,
13661                                 "pll active mismatch (didn't expect pipe %c in active mask 0x%02x)\n",
13662                                 pipe_name(drm_crtc_index(crtc)), pll->active_mask);
13663
13664         I915_STATE_WARN(!(pll->config.crtc_mask & crtc_mask),
13665                         "pll enabled crtcs mismatch (expected 0x%x in 0x%02x)\n",
13666                         crtc_mask, pll->config.crtc_mask);
13667
13668         I915_STATE_WARN(pll->on && memcmp(&pll->config.hw_state,
13669                                           &dpll_hw_state,
13670                                           sizeof(dpll_hw_state)),
13671                         "pll hw state mismatch\n");
13672 }
13673
13674 static void
13675 verify_shared_dpll_state(struct drm_device *dev, struct drm_crtc *crtc,
13676                          struct drm_crtc_state *old_crtc_state,
13677                          struct drm_crtc_state *new_crtc_state)
13678 {
13679         struct drm_i915_private *dev_priv = to_i915(dev);
13680         struct intel_crtc_state *old_state = to_intel_crtc_state(old_crtc_state);
13681         struct intel_crtc_state *new_state = to_intel_crtc_state(new_crtc_state);
13682
13683         if (new_state->shared_dpll)
13684                 verify_single_dpll_state(dev_priv, new_state->shared_dpll, crtc, new_crtc_state);
13685
13686         if (old_state->shared_dpll &&
13687             old_state->shared_dpll != new_state->shared_dpll) {
13688                 unsigned crtc_mask = 1 << drm_crtc_index(crtc);
13689                 struct intel_shared_dpll *pll = old_state->shared_dpll;
13690
13691                 I915_STATE_WARN(pll->active_mask & crtc_mask,
13692                                 "pll active mismatch (didn't expect pipe %c in active mask)\n",
13693                                 pipe_name(drm_crtc_index(crtc)));
13694                 I915_STATE_WARN(pll->config.crtc_mask & crtc_mask,
13695                                 "pll enabled crtcs mismatch (found %x in enabled mask)\n",
13696                                 pipe_name(drm_crtc_index(crtc)));
13697         }
13698 }
13699
13700 static void
13701 intel_modeset_verify_crtc(struct drm_crtc *crtc,
13702                          struct drm_crtc_state *old_state,
13703                          struct drm_crtc_state *new_state)
13704 {
13705         if (!needs_modeset(new_state) &&
13706             !to_intel_crtc_state(new_state)->update_pipe)
13707                 return;
13708
13709         verify_wm_state(crtc, new_state);
13710         verify_connector_state(crtc->dev, crtc);
13711         verify_crtc_state(crtc, old_state, new_state);
13712         verify_shared_dpll_state(crtc->dev, crtc, old_state, new_state);
13713 }
13714
13715 static void
13716 verify_disabled_dpll_state(struct drm_device *dev)
13717 {
13718         struct drm_i915_private *dev_priv = to_i915(dev);
13719         int i;
13720
13721         for (i = 0; i < dev_priv->num_shared_dpll; i++)
13722                 verify_single_dpll_state(dev_priv, &dev_priv->shared_dplls[i], NULL, NULL);
13723 }
13724
13725 static void
13726 intel_modeset_verify_disabled(struct drm_device *dev)
13727 {
13728         verify_encoder_state(dev);
13729         verify_connector_state(dev, NULL);
13730         verify_disabled_dpll_state(dev);
13731 }
13732
13733 static void update_scanline_offset(struct intel_crtc *crtc)
13734 {
13735         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
13736
13737         /*
13738          * The scanline counter increments at the leading edge of hsync.
13739          *
13740          * On most platforms it starts counting from vtotal-1 on the
13741          * first active line. That means the scanline counter value is
13742          * always one less than what we would expect. Ie. just after
13743          * start of vblank, which also occurs at start of hsync (on the
13744          * last active line), the scanline counter will read vblank_start-1.
13745          *
13746          * On gen2 the scanline counter starts counting from 1 instead
13747          * of vtotal-1, so we have to subtract one (or rather add vtotal-1
13748          * to keep the value positive), instead of adding one.
13749          *
13750          * On HSW+ the behaviour of the scanline counter depends on the output
13751          * type. For DP ports it behaves like most other platforms, but on HDMI
13752          * there's an extra 1 line difference. So we need to add two instead of
13753          * one to the value.
13754          */
13755         if (IS_GEN2(dev_priv)) {
13756                 const struct drm_display_mode *adjusted_mode = &crtc->config->base.adjusted_mode;
13757                 int vtotal;
13758
13759                 vtotal = adjusted_mode->crtc_vtotal;
13760                 if (adjusted_mode->flags & DRM_MODE_FLAG_INTERLACE)
13761                         vtotal /= 2;
13762
13763                 crtc->scanline_offset = vtotal - 1;
13764         } else if (HAS_DDI(dev_priv) &&
13765                    intel_crtc_has_type(crtc->config, INTEL_OUTPUT_HDMI)) {
13766                 crtc->scanline_offset = 2;
13767         } else
13768                 crtc->scanline_offset = 1;
13769 }
13770
13771 static void intel_modeset_clear_plls(struct drm_atomic_state *state)
13772 {
13773         struct drm_device *dev = state->dev;
13774         struct drm_i915_private *dev_priv = to_i915(dev);
13775         struct intel_shared_dpll_config *shared_dpll = NULL;
13776         struct drm_crtc *crtc;
13777         struct drm_crtc_state *crtc_state;
13778         int i;
13779
13780         if (!dev_priv->display.crtc_compute_clock)
13781                 return;
13782
13783         for_each_crtc_in_state(state, crtc, crtc_state, i) {
13784                 struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
13785                 struct intel_shared_dpll *old_dpll =
13786                         to_intel_crtc_state(crtc->state)->shared_dpll;
13787
13788                 if (!needs_modeset(crtc_state))
13789                         continue;
13790
13791                 to_intel_crtc_state(crtc_state)->shared_dpll = NULL;
13792
13793                 if (!old_dpll)
13794                         continue;
13795
13796                 if (!shared_dpll)
13797                         shared_dpll = intel_atomic_get_shared_dpll_state(state);
13798
13799                 intel_shared_dpll_config_put(shared_dpll, old_dpll, intel_crtc);
13800         }
13801 }
13802
13803 /*
13804  * This implements the workaround described in the "notes" section of the mode
13805  * set sequence documentation. When going from no pipes or single pipe to
13806  * multiple pipes, and planes are enabled after the pipe, we need to wait at
13807  * least 2 vblanks on the first pipe before enabling planes on the second pipe.
13808  */
13809 static int haswell_mode_set_planes_workaround(struct drm_atomic_state *state)
13810 {
13811         struct drm_crtc_state *crtc_state;
13812         struct intel_crtc *intel_crtc;
13813         struct drm_crtc *crtc;
13814         struct intel_crtc_state *first_crtc_state = NULL;
13815         struct intel_crtc_state *other_crtc_state = NULL;
13816         enum pipe first_pipe = INVALID_PIPE, enabled_pipe = INVALID_PIPE;
13817         int i;
13818
13819         /* look at all crtc's that are going to be enabled in during modeset */
13820         for_each_crtc_in_state(state, crtc, crtc_state, i) {
13821                 intel_crtc = to_intel_crtc(crtc);
13822
13823                 if (!crtc_state->active || !needs_modeset(crtc_state))
13824                         continue;
13825
13826                 if (first_crtc_state) {
13827                         other_crtc_state = to_intel_crtc_state(crtc_state);
13828                         break;
13829                 } else {
13830                         first_crtc_state = to_intel_crtc_state(crtc_state);
13831                         first_pipe = intel_crtc->pipe;
13832                 }
13833         }
13834
13835         /* No workaround needed? */
13836         if (!first_crtc_state)
13837                 return 0;
13838
13839         /* w/a possibly needed, check how many crtc's are already enabled. */
13840         for_each_intel_crtc(state->dev, intel_crtc) {
13841                 struct intel_crtc_state *pipe_config;
13842
13843                 pipe_config = intel_atomic_get_crtc_state(state, intel_crtc);
13844                 if (IS_ERR(pipe_config))
13845                         return PTR_ERR(pipe_config);
13846
13847                 pipe_config->hsw_workaround_pipe = INVALID_PIPE;
13848
13849                 if (!pipe_config->base.active ||
13850                     needs_modeset(&pipe_config->base))
13851                         continue;
13852
13853                 /* 2 or more enabled crtcs means no need for w/a */
13854                 if (enabled_pipe != INVALID_PIPE)
13855                         return 0;
13856
13857                 enabled_pipe = intel_crtc->pipe;
13858         }
13859
13860         if (enabled_pipe != INVALID_PIPE)
13861                 first_crtc_state->hsw_workaround_pipe = enabled_pipe;
13862         else if (other_crtc_state)
13863                 other_crtc_state->hsw_workaround_pipe = first_pipe;
13864
13865         return 0;
13866 }
13867
13868 static int intel_modeset_all_pipes(struct drm_atomic_state *state)
13869 {
13870         struct drm_crtc *crtc;
13871         struct drm_crtc_state *crtc_state;
13872         int ret = 0;
13873
13874         /* add all active pipes to the state */
13875         for_each_crtc(state->dev, crtc) {
13876                 crtc_state = drm_atomic_get_crtc_state(state, crtc);
13877                 if (IS_ERR(crtc_state))
13878                         return PTR_ERR(crtc_state);
13879
13880                 if (!crtc_state->active || needs_modeset(crtc_state))
13881                         continue;
13882
13883                 crtc_state->mode_changed = true;
13884
13885                 ret = drm_atomic_add_affected_connectors(state, crtc);
13886                 if (ret)
13887                         break;
13888
13889                 ret = drm_atomic_add_affected_planes(state, crtc);
13890                 if (ret)
13891                         break;
13892         }
13893
13894         return ret;
13895 }
13896
13897 static int intel_modeset_checks(struct drm_atomic_state *state)
13898 {
13899         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
13900         struct drm_i915_private *dev_priv = to_i915(state->dev);
13901         struct drm_crtc *crtc;
13902         struct drm_crtc_state *crtc_state;
13903         int ret = 0, i;
13904
13905         if (!check_digital_port_conflicts(state)) {
13906                 DRM_DEBUG_KMS("rejecting conflicting digital port configuration\n");
13907                 return -EINVAL;
13908         }
13909
13910         intel_state->modeset = true;
13911         intel_state->active_crtcs = dev_priv->active_crtcs;
13912
13913         for_each_crtc_in_state(state, crtc, crtc_state, i) {
13914                 if (crtc_state->active)
13915                         intel_state->active_crtcs |= 1 << i;
13916                 else
13917                         intel_state->active_crtcs &= ~(1 << i);
13918
13919                 if (crtc_state->active != crtc->state->active)
13920                         intel_state->active_pipe_changes |= drm_crtc_mask(crtc);
13921         }
13922
13923         /*
13924          * See if the config requires any additional preparation, e.g.
13925          * to adjust global state with pipes off.  We need to do this
13926          * here so we can get the modeset_pipe updated config for the new
13927          * mode set on this crtc.  For other crtcs we need to use the
13928          * adjusted_mode bits in the crtc directly.
13929          */
13930         if (dev_priv->display.modeset_calc_cdclk) {
13931                 if (!intel_state->cdclk_pll_vco)
13932                         intel_state->cdclk_pll_vco = dev_priv->cdclk_pll.vco;
13933                 if (!intel_state->cdclk_pll_vco)
13934                         intel_state->cdclk_pll_vco = dev_priv->skl_preferred_vco_freq;
13935
13936                 ret = dev_priv->display.modeset_calc_cdclk(state);
13937                 if (ret < 0)
13938                         return ret;
13939
13940                 if (intel_state->dev_cdclk != dev_priv->cdclk_freq ||
13941                     intel_state->cdclk_pll_vco != dev_priv->cdclk_pll.vco)
13942                         ret = intel_modeset_all_pipes(state);
13943
13944                 if (ret < 0)
13945                         return ret;
13946
13947                 DRM_DEBUG_KMS("New cdclk calculated to be atomic %u, actual %u\n",
13948                               intel_state->cdclk, intel_state->dev_cdclk);
13949         } else
13950                 to_intel_atomic_state(state)->cdclk = dev_priv->atomic_cdclk_freq;
13951
13952         intel_modeset_clear_plls(state);
13953
13954         if (IS_HASWELL(dev_priv))
13955                 return haswell_mode_set_planes_workaround(state);
13956
13957         return 0;
13958 }
13959
13960 /*
13961  * Handle calculation of various watermark data at the end of the atomic check
13962  * phase.  The code here should be run after the per-crtc and per-plane 'check'
13963  * handlers to ensure that all derived state has been updated.
13964  */
13965 static int calc_watermark_data(struct drm_atomic_state *state)
13966 {
13967         struct drm_device *dev = state->dev;
13968         struct drm_i915_private *dev_priv = to_i915(dev);
13969
13970         /* Is there platform-specific watermark information to calculate? */
13971         if (dev_priv->display.compute_global_watermarks)
13972                 return dev_priv->display.compute_global_watermarks(state);
13973
13974         return 0;
13975 }
13976
13977 /**
13978  * intel_atomic_check - validate state object
13979  * @dev: drm device
13980  * @state: state to validate
13981  */
13982 static int intel_atomic_check(struct drm_device *dev,
13983                               struct drm_atomic_state *state)
13984 {
13985         struct drm_i915_private *dev_priv = to_i915(dev);
13986         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
13987         struct drm_crtc *crtc;
13988         struct drm_crtc_state *crtc_state;
13989         int ret, i;
13990         bool any_ms = false;
13991
13992         ret = drm_atomic_helper_check_modeset(dev, state);
13993         if (ret)
13994                 return ret;
13995
13996         for_each_crtc_in_state(state, crtc, crtc_state, i) {
13997                 struct intel_crtc_state *pipe_config =
13998                         to_intel_crtc_state(crtc_state);
13999
14000                 /* Catch I915_MODE_FLAG_INHERITED */
14001                 if (crtc_state->mode.private_flags != crtc->state->mode.private_flags)
14002                         crtc_state->mode_changed = true;
14003
14004                 if (!needs_modeset(crtc_state))
14005                         continue;
14006
14007                 if (!crtc_state->enable) {
14008                         any_ms = true;
14009                         continue;
14010                 }
14011
14012                 /* FIXME: For only active_changed we shouldn't need to do any
14013                  * state recomputation at all. */
14014
14015                 ret = drm_atomic_add_affected_connectors(state, crtc);
14016                 if (ret)
14017                         return ret;
14018
14019                 ret = intel_modeset_pipe_config(crtc, pipe_config);
14020                 if (ret) {
14021                         intel_dump_pipe_config(to_intel_crtc(crtc),
14022                                                pipe_config, "[failed]");
14023                         return ret;
14024                 }
14025
14026                 if (i915.fastboot &&
14027                     intel_pipe_config_compare(dev,
14028                                         to_intel_crtc_state(crtc->state),
14029                                         pipe_config, true)) {
14030                         crtc_state->mode_changed = false;
14031                         to_intel_crtc_state(crtc_state)->update_pipe = true;
14032                 }
14033
14034                 if (needs_modeset(crtc_state))
14035                         any_ms = true;
14036
14037                 ret = drm_atomic_add_affected_planes(state, crtc);
14038                 if (ret)
14039                         return ret;
14040
14041                 intel_dump_pipe_config(to_intel_crtc(crtc), pipe_config,
14042                                        needs_modeset(crtc_state) ?
14043                                        "[modeset]" : "[fastset]");
14044         }
14045
14046         if (any_ms) {
14047                 ret = intel_modeset_checks(state);
14048
14049                 if (ret)
14050                         return ret;
14051         } else
14052                 intel_state->cdclk = dev_priv->cdclk_freq;
14053
14054         ret = drm_atomic_helper_check_planes(dev, state);
14055         if (ret)
14056                 return ret;
14057
14058         intel_fbc_choose_crtc(dev_priv, state);
14059         return calc_watermark_data(state);
14060 }
14061
14062 static int intel_atomic_prepare_commit(struct drm_device *dev,
14063                                        struct drm_atomic_state *state,
14064                                        bool nonblock)
14065 {
14066         struct drm_i915_private *dev_priv = to_i915(dev);
14067         struct drm_plane_state *plane_state;
14068         struct drm_crtc_state *crtc_state;
14069         struct drm_plane *plane;
14070         struct drm_crtc *crtc;
14071         int i, ret;
14072
14073         for_each_crtc_in_state(state, crtc, crtc_state, i) {
14074                 if (state->legacy_cursor_update)
14075                         continue;
14076
14077                 ret = intel_crtc_wait_for_pending_flips(crtc);
14078                 if (ret)
14079                         return ret;
14080
14081                 if (atomic_read(&to_intel_crtc(crtc)->unpin_work_count) >= 2)
14082                         flush_workqueue(dev_priv->wq);
14083         }
14084
14085         ret = mutex_lock_interruptible(&dev->struct_mutex);
14086         if (ret)
14087                 return ret;
14088
14089         ret = drm_atomic_helper_prepare_planes(dev, state);
14090         mutex_unlock(&dev->struct_mutex);
14091
14092         if (!ret && !nonblock) {
14093                 for_each_plane_in_state(state, plane, plane_state, i) {
14094                         struct intel_plane_state *intel_plane_state =
14095                                 to_intel_plane_state(plane_state);
14096
14097                         if (!intel_plane_state->wait_req)
14098                                 continue;
14099
14100                         ret = i915_wait_request(intel_plane_state->wait_req,
14101                                                 I915_WAIT_INTERRUPTIBLE,
14102                                                 NULL, NULL);
14103                         if (ret) {
14104                                 /* Any hang should be swallowed by the wait */
14105                                 WARN_ON(ret == -EIO);
14106                                 mutex_lock(&dev->struct_mutex);
14107                                 drm_atomic_helper_cleanup_planes(dev, state);
14108                                 mutex_unlock(&dev->struct_mutex);
14109                                 break;
14110                         }
14111                 }
14112         }
14113
14114         return ret;
14115 }
14116
14117 u32 intel_crtc_get_vblank_counter(struct intel_crtc *crtc)
14118 {
14119         struct drm_device *dev = crtc->base.dev;
14120
14121         if (!dev->max_vblank_count)
14122                 return drm_accurate_vblank_count(&crtc->base);
14123
14124         return dev->driver->get_vblank_counter(dev, crtc->pipe);
14125 }
14126
14127 static void intel_atomic_wait_for_vblanks(struct drm_device *dev,
14128                                           struct drm_i915_private *dev_priv,
14129                                           unsigned crtc_mask)
14130 {
14131         unsigned last_vblank_count[I915_MAX_PIPES];
14132         enum pipe pipe;
14133         int ret;
14134
14135         if (!crtc_mask)
14136                 return;
14137
14138         for_each_pipe(dev_priv, pipe) {
14139                 struct drm_crtc *crtc = dev_priv->pipe_to_crtc_mapping[pipe];
14140
14141                 if (!((1 << pipe) & crtc_mask))
14142                         continue;
14143
14144                 ret = drm_crtc_vblank_get(crtc);
14145                 if (WARN_ON(ret != 0)) {
14146                         crtc_mask &= ~(1 << pipe);
14147                         continue;
14148                 }
14149
14150                 last_vblank_count[pipe] = drm_crtc_vblank_count(crtc);
14151         }
14152
14153         for_each_pipe(dev_priv, pipe) {
14154                 struct drm_crtc *crtc = dev_priv->pipe_to_crtc_mapping[pipe];
14155                 long lret;
14156
14157                 if (!((1 << pipe) & crtc_mask))
14158                         continue;
14159
14160                 lret = wait_event_timeout(dev->vblank[pipe].queue,
14161                                 last_vblank_count[pipe] !=
14162                                         drm_crtc_vblank_count(crtc),
14163                                 msecs_to_jiffies(50));
14164
14165                 WARN(!lret, "pipe %c vblank wait timed out\n", pipe_name(pipe));
14166
14167                 drm_crtc_vblank_put(crtc);
14168         }
14169 }
14170
14171 static bool needs_vblank_wait(struct intel_crtc_state *crtc_state)
14172 {
14173         /* fb updated, need to unpin old fb */
14174         if (crtc_state->fb_changed)
14175                 return true;
14176
14177         /* wm changes, need vblank before final wm's */
14178         if (crtc_state->update_wm_post)
14179                 return true;
14180
14181         /*
14182          * cxsr is re-enabled after vblank.
14183          * This is already handled by crtc_state->update_wm_post,
14184          * but added for clarity.
14185          */
14186         if (crtc_state->disable_cxsr)
14187                 return true;
14188
14189         return false;
14190 }
14191
14192 static void intel_update_crtc(struct drm_crtc *crtc,
14193                               struct drm_atomic_state *state,
14194                               struct drm_crtc_state *old_crtc_state,
14195                               unsigned int *crtc_vblank_mask)
14196 {
14197         struct drm_device *dev = crtc->dev;
14198         struct drm_i915_private *dev_priv = to_i915(dev);
14199         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
14200         struct intel_crtc_state *pipe_config = to_intel_crtc_state(crtc->state);
14201         bool modeset = needs_modeset(crtc->state);
14202
14203         if (modeset) {
14204                 update_scanline_offset(intel_crtc);
14205                 dev_priv->display.crtc_enable(pipe_config, state);
14206         } else {
14207                 intel_pre_plane_update(to_intel_crtc_state(old_crtc_state));
14208         }
14209
14210         if (drm_atomic_get_existing_plane_state(state, crtc->primary)) {
14211                 intel_fbc_enable(
14212                     intel_crtc, pipe_config,
14213                     to_intel_plane_state(crtc->primary->state));
14214         }
14215
14216         drm_atomic_helper_commit_planes_on_crtc(old_crtc_state);
14217
14218         if (needs_vblank_wait(pipe_config))
14219                 *crtc_vblank_mask |= drm_crtc_mask(crtc);
14220 }
14221
14222 static void intel_update_crtcs(struct drm_atomic_state *state,
14223                                unsigned int *crtc_vblank_mask)
14224 {
14225         struct drm_crtc *crtc;
14226         struct drm_crtc_state *old_crtc_state;
14227         int i;
14228
14229         for_each_crtc_in_state(state, crtc, old_crtc_state, i) {
14230                 if (!crtc->state->active)
14231                         continue;
14232
14233                 intel_update_crtc(crtc, state, old_crtc_state,
14234                                   crtc_vblank_mask);
14235         }
14236 }
14237
14238 static void skl_update_crtcs(struct drm_atomic_state *state,
14239                              unsigned int *crtc_vblank_mask)
14240 {
14241         struct drm_device *dev = state->dev;
14242         struct drm_i915_private *dev_priv = to_i915(dev);
14243         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
14244         struct drm_crtc *crtc;
14245         struct drm_crtc_state *old_crtc_state;
14246         struct skl_ddb_allocation *new_ddb = &intel_state->wm_results.ddb;
14247         struct skl_ddb_allocation *cur_ddb = &dev_priv->wm.skl_hw.ddb;
14248         unsigned int updated = 0;
14249         bool progress;
14250         enum pipe pipe;
14251
14252         /*
14253          * Whenever the number of active pipes changes, we need to make sure we
14254          * update the pipes in the right order so that their ddb allocations
14255          * never overlap with eachother inbetween CRTC updates. Otherwise we'll
14256          * cause pipe underruns and other bad stuff.
14257          */
14258         do {
14259                 int i;
14260                 progress = false;
14261
14262                 for_each_crtc_in_state(state, crtc, old_crtc_state, i) {
14263                         bool vbl_wait = false;
14264                         unsigned int cmask = drm_crtc_mask(crtc);
14265                         pipe = to_intel_crtc(crtc)->pipe;
14266
14267                         if (updated & cmask || !crtc->state->active)
14268                                 continue;
14269                         if (skl_ddb_allocation_overlaps(state, cur_ddb, new_ddb,
14270                                                         pipe))
14271                                 continue;
14272
14273                         updated |= cmask;
14274
14275                         /*
14276                          * If this is an already active pipe, it's DDB changed,
14277                          * and this isn't the last pipe that needs updating
14278                          * then we need to wait for a vblank to pass for the
14279                          * new ddb allocation to take effect.
14280                          */
14281                         if (!skl_ddb_allocation_equals(cur_ddb, new_ddb, pipe) &&
14282                             !crtc->state->active_changed &&
14283                             intel_state->wm_results.dirty_pipes != updated)
14284                                 vbl_wait = true;
14285
14286                         intel_update_crtc(crtc, state, old_crtc_state,
14287                                           crtc_vblank_mask);
14288
14289                         if (vbl_wait)
14290                                 intel_wait_for_vblank(dev, pipe);
14291
14292                         progress = true;
14293                 }
14294         } while (progress);
14295 }
14296
14297 static void intel_atomic_commit_tail(struct drm_atomic_state *state)
14298 {
14299         struct drm_device *dev = state->dev;
14300         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
14301         struct drm_i915_private *dev_priv = to_i915(dev);
14302         struct drm_crtc_state *old_crtc_state;
14303         struct drm_crtc *crtc;
14304         struct intel_crtc_state *intel_cstate;
14305         struct drm_plane *plane;
14306         struct drm_plane_state *plane_state;
14307         bool hw_check = intel_state->modeset;
14308         unsigned long put_domains[I915_MAX_PIPES] = {};
14309         unsigned crtc_vblank_mask = 0;
14310         int i, ret;
14311
14312         for_each_plane_in_state(state, plane, plane_state, i) {
14313                 struct intel_plane_state *intel_plane_state =
14314                         to_intel_plane_state(plane_state);
14315
14316                 if (!intel_plane_state->wait_req)
14317                         continue;
14318
14319                 ret = i915_wait_request(intel_plane_state->wait_req,
14320                                         0, NULL, NULL);
14321                 /* EIO should be eaten, and we can't get interrupted in the
14322                  * worker, and blocking commits have waited already. */
14323                 WARN_ON(ret);
14324         }
14325
14326         drm_atomic_helper_wait_for_dependencies(state);
14327
14328         if (intel_state->modeset) {
14329                 memcpy(dev_priv->min_pixclk, intel_state->min_pixclk,
14330                        sizeof(intel_state->min_pixclk));
14331                 dev_priv->active_crtcs = intel_state->active_crtcs;
14332                 dev_priv->atomic_cdclk_freq = intel_state->cdclk;
14333
14334                 intel_display_power_get(dev_priv, POWER_DOMAIN_MODESET);
14335         }
14336
14337         for_each_crtc_in_state(state, crtc, old_crtc_state, i) {
14338                 struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
14339
14340                 if (needs_modeset(crtc->state) ||
14341                     to_intel_crtc_state(crtc->state)->update_pipe) {
14342                         hw_check = true;
14343
14344                         put_domains[to_intel_crtc(crtc)->pipe] =
14345                                 modeset_get_crtc_power_domains(crtc,
14346                                         to_intel_crtc_state(crtc->state));
14347                 }
14348
14349                 if (!needs_modeset(crtc->state))
14350                         continue;
14351
14352                 intel_pre_plane_update(to_intel_crtc_state(old_crtc_state));
14353
14354                 if (old_crtc_state->active) {
14355                         intel_crtc_disable_planes(crtc, old_crtc_state->plane_mask);
14356                         dev_priv->display.crtc_disable(to_intel_crtc_state(old_crtc_state), state);
14357                         intel_crtc->active = false;
14358                         intel_fbc_disable(intel_crtc);
14359                         intel_disable_shared_dpll(intel_crtc);
14360
14361                         /*
14362                          * Underruns don't always raise
14363                          * interrupts, so check manually.
14364                          */
14365                         intel_check_cpu_fifo_underruns(dev_priv);
14366                         intel_check_pch_fifo_underruns(dev_priv);
14367
14368                         if (!crtc->state->active)
14369                                 intel_update_watermarks(crtc);
14370                 }
14371         }
14372
14373         /* Only after disabling all output pipelines that will be changed can we
14374          * update the the output configuration. */
14375         intel_modeset_update_crtc_state(state);
14376
14377         if (intel_state->modeset) {
14378                 drm_atomic_helper_update_legacy_modeset_state(state->dev, state);
14379
14380                 if (dev_priv->display.modeset_commit_cdclk &&
14381                     (intel_state->dev_cdclk != dev_priv->cdclk_freq ||
14382                      intel_state->cdclk_pll_vco != dev_priv->cdclk_pll.vco))
14383                         dev_priv->display.modeset_commit_cdclk(state);
14384
14385                 /*
14386                  * SKL workaround: bspec recommends we disable the SAGV when we
14387                  * have more then one pipe enabled
14388                  */
14389                 if (!intel_can_enable_sagv(state))
14390                         intel_disable_sagv(dev_priv);
14391
14392                 intel_modeset_verify_disabled(dev);
14393         }
14394
14395         /* Complete the events for pipes that have now been disabled */
14396         for_each_crtc_in_state(state, crtc, old_crtc_state, i) {
14397                 bool modeset = needs_modeset(crtc->state);
14398
14399                 /* Complete events for now disable pipes here. */
14400                 if (modeset && !crtc->state->active && crtc->state->event) {
14401                         spin_lock_irq(&dev->event_lock);
14402                         drm_crtc_send_vblank_event(crtc, crtc->state->event);
14403                         spin_unlock_irq(&dev->event_lock);
14404
14405                         crtc->state->event = NULL;
14406                 }
14407         }
14408
14409         /* Now enable the clocks, plane, pipe, and connectors that we set up. */
14410         dev_priv->display.update_crtcs(state, &crtc_vblank_mask);
14411
14412         /* FIXME: We should call drm_atomic_helper_commit_hw_done() here
14413          * already, but still need the state for the delayed optimization. To
14414          * fix this:
14415          * - wrap the optimization/post_plane_update stuff into a per-crtc work.
14416          * - schedule that vblank worker _before_ calling hw_done
14417          * - at the start of commit_tail, cancel it _synchrously
14418          * - switch over to the vblank wait helper in the core after that since
14419          *   we don't need out special handling any more.
14420          */
14421         if (!state->legacy_cursor_update)
14422                 intel_atomic_wait_for_vblanks(dev, dev_priv, crtc_vblank_mask);
14423
14424         /*
14425          * Now that the vblank has passed, we can go ahead and program the
14426          * optimal watermarks on platforms that need two-step watermark
14427          * programming.
14428          *
14429          * TODO: Move this (and other cleanup) to an async worker eventually.
14430          */
14431         for_each_crtc_in_state(state, crtc, old_crtc_state, i) {
14432                 intel_cstate = to_intel_crtc_state(crtc->state);
14433
14434                 if (dev_priv->display.optimize_watermarks)
14435                         dev_priv->display.optimize_watermarks(intel_cstate);
14436         }
14437
14438         for_each_crtc_in_state(state, crtc, old_crtc_state, i) {
14439                 intel_post_plane_update(to_intel_crtc_state(old_crtc_state));
14440
14441                 if (put_domains[i])
14442                         modeset_put_power_domains(dev_priv, put_domains[i]);
14443
14444                 intel_modeset_verify_crtc(crtc, old_crtc_state, crtc->state);
14445         }
14446
14447         if (intel_state->modeset && intel_can_enable_sagv(state))
14448                 intel_enable_sagv(dev_priv);
14449
14450         drm_atomic_helper_commit_hw_done(state);
14451
14452         if (intel_state->modeset)
14453                 intel_display_power_put(dev_priv, POWER_DOMAIN_MODESET);
14454
14455         mutex_lock(&dev->struct_mutex);
14456         drm_atomic_helper_cleanup_planes(dev, state);
14457         mutex_unlock(&dev->struct_mutex);
14458
14459         drm_atomic_helper_commit_cleanup_done(state);
14460
14461         drm_atomic_state_free(state);
14462
14463         /* As one of the primary mmio accessors, KMS has a high likelihood
14464          * of triggering bugs in unclaimed access. After we finish
14465          * modesetting, see if an error has been flagged, and if so
14466          * enable debugging for the next modeset - and hope we catch
14467          * the culprit.
14468          *
14469          * XXX note that we assume display power is on at this point.
14470          * This might hold true now but we need to add pm helper to check
14471          * unclaimed only when the hardware is on, as atomic commits
14472          * can happen also when the device is completely off.
14473          */
14474         intel_uncore_arm_unclaimed_mmio_detection(dev_priv);
14475 }
14476
14477 static void intel_atomic_commit_work(struct work_struct *work)
14478 {
14479         struct drm_atomic_state *state = container_of(work,
14480                                                       struct drm_atomic_state,
14481                                                       commit_work);
14482         intel_atomic_commit_tail(state);
14483 }
14484
14485 static void intel_atomic_track_fbs(struct drm_atomic_state *state)
14486 {
14487         struct drm_plane_state *old_plane_state;
14488         struct drm_plane *plane;
14489         int i;
14490
14491         for_each_plane_in_state(state, plane, old_plane_state, i)
14492                 i915_gem_track_fb(intel_fb_obj(old_plane_state->fb),
14493                                   intel_fb_obj(plane->state->fb),
14494                                   to_intel_plane(plane)->frontbuffer_bit);
14495 }
14496
14497 /**
14498  * intel_atomic_commit - commit validated state object
14499  * @dev: DRM device
14500  * @state: the top-level driver state object
14501  * @nonblock: nonblocking commit
14502  *
14503  * This function commits a top-level state object that has been validated
14504  * with drm_atomic_helper_check().
14505  *
14506  * FIXME:  Atomic modeset support for i915 is not yet complete.  At the moment
14507  * nonblocking commits are only safe for pure plane updates. Everything else
14508  * should work though.
14509  *
14510  * RETURNS
14511  * Zero for success or -errno.
14512  */
14513 static int intel_atomic_commit(struct drm_device *dev,
14514                                struct drm_atomic_state *state,
14515                                bool nonblock)
14516 {
14517         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
14518         struct drm_i915_private *dev_priv = to_i915(dev);
14519         int ret = 0;
14520
14521         if (intel_state->modeset && nonblock) {
14522                 DRM_DEBUG_KMS("nonblocking commit for modeset not yet implemented.\n");
14523                 return -EINVAL;
14524         }
14525
14526         ret = drm_atomic_helper_setup_commit(state, nonblock);
14527         if (ret)
14528                 return ret;
14529
14530         INIT_WORK(&state->commit_work, intel_atomic_commit_work);
14531
14532         ret = intel_atomic_prepare_commit(dev, state, nonblock);
14533         if (ret) {
14534                 DRM_DEBUG_ATOMIC("Preparing state failed with %i\n", ret);
14535                 return ret;
14536         }
14537
14538         drm_atomic_helper_swap_state(state, true);
14539         dev_priv->wm.distrust_bios_wm = false;
14540         dev_priv->wm.skl_results = intel_state->wm_results;
14541         intel_shared_dpll_commit(state);
14542         intel_atomic_track_fbs(state);
14543
14544         if (nonblock)
14545                 queue_work(system_unbound_wq, &state->commit_work);
14546         else
14547                 intel_atomic_commit_tail(state);
14548
14549         return 0;
14550 }
14551
14552 void intel_crtc_restore_mode(struct drm_crtc *crtc)
14553 {
14554         struct drm_device *dev = crtc->dev;
14555         struct drm_atomic_state *state;
14556         struct drm_crtc_state *crtc_state;
14557         int ret;
14558
14559         state = drm_atomic_state_alloc(dev);
14560         if (!state) {
14561                 DRM_DEBUG_KMS("[CRTC:%d:%s] crtc restore failed, out of memory",
14562                               crtc->base.id, crtc->name);
14563                 return;
14564         }
14565
14566         state->acquire_ctx = drm_modeset_legacy_acquire_ctx(crtc);
14567
14568 retry:
14569         crtc_state = drm_atomic_get_crtc_state(state, crtc);
14570         ret = PTR_ERR_OR_ZERO(crtc_state);
14571         if (!ret) {
14572                 if (!crtc_state->active)
14573                         goto out;
14574
14575                 crtc_state->mode_changed = true;
14576                 ret = drm_atomic_commit(state);
14577         }
14578
14579         if (ret == -EDEADLK) {
14580                 drm_atomic_state_clear(state);
14581                 drm_modeset_backoff(state->acquire_ctx);
14582                 goto retry;
14583         }
14584
14585         if (ret)
14586 out:
14587                 drm_atomic_state_free(state);
14588 }
14589
14590 /*
14591  * FIXME: Remove this once i915 is fully DRIVER_ATOMIC by calling
14592  *        drm_atomic_helper_legacy_gamma_set() directly.
14593  */
14594 static int intel_atomic_legacy_gamma_set(struct drm_crtc *crtc,
14595                                          u16 *red, u16 *green, u16 *blue,
14596                                          uint32_t size)
14597 {
14598         struct drm_device *dev = crtc->dev;
14599         struct drm_mode_config *config = &dev->mode_config;
14600         struct drm_crtc_state *state;
14601         int ret;
14602
14603         ret = drm_atomic_helper_legacy_gamma_set(crtc, red, green, blue, size);
14604         if (ret)
14605                 return ret;
14606
14607         /*
14608          * Make sure we update the legacy properties so this works when
14609          * atomic is not enabled.
14610          */
14611
14612         state = crtc->state;
14613
14614         drm_object_property_set_value(&crtc->base,
14615                                       config->degamma_lut_property,
14616                                       (state->degamma_lut) ?
14617                                       state->degamma_lut->base.id : 0);
14618
14619         drm_object_property_set_value(&crtc->base,
14620                                       config->ctm_property,
14621                                       (state->ctm) ?
14622                                       state->ctm->base.id : 0);
14623
14624         drm_object_property_set_value(&crtc->base,
14625                                       config->gamma_lut_property,
14626                                       (state->gamma_lut) ?
14627                                       state->gamma_lut->base.id : 0);
14628
14629         return 0;
14630 }
14631
14632 static const struct drm_crtc_funcs intel_crtc_funcs = {
14633         .gamma_set = intel_atomic_legacy_gamma_set,
14634         .set_config = drm_atomic_helper_set_config,
14635         .set_property = drm_atomic_helper_crtc_set_property,
14636         .destroy = intel_crtc_destroy,
14637         .page_flip = intel_crtc_page_flip,
14638         .atomic_duplicate_state = intel_crtc_duplicate_state,
14639         .atomic_destroy_state = intel_crtc_destroy_state,
14640 };
14641
14642 /**
14643  * intel_prepare_plane_fb - Prepare fb for usage on plane
14644  * @plane: drm plane to prepare for
14645  * @fb: framebuffer to prepare for presentation
14646  *
14647  * Prepares a framebuffer for usage on a display plane.  Generally this
14648  * involves pinning the underlying object and updating the frontbuffer tracking
14649  * bits.  Some older platforms need special physical address handling for
14650  * cursor planes.
14651  *
14652  * Must be called with struct_mutex held.
14653  *
14654  * Returns 0 on success, negative error code on failure.
14655  */
14656 int
14657 intel_prepare_plane_fb(struct drm_plane *plane,
14658                        struct drm_plane_state *new_state)
14659 {
14660         struct drm_device *dev = plane->dev;
14661         struct drm_i915_private *dev_priv = to_i915(dev);
14662         struct drm_framebuffer *fb = new_state->fb;
14663         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
14664         struct drm_i915_gem_object *old_obj = intel_fb_obj(plane->state->fb);
14665         struct reservation_object *resv;
14666         int ret = 0;
14667
14668         if (!obj && !old_obj)
14669                 return 0;
14670
14671         if (old_obj) {
14672                 struct drm_crtc_state *crtc_state =
14673                         drm_atomic_get_existing_crtc_state(new_state->state, plane->state->crtc);
14674
14675                 /* Big Hammer, we also need to ensure that any pending
14676                  * MI_WAIT_FOR_EVENT inside a user batch buffer on the
14677                  * current scanout is retired before unpinning the old
14678                  * framebuffer. Note that we rely on userspace rendering
14679                  * into the buffer attached to the pipe they are waiting
14680                  * on. If not, userspace generates a GPU hang with IPEHR
14681                  * point to the MI_WAIT_FOR_EVENT.
14682                  *
14683                  * This should only fail upon a hung GPU, in which case we
14684                  * can safely continue.
14685                  */
14686                 if (needs_modeset(crtc_state))
14687                         ret = i915_gem_object_wait_rendering(old_obj, true);
14688                 if (ret) {
14689                         /* GPU hangs should have been swallowed by the wait */
14690                         WARN_ON(ret == -EIO);
14691                         return ret;
14692                 }
14693         }
14694
14695         if (!obj)
14696                 return 0;
14697
14698         /* For framebuffer backed by dmabuf, wait for fence */
14699         resv = i915_gem_object_get_dmabuf_resv(obj);
14700         if (resv) {
14701                 long lret;
14702
14703                 lret = reservation_object_wait_timeout_rcu(resv, false, true,
14704                                                            MAX_SCHEDULE_TIMEOUT);
14705                 if (lret == -ERESTARTSYS)
14706                         return lret;
14707
14708                 WARN(lret < 0, "waiting returns %li\n", lret);
14709         }
14710
14711         if (plane->type == DRM_PLANE_TYPE_CURSOR &&
14712             INTEL_INFO(dev)->cursor_needs_physical) {
14713                 int align = IS_I830(dev_priv) ? 16 * 1024 : 256;
14714                 ret = i915_gem_object_attach_phys(obj, align);
14715                 if (ret)
14716                         DRM_DEBUG_KMS("failed to attach phys object\n");
14717         } else {
14718                 struct i915_vma *vma;
14719
14720                 vma = intel_pin_and_fence_fb_obj(fb, new_state->rotation);
14721                 if (IS_ERR(vma))
14722                         ret = PTR_ERR(vma);
14723         }
14724
14725         if (ret == 0) {
14726                 to_intel_plane_state(new_state)->wait_req =
14727                         i915_gem_active_get(&obj->last_write,
14728                                             &obj->base.dev->struct_mutex);
14729         }
14730
14731         return ret;
14732 }
14733
14734 /**
14735  * intel_cleanup_plane_fb - Cleans up an fb after plane use
14736  * @plane: drm plane to clean up for
14737  * @fb: old framebuffer that was on plane
14738  *
14739  * Cleans up a framebuffer that has just been removed from a plane.
14740  *
14741  * Must be called with struct_mutex held.
14742  */
14743 void
14744 intel_cleanup_plane_fb(struct drm_plane *plane,
14745                        struct drm_plane_state *old_state)
14746 {
14747         struct drm_device *dev = plane->dev;
14748         struct intel_plane_state *old_intel_state;
14749         struct intel_plane_state *intel_state = to_intel_plane_state(plane->state);
14750         struct drm_i915_gem_object *old_obj = intel_fb_obj(old_state->fb);
14751         struct drm_i915_gem_object *obj = intel_fb_obj(plane->state->fb);
14752
14753         old_intel_state = to_intel_plane_state(old_state);
14754
14755         if (!obj && !old_obj)
14756                 return;
14757
14758         if (old_obj && (plane->type != DRM_PLANE_TYPE_CURSOR ||
14759             !INTEL_INFO(dev)->cursor_needs_physical))
14760                 intel_unpin_fb_obj(old_state->fb, old_state->rotation);
14761
14762         i915_gem_request_assign(&intel_state->wait_req, NULL);
14763         i915_gem_request_assign(&old_intel_state->wait_req, NULL);
14764 }
14765
14766 int
14767 skl_max_scale(struct intel_crtc *intel_crtc, struct intel_crtc_state *crtc_state)
14768 {
14769         int max_scale;
14770         int crtc_clock, cdclk;
14771
14772         if (!intel_crtc || !crtc_state->base.enable)
14773                 return DRM_PLANE_HELPER_NO_SCALING;
14774
14775         crtc_clock = crtc_state->base.adjusted_mode.crtc_clock;
14776         cdclk = to_intel_atomic_state(crtc_state->base.state)->cdclk;
14777
14778         if (WARN_ON_ONCE(!crtc_clock || cdclk < crtc_clock))
14779                 return DRM_PLANE_HELPER_NO_SCALING;
14780
14781         /*
14782          * skl max scale is lower of:
14783          *    close to 3 but not 3, -1 is for that purpose
14784          *            or
14785          *    cdclk/crtc_clock
14786          */
14787         max_scale = min((1 << 16) * 3 - 1, (1 << 8) * ((cdclk << 8) / crtc_clock));
14788
14789         return max_scale;
14790 }
14791
14792 static int
14793 intel_check_primary_plane(struct drm_plane *plane,
14794                           struct intel_crtc_state *crtc_state,
14795                           struct intel_plane_state *state)
14796 {
14797         struct drm_i915_private *dev_priv = to_i915(plane->dev);
14798         struct drm_crtc *crtc = state->base.crtc;
14799         int min_scale = DRM_PLANE_HELPER_NO_SCALING;
14800         int max_scale = DRM_PLANE_HELPER_NO_SCALING;
14801         bool can_position = false;
14802         int ret;
14803
14804         if (INTEL_GEN(dev_priv) >= 9) {
14805                 /* use scaler when colorkey is not required */
14806                 if (state->ckey.flags == I915_SET_COLORKEY_NONE) {
14807                         min_scale = 1;
14808                         max_scale = skl_max_scale(to_intel_crtc(crtc), crtc_state);
14809                 }
14810                 can_position = true;
14811         }
14812
14813         ret = drm_plane_helper_check_state(&state->base,
14814                                            &state->clip,
14815                                            min_scale, max_scale,
14816                                            can_position, true);
14817         if (ret)
14818                 return ret;
14819
14820         if (!state->base.fb)
14821                 return 0;
14822
14823         if (INTEL_GEN(dev_priv) >= 9) {
14824                 ret = skl_check_plane_surface(state);
14825                 if (ret)
14826                         return ret;
14827         }
14828
14829         return 0;
14830 }
14831
14832 static void intel_begin_crtc_commit(struct drm_crtc *crtc,
14833                                     struct drm_crtc_state *old_crtc_state)
14834 {
14835         struct drm_device *dev = crtc->dev;
14836         struct drm_i915_private *dev_priv = to_i915(dev);
14837         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
14838         struct intel_crtc_state *old_intel_state =
14839                 to_intel_crtc_state(old_crtc_state);
14840         bool modeset = needs_modeset(crtc->state);
14841         enum pipe pipe = intel_crtc->pipe;
14842
14843         /* Perform vblank evasion around commit operation */
14844         intel_pipe_update_start(intel_crtc);
14845
14846         if (modeset)
14847                 return;
14848
14849         if (crtc->state->color_mgmt_changed || to_intel_crtc_state(crtc->state)->update_pipe) {
14850                 intel_color_set_csc(crtc->state);
14851                 intel_color_load_luts(crtc->state);
14852         }
14853
14854         if (to_intel_crtc_state(crtc->state)->update_pipe)
14855                 intel_update_pipe_config(intel_crtc, old_intel_state);
14856         else if (INTEL_GEN(dev_priv) >= 9) {
14857                 skl_detach_scalers(intel_crtc);
14858
14859                 I915_WRITE(PIPE_WM_LINETIME(pipe),
14860                            dev_priv->wm.skl_hw.wm_linetime[pipe]);
14861         }
14862 }
14863
14864 static void intel_finish_crtc_commit(struct drm_crtc *crtc,
14865                                      struct drm_crtc_state *old_crtc_state)
14866 {
14867         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
14868
14869         intel_pipe_update_end(intel_crtc, NULL);
14870 }
14871
14872 /**
14873  * intel_plane_destroy - destroy a plane
14874  * @plane: plane to destroy
14875  *
14876  * Common destruction function for all types of planes (primary, cursor,
14877  * sprite).
14878  */
14879 void intel_plane_destroy(struct drm_plane *plane)
14880 {
14881         if (!plane)
14882                 return;
14883
14884         drm_plane_cleanup(plane);
14885         kfree(to_intel_plane(plane));
14886 }
14887
14888 const struct drm_plane_funcs intel_plane_funcs = {
14889         .update_plane = drm_atomic_helper_update_plane,
14890         .disable_plane = drm_atomic_helper_disable_plane,
14891         .destroy = intel_plane_destroy,
14892         .set_property = drm_atomic_helper_plane_set_property,
14893         .atomic_get_property = intel_plane_atomic_get_property,
14894         .atomic_set_property = intel_plane_atomic_set_property,
14895         .atomic_duplicate_state = intel_plane_duplicate_state,
14896         .atomic_destroy_state = intel_plane_destroy_state,
14897
14898 };
14899
14900 static struct drm_plane *intel_primary_plane_create(struct drm_device *dev,
14901                                                     int pipe)
14902 {
14903         struct drm_i915_private *dev_priv = to_i915(dev);
14904         struct intel_plane *primary = NULL;
14905         struct intel_plane_state *state = NULL;
14906         const uint32_t *intel_primary_formats;
14907         unsigned int num_formats;
14908         int ret;
14909
14910         primary = kzalloc(sizeof(*primary), GFP_KERNEL);
14911         if (!primary)
14912                 goto fail;
14913
14914         state = intel_create_plane_state(&primary->base);
14915         if (!state)
14916                 goto fail;
14917         primary->base.state = &state->base;
14918
14919         primary->can_scale = false;
14920         primary->max_downscale = 1;
14921         if (INTEL_INFO(dev)->gen >= 9) {
14922                 primary->can_scale = true;
14923                 state->scaler_id = -1;
14924         }
14925         primary->pipe = pipe;
14926         primary->plane = pipe;
14927         primary->frontbuffer_bit = INTEL_FRONTBUFFER_PRIMARY(pipe);
14928         primary->check_plane = intel_check_primary_plane;
14929         if (HAS_FBC(dev) && INTEL_INFO(dev)->gen < 4)
14930                 primary->plane = !pipe;
14931
14932         if (INTEL_INFO(dev)->gen >= 9) {
14933                 intel_primary_formats = skl_primary_formats;
14934                 num_formats = ARRAY_SIZE(skl_primary_formats);
14935
14936                 primary->update_plane = skylake_update_primary_plane;
14937                 primary->disable_plane = skylake_disable_primary_plane;
14938         } else if (HAS_PCH_SPLIT(dev_priv)) {
14939                 intel_primary_formats = i965_primary_formats;
14940                 num_formats = ARRAY_SIZE(i965_primary_formats);
14941
14942                 primary->update_plane = ironlake_update_primary_plane;
14943                 primary->disable_plane = i9xx_disable_primary_plane;
14944         } else if (INTEL_INFO(dev)->gen >= 4) {
14945                 intel_primary_formats = i965_primary_formats;
14946                 num_formats = ARRAY_SIZE(i965_primary_formats);
14947
14948                 primary->update_plane = i9xx_update_primary_plane;
14949                 primary->disable_plane = i9xx_disable_primary_plane;
14950         } else {
14951                 intel_primary_formats = i8xx_primary_formats;
14952                 num_formats = ARRAY_SIZE(i8xx_primary_formats);
14953
14954                 primary->update_plane = i9xx_update_primary_plane;
14955                 primary->disable_plane = i9xx_disable_primary_plane;
14956         }
14957
14958         if (INTEL_INFO(dev)->gen >= 9)
14959                 ret = drm_universal_plane_init(dev, &primary->base, 0,
14960                                                &intel_plane_funcs,
14961                                                intel_primary_formats, num_formats,
14962                                                DRM_PLANE_TYPE_PRIMARY,
14963                                                "plane 1%c", pipe_name(pipe));
14964         else if (INTEL_INFO(dev)->gen >= 5 || IS_G4X(dev))
14965                 ret = drm_universal_plane_init(dev, &primary->base, 0,
14966                                                &intel_plane_funcs,
14967                                                intel_primary_formats, num_formats,
14968                                                DRM_PLANE_TYPE_PRIMARY,
14969                                                "primary %c", pipe_name(pipe));
14970         else
14971                 ret = drm_universal_plane_init(dev, &primary->base, 0,
14972                                                &intel_plane_funcs,
14973                                                intel_primary_formats, num_formats,
14974                                                DRM_PLANE_TYPE_PRIMARY,
14975                                                "plane %c", plane_name(primary->plane));
14976         if (ret)
14977                 goto fail;
14978
14979         if (INTEL_INFO(dev)->gen >= 4)
14980                 intel_create_rotation_property(dev, primary);
14981
14982         drm_plane_helper_add(&primary->base, &intel_plane_helper_funcs);
14983
14984         return &primary->base;
14985
14986 fail:
14987         kfree(state);
14988         kfree(primary);
14989
14990         return NULL;
14991 }
14992
14993 void intel_create_rotation_property(struct drm_device *dev, struct intel_plane *plane)
14994 {
14995         if (!dev->mode_config.rotation_property) {
14996                 unsigned long flags = DRM_ROTATE_0 |
14997                         DRM_ROTATE_180;
14998
14999                 if (INTEL_INFO(dev)->gen >= 9)
15000                         flags |= DRM_ROTATE_90 | DRM_ROTATE_270;
15001
15002                 dev->mode_config.rotation_property =
15003                         drm_mode_create_rotation_property(dev, flags);
15004         }
15005         if (dev->mode_config.rotation_property)
15006                 drm_object_attach_property(&plane->base.base,
15007                                 dev->mode_config.rotation_property,
15008                                 plane->base.state->rotation);
15009 }
15010
15011 static int
15012 intel_check_cursor_plane(struct drm_plane *plane,
15013                          struct intel_crtc_state *crtc_state,
15014                          struct intel_plane_state *state)
15015 {
15016         struct drm_framebuffer *fb = state->base.fb;
15017         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
15018         enum pipe pipe = to_intel_plane(plane)->pipe;
15019         unsigned stride;
15020         int ret;
15021
15022         ret = drm_plane_helper_check_state(&state->base,
15023                                            &state->clip,
15024                                            DRM_PLANE_HELPER_NO_SCALING,
15025                                            DRM_PLANE_HELPER_NO_SCALING,
15026                                            true, true);
15027         if (ret)
15028                 return ret;
15029
15030         /* if we want to turn off the cursor ignore width and height */
15031         if (!obj)
15032                 return 0;
15033
15034         /* Check for which cursor types we support */
15035         if (!cursor_size_ok(to_i915(plane->dev), state->base.crtc_w,
15036                             state->base.crtc_h)) {
15037                 DRM_DEBUG("Cursor dimension %dx%d not supported\n",
15038                           state->base.crtc_w, state->base.crtc_h);
15039                 return -EINVAL;
15040         }
15041
15042         stride = roundup_pow_of_two(state->base.crtc_w) * 4;
15043         if (obj->base.size < stride * state->base.crtc_h) {
15044                 DRM_DEBUG_KMS("buffer is too small\n");
15045                 return -ENOMEM;
15046         }
15047
15048         if (fb->modifier[0] != DRM_FORMAT_MOD_NONE) {
15049                 DRM_DEBUG_KMS("cursor cannot be tiled\n");
15050                 return -EINVAL;
15051         }
15052
15053         /*
15054          * There's something wrong with the cursor on CHV pipe C.
15055          * If it straddles the left edge of the screen then
15056          * moving it away from the edge or disabling it often
15057          * results in a pipe underrun, and often that can lead to
15058          * dead pipe (constant underrun reported, and it scans
15059          * out just a solid color). To recover from that, the
15060          * display power well must be turned off and on again.
15061          * Refuse the put the cursor into that compromised position.
15062          */
15063         if (IS_CHERRYVIEW(plane->dev) && pipe == PIPE_C &&
15064             state->base.visible && state->base.crtc_x < 0) {
15065                 DRM_DEBUG_KMS("CHV cursor C not allowed to straddle the left screen edge\n");
15066                 return -EINVAL;
15067         }
15068
15069         return 0;
15070 }
15071
15072 static void
15073 intel_disable_cursor_plane(struct drm_plane *plane,
15074                            struct drm_crtc *crtc)
15075 {
15076         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
15077
15078         intel_crtc->cursor_addr = 0;
15079         intel_crtc_update_cursor(crtc, NULL);
15080 }
15081
15082 static void
15083 intel_update_cursor_plane(struct drm_plane *plane,
15084                           const struct intel_crtc_state *crtc_state,
15085                           const struct intel_plane_state *state)
15086 {
15087         struct drm_crtc *crtc = crtc_state->base.crtc;
15088         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
15089         struct drm_device *dev = plane->dev;
15090         struct drm_i915_gem_object *obj = intel_fb_obj(state->base.fb);
15091         uint32_t addr;
15092
15093         if (!obj)
15094                 addr = 0;
15095         else if (!INTEL_INFO(dev)->cursor_needs_physical)
15096                 addr = i915_gem_object_ggtt_offset(obj, NULL);
15097         else
15098                 addr = obj->phys_handle->busaddr;
15099
15100         intel_crtc->cursor_addr = addr;
15101         intel_crtc_update_cursor(crtc, state);
15102 }
15103
15104 static struct drm_plane *intel_cursor_plane_create(struct drm_device *dev,
15105                                                    int pipe)
15106 {
15107         struct intel_plane *cursor = NULL;
15108         struct intel_plane_state *state = NULL;
15109         int ret;
15110
15111         cursor = kzalloc(sizeof(*cursor), GFP_KERNEL);
15112         if (!cursor)
15113                 goto fail;
15114
15115         state = intel_create_plane_state(&cursor->base);
15116         if (!state)
15117                 goto fail;
15118         cursor->base.state = &state->base;
15119
15120         cursor->can_scale = false;
15121         cursor->max_downscale = 1;
15122         cursor->pipe = pipe;
15123         cursor->plane = pipe;
15124         cursor->frontbuffer_bit = INTEL_FRONTBUFFER_CURSOR(pipe);
15125         cursor->check_plane = intel_check_cursor_plane;
15126         cursor->update_plane = intel_update_cursor_plane;
15127         cursor->disable_plane = intel_disable_cursor_plane;
15128
15129         ret = drm_universal_plane_init(dev, &cursor->base, 0,
15130                                        &intel_plane_funcs,
15131                                        intel_cursor_formats,
15132                                        ARRAY_SIZE(intel_cursor_formats),
15133                                        DRM_PLANE_TYPE_CURSOR,
15134                                        "cursor %c", pipe_name(pipe));
15135         if (ret)
15136                 goto fail;
15137
15138         if (INTEL_INFO(dev)->gen >= 4) {
15139                 if (!dev->mode_config.rotation_property)
15140                         dev->mode_config.rotation_property =
15141                                 drm_mode_create_rotation_property(dev,
15142                                                         DRM_ROTATE_0 |
15143                                                         DRM_ROTATE_180);
15144                 if (dev->mode_config.rotation_property)
15145                         drm_object_attach_property(&cursor->base.base,
15146                                 dev->mode_config.rotation_property,
15147                                 state->base.rotation);
15148         }
15149
15150         if (INTEL_INFO(dev)->gen >=9)
15151                 state->scaler_id = -1;
15152
15153         drm_plane_helper_add(&cursor->base, &intel_plane_helper_funcs);
15154
15155         return &cursor->base;
15156
15157 fail:
15158         kfree(state);
15159         kfree(cursor);
15160
15161         return NULL;
15162 }
15163
15164 static void skl_init_scalers(struct drm_device *dev, struct intel_crtc *intel_crtc,
15165         struct intel_crtc_state *crtc_state)
15166 {
15167         int i;
15168         struct intel_scaler *intel_scaler;
15169         struct intel_crtc_scaler_state *scaler_state = &crtc_state->scaler_state;
15170
15171         for (i = 0; i < intel_crtc->num_scalers; i++) {
15172                 intel_scaler = &scaler_state->scalers[i];
15173                 intel_scaler->in_use = 0;
15174                 intel_scaler->mode = PS_SCALER_MODE_DYN;
15175         }
15176
15177         scaler_state->scaler_id = -1;
15178 }
15179
15180 static void intel_crtc_init(struct drm_device *dev, int pipe)
15181 {
15182         struct drm_i915_private *dev_priv = to_i915(dev);
15183         struct intel_crtc *intel_crtc;
15184         struct intel_crtc_state *crtc_state = NULL;
15185         struct drm_plane *primary = NULL;
15186         struct drm_plane *cursor = NULL;
15187         int ret;
15188
15189         intel_crtc = kzalloc(sizeof(*intel_crtc), GFP_KERNEL);
15190         if (intel_crtc == NULL)
15191                 return;
15192
15193         crtc_state = kzalloc(sizeof(*crtc_state), GFP_KERNEL);
15194         if (!crtc_state)
15195                 goto fail;
15196         intel_crtc->config = crtc_state;
15197         intel_crtc->base.state = &crtc_state->base;
15198         crtc_state->base.crtc = &intel_crtc->base;
15199
15200         /* initialize shared scalers */
15201         if (INTEL_INFO(dev)->gen >= 9) {
15202                 if (pipe == PIPE_C)
15203                         intel_crtc->num_scalers = 1;
15204                 else
15205                         intel_crtc->num_scalers = SKL_NUM_SCALERS;
15206
15207                 skl_init_scalers(dev, intel_crtc, crtc_state);
15208         }
15209
15210         primary = intel_primary_plane_create(dev, pipe);
15211         if (!primary)
15212                 goto fail;
15213
15214         cursor = intel_cursor_plane_create(dev, pipe);
15215         if (!cursor)
15216                 goto fail;
15217
15218         ret = drm_crtc_init_with_planes(dev, &intel_crtc->base, primary,
15219                                         cursor, &intel_crtc_funcs,
15220                                         "pipe %c", pipe_name(pipe));
15221         if (ret)
15222                 goto fail;
15223
15224         /*
15225          * On gen2/3 only plane A can do fbc, but the panel fitter and lvds port
15226          * is hooked to pipe B. Hence we want plane A feeding pipe B.
15227          */
15228         intel_crtc->pipe = pipe;
15229         intel_crtc->plane = pipe;
15230         if (HAS_FBC(dev) && INTEL_INFO(dev)->gen < 4) {
15231                 DRM_DEBUG_KMS("swapping pipes & planes for FBC\n");
15232                 intel_crtc->plane = !pipe;
15233         }
15234
15235         intel_crtc->cursor_base = ~0;
15236         intel_crtc->cursor_cntl = ~0;
15237         intel_crtc->cursor_size = ~0;
15238
15239         intel_crtc->wm.cxsr_allowed = true;
15240
15241         BUG_ON(pipe >= ARRAY_SIZE(dev_priv->plane_to_crtc_mapping) ||
15242                dev_priv->plane_to_crtc_mapping[intel_crtc->plane] != NULL);
15243         dev_priv->plane_to_crtc_mapping[intel_crtc->plane] = &intel_crtc->base;
15244         dev_priv->pipe_to_crtc_mapping[intel_crtc->pipe] = &intel_crtc->base;
15245
15246         drm_crtc_helper_add(&intel_crtc->base, &intel_helper_funcs);
15247
15248         intel_color_init(&intel_crtc->base);
15249
15250         WARN_ON(drm_crtc_index(&intel_crtc->base) != intel_crtc->pipe);
15251         return;
15252
15253 fail:
15254         intel_plane_destroy(primary);
15255         intel_plane_destroy(cursor);
15256         kfree(crtc_state);
15257         kfree(intel_crtc);
15258 }
15259
15260 enum pipe intel_get_pipe_from_connector(struct intel_connector *connector)
15261 {
15262         struct drm_encoder *encoder = connector->base.encoder;
15263         struct drm_device *dev = connector->base.dev;
15264
15265         WARN_ON(!drm_modeset_is_locked(&dev->mode_config.connection_mutex));
15266
15267         if (!encoder || WARN_ON(!encoder->crtc))
15268                 return INVALID_PIPE;
15269
15270         return to_intel_crtc(encoder->crtc)->pipe;
15271 }
15272
15273 int intel_get_pipe_from_crtc_id(struct drm_device *dev, void *data,
15274                                 struct drm_file *file)
15275 {
15276         struct drm_i915_get_pipe_from_crtc_id *pipe_from_crtc_id = data;
15277         struct drm_crtc *drmmode_crtc;
15278         struct intel_crtc *crtc;
15279
15280         drmmode_crtc = drm_crtc_find(dev, pipe_from_crtc_id->crtc_id);
15281         if (!drmmode_crtc)
15282                 return -ENOENT;
15283
15284         crtc = to_intel_crtc(drmmode_crtc);
15285         pipe_from_crtc_id->pipe = crtc->pipe;
15286
15287         return 0;
15288 }
15289
15290 static int intel_encoder_clones(struct intel_encoder *encoder)
15291 {
15292         struct drm_device *dev = encoder->base.dev;
15293         struct intel_encoder *source_encoder;
15294         int index_mask = 0;
15295         int entry = 0;
15296
15297         for_each_intel_encoder(dev, source_encoder) {
15298                 if (encoders_cloneable(encoder, source_encoder))
15299                         index_mask |= (1 << entry);
15300
15301                 entry++;
15302         }
15303
15304         return index_mask;
15305 }
15306
15307 static bool has_edp_a(struct drm_device *dev)
15308 {
15309         struct drm_i915_private *dev_priv = to_i915(dev);
15310
15311         if (!IS_MOBILE(dev))
15312                 return false;
15313
15314         if ((I915_READ(DP_A) & DP_DETECTED) == 0)
15315                 return false;
15316
15317         if (IS_GEN5(dev) && (I915_READ(FUSE_STRAP) & ILK_eDP_A_DISABLE))
15318                 return false;
15319
15320         return true;
15321 }
15322
15323 static bool intel_crt_present(struct drm_device *dev)
15324 {
15325         struct drm_i915_private *dev_priv = to_i915(dev);
15326
15327         if (INTEL_INFO(dev)->gen >= 9)
15328                 return false;
15329
15330         if (IS_HSW_ULT(dev_priv) || IS_BDW_ULT(dev_priv))
15331                 return false;
15332
15333         if (IS_CHERRYVIEW(dev))
15334                 return false;
15335
15336         if (HAS_PCH_LPT_H(dev_priv) &&
15337             I915_READ(SFUSE_STRAP) & SFUSE_STRAP_CRT_DISABLED)
15338                 return false;
15339
15340         /* DDI E can't be used if DDI A requires 4 lanes */
15341         if (HAS_DDI(dev_priv) && I915_READ(DDI_BUF_CTL(PORT_A)) & DDI_A_4_LANES)
15342                 return false;
15343
15344         if (!dev_priv->vbt.int_crt_support)
15345                 return false;
15346
15347         return true;
15348 }
15349
15350 void intel_pps_unlock_regs_wa(struct drm_i915_private *dev_priv)
15351 {
15352         int pps_num;
15353         int pps_idx;
15354
15355         if (HAS_DDI(dev_priv))
15356                 return;
15357         /*
15358          * This w/a is needed at least on CPT/PPT, but to be sure apply it
15359          * everywhere where registers can be write protected.
15360          */
15361         if (IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv))
15362                 pps_num = 2;
15363         else
15364                 pps_num = 1;
15365
15366         for (pps_idx = 0; pps_idx < pps_num; pps_idx++) {
15367                 u32 val = I915_READ(PP_CONTROL(pps_idx));
15368
15369                 val = (val & ~PANEL_UNLOCK_MASK) | PANEL_UNLOCK_REGS;
15370                 I915_WRITE(PP_CONTROL(pps_idx), val);
15371         }
15372 }
15373
15374 static void intel_pps_init(struct drm_i915_private *dev_priv)
15375 {
15376         if (HAS_PCH_SPLIT(dev_priv) || IS_BROXTON(dev_priv))
15377                 dev_priv->pps_mmio_base = PCH_PPS_BASE;
15378         else if (IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv))
15379                 dev_priv->pps_mmio_base = VLV_PPS_BASE;
15380         else
15381                 dev_priv->pps_mmio_base = PPS_BASE;
15382
15383         intel_pps_unlock_regs_wa(dev_priv);
15384 }
15385
15386 static void intel_setup_outputs(struct drm_device *dev)
15387 {
15388         struct drm_i915_private *dev_priv = to_i915(dev);
15389         struct intel_encoder *encoder;
15390         bool dpd_is_edp = false;
15391
15392         intel_pps_init(dev_priv);
15393
15394         /*
15395          * intel_edp_init_connector() depends on this completing first, to
15396          * prevent the registeration of both eDP and LVDS and the incorrect
15397          * sharing of the PPS.
15398          */
15399         intel_lvds_init(dev);
15400
15401         if (intel_crt_present(dev))
15402                 intel_crt_init(dev);
15403
15404         if (IS_BROXTON(dev)) {
15405                 /*
15406                  * FIXME: Broxton doesn't support port detection via the
15407                  * DDI_BUF_CTL_A or SFUSE_STRAP registers, find another way to
15408                  * detect the ports.
15409                  */
15410                 intel_ddi_init(dev, PORT_A);
15411                 intel_ddi_init(dev, PORT_B);
15412                 intel_ddi_init(dev, PORT_C);
15413
15414                 intel_dsi_init(dev);
15415         } else if (HAS_DDI(dev_priv)) {
15416                 int found;
15417
15418                 /*
15419                  * Haswell uses DDI functions to detect digital outputs.
15420                  * On SKL pre-D0 the strap isn't connected, so we assume
15421                  * it's there.
15422                  */
15423                 found = I915_READ(DDI_BUF_CTL(PORT_A)) & DDI_INIT_DISPLAY_DETECTED;
15424                 /* WaIgnoreDDIAStrap: skl */
15425                 if (found || IS_SKYLAKE(dev) || IS_KABYLAKE(dev))
15426                         intel_ddi_init(dev, PORT_A);
15427
15428                 /* DDI B, C and D detection is indicated by the SFUSE_STRAP
15429                  * register */
15430                 found = I915_READ(SFUSE_STRAP);
15431
15432                 if (found & SFUSE_STRAP_DDIB_DETECTED)
15433                         intel_ddi_init(dev, PORT_B);
15434                 if (found & SFUSE_STRAP_DDIC_DETECTED)
15435                         intel_ddi_init(dev, PORT_C);
15436                 if (found & SFUSE_STRAP_DDID_DETECTED)
15437                         intel_ddi_init(dev, PORT_D);
15438                 /*
15439                  * On SKL we don't have a way to detect DDI-E so we rely on VBT.
15440                  */
15441                 if ((IS_SKYLAKE(dev) || IS_KABYLAKE(dev)) &&
15442                     (dev_priv->vbt.ddi_port_info[PORT_E].supports_dp ||
15443                      dev_priv->vbt.ddi_port_info[PORT_E].supports_dvi ||
15444                      dev_priv->vbt.ddi_port_info[PORT_E].supports_hdmi))
15445                         intel_ddi_init(dev, PORT_E);
15446
15447         } else if (HAS_PCH_SPLIT(dev_priv)) {
15448                 int found;
15449                 dpd_is_edp = intel_dp_is_edp(dev, PORT_D);
15450
15451                 if (has_edp_a(dev))
15452                         intel_dp_init(dev, DP_A, PORT_A);
15453
15454                 if (I915_READ(PCH_HDMIB) & SDVO_DETECTED) {
15455                         /* PCH SDVOB multiplex with HDMIB */
15456                         found = intel_sdvo_init(dev, PCH_SDVOB, PORT_B);
15457                         if (!found)
15458                                 intel_hdmi_init(dev, PCH_HDMIB, PORT_B);
15459                         if (!found && (I915_READ(PCH_DP_B) & DP_DETECTED))
15460                                 intel_dp_init(dev, PCH_DP_B, PORT_B);
15461                 }
15462
15463                 if (I915_READ(PCH_HDMIC) & SDVO_DETECTED)
15464                         intel_hdmi_init(dev, PCH_HDMIC, PORT_C);
15465
15466                 if (!dpd_is_edp && I915_READ(PCH_HDMID) & SDVO_DETECTED)
15467                         intel_hdmi_init(dev, PCH_HDMID, PORT_D);
15468
15469                 if (I915_READ(PCH_DP_C) & DP_DETECTED)
15470                         intel_dp_init(dev, PCH_DP_C, PORT_C);
15471
15472                 if (I915_READ(PCH_DP_D) & DP_DETECTED)
15473                         intel_dp_init(dev, PCH_DP_D, PORT_D);
15474         } else if (IS_VALLEYVIEW(dev) || IS_CHERRYVIEW(dev)) {
15475                 bool has_edp, has_port;
15476
15477                 /*
15478                  * The DP_DETECTED bit is the latched state of the DDC
15479                  * SDA pin at boot. However since eDP doesn't require DDC
15480                  * (no way to plug in a DP->HDMI dongle) the DDC pins for
15481                  * eDP ports may have been muxed to an alternate function.
15482                  * Thus we can't rely on the DP_DETECTED bit alone to detect
15483                  * eDP ports. Consult the VBT as well as DP_DETECTED to
15484                  * detect eDP ports.
15485                  *
15486                  * Sadly the straps seem to be missing sometimes even for HDMI
15487                  * ports (eg. on Voyo V3 - CHT x7-Z8700), so check both strap
15488                  * and VBT for the presence of the port. Additionally we can't
15489                  * trust the port type the VBT declares as we've seen at least
15490                  * HDMI ports that the VBT claim are DP or eDP.
15491                  */
15492                 has_edp = intel_dp_is_edp(dev, PORT_B);
15493                 has_port = intel_bios_is_port_present(dev_priv, PORT_B);
15494                 if (I915_READ(VLV_DP_B) & DP_DETECTED || has_port)
15495                         has_edp &= intel_dp_init(dev, VLV_DP_B, PORT_B);
15496                 if ((I915_READ(VLV_HDMIB) & SDVO_DETECTED || has_port) && !has_edp)
15497                         intel_hdmi_init(dev, VLV_HDMIB, PORT_B);
15498
15499                 has_edp = intel_dp_is_edp(dev, PORT_C);
15500                 has_port = intel_bios_is_port_present(dev_priv, PORT_C);
15501                 if (I915_READ(VLV_DP_C) & DP_DETECTED || has_port)
15502                         has_edp &= intel_dp_init(dev, VLV_DP_C, PORT_C);
15503                 if ((I915_READ(VLV_HDMIC) & SDVO_DETECTED || has_port) && !has_edp)
15504                         intel_hdmi_init(dev, VLV_HDMIC, PORT_C);
15505
15506                 if (IS_CHERRYVIEW(dev)) {
15507                         /*
15508                          * eDP not supported on port D,
15509                          * so no need to worry about it
15510                          */
15511                         has_port = intel_bios_is_port_present(dev_priv, PORT_D);
15512                         if (I915_READ(CHV_DP_D) & DP_DETECTED || has_port)
15513                                 intel_dp_init(dev, CHV_DP_D, PORT_D);
15514                         if (I915_READ(CHV_HDMID) & SDVO_DETECTED || has_port)
15515                                 intel_hdmi_init(dev, CHV_HDMID, PORT_D);
15516                 }
15517
15518                 intel_dsi_init(dev);
15519         } else if (!IS_GEN2(dev) && !IS_PINEVIEW(dev)) {
15520                 bool found = false;
15521
15522                 if (I915_READ(GEN3_SDVOB) & SDVO_DETECTED) {
15523                         DRM_DEBUG_KMS("probing SDVOB\n");
15524                         found = intel_sdvo_init(dev, GEN3_SDVOB, PORT_B);
15525                         if (!found && IS_G4X(dev)) {
15526                                 DRM_DEBUG_KMS("probing HDMI on SDVOB\n");
15527                                 intel_hdmi_init(dev, GEN4_HDMIB, PORT_B);
15528                         }
15529
15530                         if (!found && IS_G4X(dev))
15531                                 intel_dp_init(dev, DP_B, PORT_B);
15532                 }
15533
15534                 /* Before G4X SDVOC doesn't have its own detect register */
15535
15536                 if (I915_READ(GEN3_SDVOB) & SDVO_DETECTED) {
15537                         DRM_DEBUG_KMS("probing SDVOC\n");
15538                         found = intel_sdvo_init(dev, GEN3_SDVOC, PORT_C);
15539                 }
15540
15541                 if (!found && (I915_READ(GEN3_SDVOC) & SDVO_DETECTED)) {
15542
15543                         if (IS_G4X(dev)) {
15544                                 DRM_DEBUG_KMS("probing HDMI on SDVOC\n");
15545                                 intel_hdmi_init(dev, GEN4_HDMIC, PORT_C);
15546                         }
15547                         if (IS_G4X(dev))
15548                                 intel_dp_init(dev, DP_C, PORT_C);
15549                 }
15550
15551                 if (IS_G4X(dev) &&
15552                     (I915_READ(DP_D) & DP_DETECTED))
15553                         intel_dp_init(dev, DP_D, PORT_D);
15554         } else if (IS_GEN2(dev))
15555                 intel_dvo_init(dev);
15556
15557         if (SUPPORTS_TV(dev))
15558                 intel_tv_init(dev);
15559
15560         intel_psr_init(dev);
15561
15562         for_each_intel_encoder(dev, encoder) {
15563                 encoder->base.possible_crtcs = encoder->crtc_mask;
15564                 encoder->base.possible_clones =
15565                         intel_encoder_clones(encoder);
15566         }
15567
15568         intel_init_pch_refclk(dev);
15569
15570         drm_helper_move_panel_connectors_to_head(dev);
15571 }
15572
15573 static void intel_user_framebuffer_destroy(struct drm_framebuffer *fb)
15574 {
15575         struct drm_device *dev = fb->dev;
15576         struct intel_framebuffer *intel_fb = to_intel_framebuffer(fb);
15577
15578         drm_framebuffer_cleanup(fb);
15579         mutex_lock(&dev->struct_mutex);
15580         WARN_ON(!intel_fb->obj->framebuffer_references--);
15581         i915_gem_object_put(intel_fb->obj);
15582         mutex_unlock(&dev->struct_mutex);
15583         kfree(intel_fb);
15584 }
15585
15586 static int intel_user_framebuffer_create_handle(struct drm_framebuffer *fb,
15587                                                 struct drm_file *file,
15588                                                 unsigned int *handle)
15589 {
15590         struct intel_framebuffer *intel_fb = to_intel_framebuffer(fb);
15591         struct drm_i915_gem_object *obj = intel_fb->obj;
15592
15593         if (obj->userptr.mm) {
15594                 DRM_DEBUG("attempting to use a userptr for a framebuffer, denied\n");
15595                 return -EINVAL;
15596         }
15597
15598         return drm_gem_handle_create(file, &obj->base, handle);
15599 }
15600
15601 static int intel_user_framebuffer_dirty(struct drm_framebuffer *fb,
15602                                         struct drm_file *file,
15603                                         unsigned flags, unsigned color,
15604                                         struct drm_clip_rect *clips,
15605                                         unsigned num_clips)
15606 {
15607         struct drm_device *dev = fb->dev;
15608         struct intel_framebuffer *intel_fb = to_intel_framebuffer(fb);
15609         struct drm_i915_gem_object *obj = intel_fb->obj;
15610
15611         mutex_lock(&dev->struct_mutex);
15612         intel_fb_obj_flush(obj, false, ORIGIN_DIRTYFB);
15613         mutex_unlock(&dev->struct_mutex);
15614
15615         return 0;
15616 }
15617
15618 static const struct drm_framebuffer_funcs intel_fb_funcs = {
15619         .destroy = intel_user_framebuffer_destroy,
15620         .create_handle = intel_user_framebuffer_create_handle,
15621         .dirty = intel_user_framebuffer_dirty,
15622 };
15623
15624 static
15625 u32 intel_fb_pitch_limit(struct drm_device *dev, uint64_t fb_modifier,
15626                          uint32_t pixel_format)
15627 {
15628         u32 gen = INTEL_INFO(dev)->gen;
15629
15630         if (gen >= 9) {
15631                 int cpp = drm_format_plane_cpp(pixel_format, 0);
15632
15633                 /* "The stride in bytes must not exceed the of the size of 8K
15634                  *  pixels and 32K bytes."
15635                  */
15636                 return min(8192 * cpp, 32768);
15637         } else if (gen >= 5 && !IS_VALLEYVIEW(dev) && !IS_CHERRYVIEW(dev)) {
15638                 return 32*1024;
15639         } else if (gen >= 4) {
15640                 if (fb_modifier == I915_FORMAT_MOD_X_TILED)
15641                         return 16*1024;
15642                 else
15643                         return 32*1024;
15644         } else if (gen >= 3) {
15645                 if (fb_modifier == I915_FORMAT_MOD_X_TILED)
15646                         return 8*1024;
15647                 else
15648                         return 16*1024;
15649         } else {
15650                 /* XXX DSPC is limited to 4k tiled */
15651                 return 8*1024;
15652         }
15653 }
15654
15655 static int intel_framebuffer_init(struct drm_device *dev,
15656                                   struct intel_framebuffer *intel_fb,
15657                                   struct drm_mode_fb_cmd2 *mode_cmd,
15658                                   struct drm_i915_gem_object *obj)
15659 {
15660         struct drm_i915_private *dev_priv = to_i915(dev);
15661         unsigned int tiling = i915_gem_object_get_tiling(obj);
15662         int ret;
15663         u32 pitch_limit, stride_alignment;
15664         char *format_name;
15665
15666         WARN_ON(!mutex_is_locked(&dev->struct_mutex));
15667
15668         if (mode_cmd->flags & DRM_MODE_FB_MODIFIERS) {
15669                 /*
15670                  * If there's a fence, enforce that
15671                  * the fb modifier and tiling mode match.
15672                  */
15673                 if (tiling != I915_TILING_NONE &&
15674                     tiling != intel_fb_modifier_to_tiling(mode_cmd->modifier[0])) {
15675                         DRM_DEBUG("tiling_mode doesn't match fb modifier\n");
15676                         return -EINVAL;
15677                 }
15678         } else {
15679                 if (tiling == I915_TILING_X) {
15680                         mode_cmd->modifier[0] = I915_FORMAT_MOD_X_TILED;
15681                 } else if (tiling == I915_TILING_Y) {
15682                         DRM_DEBUG("No Y tiling for legacy addfb\n");
15683                         return -EINVAL;
15684                 }
15685         }
15686
15687         /* Passed in modifier sanity checking. */
15688         switch (mode_cmd->modifier[0]) {
15689         case I915_FORMAT_MOD_Y_TILED:
15690         case I915_FORMAT_MOD_Yf_TILED:
15691                 if (INTEL_INFO(dev)->gen < 9) {
15692                         DRM_DEBUG("Unsupported tiling 0x%llx!\n",
15693                                   mode_cmd->modifier[0]);
15694                         return -EINVAL;
15695                 }
15696         case DRM_FORMAT_MOD_NONE:
15697         case I915_FORMAT_MOD_X_TILED:
15698                 break;
15699         default:
15700                 DRM_DEBUG("Unsupported fb modifier 0x%llx!\n",
15701                           mode_cmd->modifier[0]);
15702                 return -EINVAL;
15703         }
15704
15705         /*
15706          * gen2/3 display engine uses the fence if present,
15707          * so the tiling mode must match the fb modifier exactly.
15708          */
15709         if (INTEL_INFO(dev_priv)->gen < 4 &&
15710             tiling != intel_fb_modifier_to_tiling(mode_cmd->modifier[0])) {
15711                 DRM_DEBUG("tiling_mode must match fb modifier exactly on gen2/3\n");
15712                 return -EINVAL;
15713         }
15714
15715         stride_alignment = intel_fb_stride_alignment(dev_priv,
15716                                                      mode_cmd->modifier[0],
15717                                                      mode_cmd->pixel_format);
15718         if (mode_cmd->pitches[0] & (stride_alignment - 1)) {
15719                 DRM_DEBUG("pitch (%d) must be at least %u byte aligned\n",
15720                           mode_cmd->pitches[0], stride_alignment);
15721                 return -EINVAL;
15722         }
15723
15724         pitch_limit = intel_fb_pitch_limit(dev, mode_cmd->modifier[0],
15725                                            mode_cmd->pixel_format);
15726         if (mode_cmd->pitches[0] > pitch_limit) {
15727                 DRM_DEBUG("%s pitch (%u) must be at less than %d\n",
15728                           mode_cmd->modifier[0] != DRM_FORMAT_MOD_NONE ?
15729                           "tiled" : "linear",
15730                           mode_cmd->pitches[0], pitch_limit);
15731                 return -EINVAL;
15732         }
15733
15734         /*
15735          * If there's a fence, enforce that
15736          * the fb pitch and fence stride match.
15737          */
15738         if (tiling != I915_TILING_NONE &&
15739             mode_cmd->pitches[0] != i915_gem_object_get_stride(obj)) {
15740                 DRM_DEBUG("pitch (%d) must match tiling stride (%d)\n",
15741                           mode_cmd->pitches[0],
15742                           i915_gem_object_get_stride(obj));
15743                 return -EINVAL;
15744         }
15745
15746         /* Reject formats not supported by any plane early. */
15747         switch (mode_cmd->pixel_format) {
15748         case DRM_FORMAT_C8:
15749         case DRM_FORMAT_RGB565:
15750         case DRM_FORMAT_XRGB8888:
15751         case DRM_FORMAT_ARGB8888:
15752                 break;
15753         case DRM_FORMAT_XRGB1555:
15754                 if (INTEL_INFO(dev)->gen > 3) {
15755                         format_name = drm_get_format_name(mode_cmd->pixel_format);
15756                         DRM_DEBUG("unsupported pixel format: %s\n", format_name);
15757                         kfree(format_name);
15758                         return -EINVAL;
15759                 }
15760                 break;
15761         case DRM_FORMAT_ABGR8888:
15762                 if (!IS_VALLEYVIEW(dev) && !IS_CHERRYVIEW(dev) &&
15763                     INTEL_INFO(dev)->gen < 9) {
15764                         format_name = drm_get_format_name(mode_cmd->pixel_format);
15765                         DRM_DEBUG("unsupported pixel format: %s\n", format_name);
15766                         kfree(format_name);
15767                         return -EINVAL;
15768                 }
15769                 break;
15770         case DRM_FORMAT_XBGR8888:
15771         case DRM_FORMAT_XRGB2101010:
15772         case DRM_FORMAT_XBGR2101010:
15773                 if (INTEL_INFO(dev)->gen < 4) {
15774                         format_name = drm_get_format_name(mode_cmd->pixel_format);
15775                         DRM_DEBUG("unsupported pixel format: %s\n", format_name);
15776                         kfree(format_name);
15777                         return -EINVAL;
15778                 }
15779                 break;
15780         case DRM_FORMAT_ABGR2101010:
15781                 if (!IS_VALLEYVIEW(dev) && !IS_CHERRYVIEW(dev)) {
15782                         format_name = drm_get_format_name(mode_cmd->pixel_format);
15783                         DRM_DEBUG("unsupported pixel format: %s\n", format_name);
15784                         kfree(format_name);
15785                         return -EINVAL;
15786                 }
15787                 break;
15788         case DRM_FORMAT_YUYV:
15789         case DRM_FORMAT_UYVY:
15790         case DRM_FORMAT_YVYU:
15791         case DRM_FORMAT_VYUY:
15792                 if (INTEL_INFO(dev)->gen < 5) {
15793                         format_name = drm_get_format_name(mode_cmd->pixel_format);
15794                         DRM_DEBUG("unsupported pixel format: %s\n", format_name);
15795                         kfree(format_name);
15796                         return -EINVAL;
15797                 }
15798                 break;
15799         default:
15800                 format_name = drm_get_format_name(mode_cmd->pixel_format);
15801                 DRM_DEBUG("unsupported pixel format: %s\n", format_name);
15802                 kfree(format_name);
15803                 return -EINVAL;
15804         }
15805
15806         /* FIXME need to adjust LINOFF/TILEOFF accordingly. */
15807         if (mode_cmd->offsets[0] != 0)
15808                 return -EINVAL;
15809
15810         drm_helper_mode_fill_fb_struct(&intel_fb->base, mode_cmd);
15811         intel_fb->obj = obj;
15812
15813         ret = intel_fill_fb_info(dev_priv, &intel_fb->base);
15814         if (ret)
15815                 return ret;
15816
15817         ret = drm_framebuffer_init(dev, &intel_fb->base, &intel_fb_funcs);
15818         if (ret) {
15819                 DRM_ERROR("framebuffer init failed %d\n", ret);
15820                 return ret;
15821         }
15822
15823         intel_fb->obj->framebuffer_references++;
15824
15825         return 0;
15826 }
15827
15828 static struct drm_framebuffer *
15829 intel_user_framebuffer_create(struct drm_device *dev,
15830                               struct drm_file *filp,
15831                               const struct drm_mode_fb_cmd2 *user_mode_cmd)
15832 {
15833         struct drm_framebuffer *fb;
15834         struct drm_i915_gem_object *obj;
15835         struct drm_mode_fb_cmd2 mode_cmd = *user_mode_cmd;
15836
15837         obj = i915_gem_object_lookup(filp, mode_cmd.handles[0]);
15838         if (!obj)
15839                 return ERR_PTR(-ENOENT);
15840
15841         fb = intel_framebuffer_create(dev, &mode_cmd, obj);
15842         if (IS_ERR(fb))
15843                 i915_gem_object_put_unlocked(obj);
15844
15845         return fb;
15846 }
15847
15848 static const struct drm_mode_config_funcs intel_mode_funcs = {
15849         .fb_create = intel_user_framebuffer_create,
15850         .output_poll_changed = intel_fbdev_output_poll_changed,
15851         .atomic_check = intel_atomic_check,
15852         .atomic_commit = intel_atomic_commit,
15853         .atomic_state_alloc = intel_atomic_state_alloc,
15854         .atomic_state_clear = intel_atomic_state_clear,
15855 };
15856
15857 /**
15858  * intel_init_display_hooks - initialize the display modesetting hooks
15859  * @dev_priv: device private
15860  */
15861 void intel_init_display_hooks(struct drm_i915_private *dev_priv)
15862 {
15863         if (INTEL_INFO(dev_priv)->gen >= 9) {
15864                 dev_priv->display.get_pipe_config = haswell_get_pipe_config;
15865                 dev_priv->display.get_initial_plane_config =
15866                         skylake_get_initial_plane_config;
15867                 dev_priv->display.crtc_compute_clock =
15868                         haswell_crtc_compute_clock;
15869                 dev_priv->display.crtc_enable = haswell_crtc_enable;
15870                 dev_priv->display.crtc_disable = haswell_crtc_disable;
15871         } else if (HAS_DDI(dev_priv)) {
15872                 dev_priv->display.get_pipe_config = haswell_get_pipe_config;
15873                 dev_priv->display.get_initial_plane_config =
15874                         ironlake_get_initial_plane_config;
15875                 dev_priv->display.crtc_compute_clock =
15876                         haswell_crtc_compute_clock;
15877                 dev_priv->display.crtc_enable = haswell_crtc_enable;
15878                 dev_priv->display.crtc_disable = haswell_crtc_disable;
15879         } else if (HAS_PCH_SPLIT(dev_priv)) {
15880                 dev_priv->display.get_pipe_config = ironlake_get_pipe_config;
15881                 dev_priv->display.get_initial_plane_config =
15882                         ironlake_get_initial_plane_config;
15883                 dev_priv->display.crtc_compute_clock =
15884                         ironlake_crtc_compute_clock;
15885                 dev_priv->display.crtc_enable = ironlake_crtc_enable;
15886                 dev_priv->display.crtc_disable = ironlake_crtc_disable;
15887         } else if (IS_CHERRYVIEW(dev_priv)) {
15888                 dev_priv->display.get_pipe_config = i9xx_get_pipe_config;
15889                 dev_priv->display.get_initial_plane_config =
15890                         i9xx_get_initial_plane_config;
15891                 dev_priv->display.crtc_compute_clock = chv_crtc_compute_clock;
15892                 dev_priv->display.crtc_enable = valleyview_crtc_enable;
15893                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
15894         } else if (IS_VALLEYVIEW(dev_priv)) {
15895                 dev_priv->display.get_pipe_config = i9xx_get_pipe_config;
15896                 dev_priv->display.get_initial_plane_config =
15897                         i9xx_get_initial_plane_config;
15898                 dev_priv->display.crtc_compute_clock = vlv_crtc_compute_clock;
15899                 dev_priv->display.crtc_enable = valleyview_crtc_enable;
15900                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
15901         } else if (IS_G4X(dev_priv)) {
15902                 dev_priv->display.get_pipe_config = i9xx_get_pipe_config;
15903                 dev_priv->display.get_initial_plane_config =
15904                         i9xx_get_initial_plane_config;
15905                 dev_priv->display.crtc_compute_clock = g4x_crtc_compute_clock;
15906                 dev_priv->display.crtc_enable = i9xx_crtc_enable;
15907                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
15908         } else if (IS_PINEVIEW(dev_priv)) {
15909                 dev_priv->display.get_pipe_config = i9xx_get_pipe_config;
15910                 dev_priv->display.get_initial_plane_config =
15911                         i9xx_get_initial_plane_config;
15912                 dev_priv->display.crtc_compute_clock = pnv_crtc_compute_clock;
15913                 dev_priv->display.crtc_enable = i9xx_crtc_enable;
15914                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
15915         } else if (!IS_GEN2(dev_priv)) {
15916                 dev_priv->display.get_pipe_config = i9xx_get_pipe_config;
15917                 dev_priv->display.get_initial_plane_config =
15918                         i9xx_get_initial_plane_config;
15919                 dev_priv->display.crtc_compute_clock = i9xx_crtc_compute_clock;
15920                 dev_priv->display.crtc_enable = i9xx_crtc_enable;
15921                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
15922         } else {
15923                 dev_priv->display.get_pipe_config = i9xx_get_pipe_config;
15924                 dev_priv->display.get_initial_plane_config =
15925                         i9xx_get_initial_plane_config;
15926                 dev_priv->display.crtc_compute_clock = i8xx_crtc_compute_clock;
15927                 dev_priv->display.crtc_enable = i9xx_crtc_enable;
15928                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
15929         }
15930
15931         /* Returns the core display clock speed */
15932         if (IS_SKYLAKE(dev_priv) || IS_KABYLAKE(dev_priv))
15933                 dev_priv->display.get_display_clock_speed =
15934                         skylake_get_display_clock_speed;
15935         else if (IS_BROXTON(dev_priv))
15936                 dev_priv->display.get_display_clock_speed =
15937                         broxton_get_display_clock_speed;
15938         else if (IS_BROADWELL(dev_priv))
15939                 dev_priv->display.get_display_clock_speed =
15940                         broadwell_get_display_clock_speed;
15941         else if (IS_HASWELL(dev_priv))
15942                 dev_priv->display.get_display_clock_speed =
15943                         haswell_get_display_clock_speed;
15944         else if (IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv))
15945                 dev_priv->display.get_display_clock_speed =
15946                         valleyview_get_display_clock_speed;
15947         else if (IS_GEN5(dev_priv))
15948                 dev_priv->display.get_display_clock_speed =
15949                         ilk_get_display_clock_speed;
15950         else if (IS_I945G(dev_priv) || IS_BROADWATER(dev_priv) ||
15951                  IS_GEN6(dev_priv) || IS_IVYBRIDGE(dev_priv))
15952                 dev_priv->display.get_display_clock_speed =
15953                         i945_get_display_clock_speed;
15954         else if (IS_GM45(dev_priv))
15955                 dev_priv->display.get_display_clock_speed =
15956                         gm45_get_display_clock_speed;
15957         else if (IS_CRESTLINE(dev_priv))
15958                 dev_priv->display.get_display_clock_speed =
15959                         i965gm_get_display_clock_speed;
15960         else if (IS_PINEVIEW(dev_priv))
15961                 dev_priv->display.get_display_clock_speed =
15962                         pnv_get_display_clock_speed;
15963         else if (IS_G33(dev_priv) || IS_G4X(dev_priv))
15964                 dev_priv->display.get_display_clock_speed =
15965                         g33_get_display_clock_speed;
15966         else if (IS_I915G(dev_priv))
15967                 dev_priv->display.get_display_clock_speed =
15968                         i915_get_display_clock_speed;
15969         else if (IS_I945GM(dev_priv) || IS_845G(dev_priv))
15970                 dev_priv->display.get_display_clock_speed =
15971                         i9xx_misc_get_display_clock_speed;
15972         else if (IS_I915GM(dev_priv))
15973                 dev_priv->display.get_display_clock_speed =
15974                         i915gm_get_display_clock_speed;
15975         else if (IS_I865G(dev_priv))
15976                 dev_priv->display.get_display_clock_speed =
15977                         i865_get_display_clock_speed;
15978         else if (IS_I85X(dev_priv))
15979                 dev_priv->display.get_display_clock_speed =
15980                         i85x_get_display_clock_speed;
15981         else { /* 830 */
15982                 WARN(!IS_I830(dev_priv), "Unknown platform. Assuming 133 MHz CDCLK\n");
15983                 dev_priv->display.get_display_clock_speed =
15984                         i830_get_display_clock_speed;
15985         }
15986
15987         if (IS_GEN5(dev_priv)) {
15988                 dev_priv->display.fdi_link_train = ironlake_fdi_link_train;
15989         } else if (IS_GEN6(dev_priv)) {
15990                 dev_priv->display.fdi_link_train = gen6_fdi_link_train;
15991         } else if (IS_IVYBRIDGE(dev_priv)) {
15992                 /* FIXME: detect B0+ stepping and use auto training */
15993                 dev_priv->display.fdi_link_train = ivb_manual_fdi_link_train;
15994         } else if (IS_HASWELL(dev_priv) || IS_BROADWELL(dev_priv)) {
15995                 dev_priv->display.fdi_link_train = hsw_fdi_link_train;
15996         }
15997
15998         if (IS_BROADWELL(dev_priv)) {
15999                 dev_priv->display.modeset_commit_cdclk =
16000                         broadwell_modeset_commit_cdclk;
16001                 dev_priv->display.modeset_calc_cdclk =
16002                         broadwell_modeset_calc_cdclk;
16003         } else if (IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv)) {
16004                 dev_priv->display.modeset_commit_cdclk =
16005                         valleyview_modeset_commit_cdclk;
16006                 dev_priv->display.modeset_calc_cdclk =
16007                         valleyview_modeset_calc_cdclk;
16008         } else if (IS_BROXTON(dev_priv)) {
16009                 dev_priv->display.modeset_commit_cdclk =
16010                         bxt_modeset_commit_cdclk;
16011                 dev_priv->display.modeset_calc_cdclk =
16012                         bxt_modeset_calc_cdclk;
16013         } else if (IS_SKYLAKE(dev_priv) || IS_KABYLAKE(dev_priv)) {
16014                 dev_priv->display.modeset_commit_cdclk =
16015                         skl_modeset_commit_cdclk;
16016                 dev_priv->display.modeset_calc_cdclk =
16017                         skl_modeset_calc_cdclk;
16018         }
16019
16020         if (dev_priv->info.gen >= 9)
16021                 dev_priv->display.update_crtcs = skl_update_crtcs;
16022         else
16023                 dev_priv->display.update_crtcs = intel_update_crtcs;
16024
16025         switch (INTEL_INFO(dev_priv)->gen) {
16026         case 2:
16027                 dev_priv->display.queue_flip = intel_gen2_queue_flip;
16028                 break;
16029
16030         case 3:
16031                 dev_priv->display.queue_flip = intel_gen3_queue_flip;
16032                 break;
16033
16034         case 4:
16035         case 5:
16036                 dev_priv->display.queue_flip = intel_gen4_queue_flip;
16037                 break;
16038
16039         case 6:
16040                 dev_priv->display.queue_flip = intel_gen6_queue_flip;
16041                 break;
16042         case 7:
16043         case 8: /* FIXME(BDW): Check that the gen8 RCS flip works. */
16044                 dev_priv->display.queue_flip = intel_gen7_queue_flip;
16045                 break;
16046         case 9:
16047                 /* Drop through - unsupported since execlist only. */
16048         default:
16049                 /* Default just returns -ENODEV to indicate unsupported */
16050                 dev_priv->display.queue_flip = intel_default_queue_flip;
16051         }
16052 }
16053
16054 /*
16055  * Some BIOSes insist on assuming the GPU's pipe A is enabled at suspend,
16056  * resume, or other times.  This quirk makes sure that's the case for
16057  * affected systems.
16058  */
16059 static void quirk_pipea_force(struct drm_device *dev)
16060 {
16061         struct drm_i915_private *dev_priv = to_i915(dev);
16062
16063         dev_priv->quirks |= QUIRK_PIPEA_FORCE;
16064         DRM_INFO("applying pipe a force quirk\n");
16065 }
16066
16067 static void quirk_pipeb_force(struct drm_device *dev)
16068 {
16069         struct drm_i915_private *dev_priv = to_i915(dev);
16070
16071         dev_priv->quirks |= QUIRK_PIPEB_FORCE;
16072         DRM_INFO("applying pipe b force quirk\n");
16073 }
16074
16075 /*
16076  * Some machines (Lenovo U160) do not work with SSC on LVDS for some reason
16077  */
16078 static void quirk_ssc_force_disable(struct drm_device *dev)
16079 {
16080         struct drm_i915_private *dev_priv = to_i915(dev);
16081         dev_priv->quirks |= QUIRK_LVDS_SSC_DISABLE;
16082         DRM_INFO("applying lvds SSC disable quirk\n");
16083 }
16084
16085 /*
16086  * A machine (e.g. Acer Aspire 5734Z) may need to invert the panel backlight
16087  * brightness value
16088  */
16089 static void quirk_invert_brightness(struct drm_device *dev)
16090 {
16091         struct drm_i915_private *dev_priv = to_i915(dev);
16092         dev_priv->quirks |= QUIRK_INVERT_BRIGHTNESS;
16093         DRM_INFO("applying inverted panel brightness quirk\n");
16094 }
16095
16096 /* Some VBT's incorrectly indicate no backlight is present */
16097 static void quirk_backlight_present(struct drm_device *dev)
16098 {
16099         struct drm_i915_private *dev_priv = to_i915(dev);
16100         dev_priv->quirks |= QUIRK_BACKLIGHT_PRESENT;
16101         DRM_INFO("applying backlight present quirk\n");
16102 }
16103
16104 struct intel_quirk {
16105         int device;
16106         int subsystem_vendor;
16107         int subsystem_device;
16108         void (*hook)(struct drm_device *dev);
16109 };
16110
16111 /* For systems that don't have a meaningful PCI subdevice/subvendor ID */
16112 struct intel_dmi_quirk {
16113         void (*hook)(struct drm_device *dev);
16114         const struct dmi_system_id (*dmi_id_list)[];
16115 };
16116
16117 static int intel_dmi_reverse_brightness(const struct dmi_system_id *id)
16118 {
16119         DRM_INFO("Backlight polarity reversed on %s\n", id->ident);
16120         return 1;
16121 }
16122
16123 static const struct intel_dmi_quirk intel_dmi_quirks[] = {
16124         {
16125                 .dmi_id_list = &(const struct dmi_system_id[]) {
16126                         {
16127                                 .callback = intel_dmi_reverse_brightness,
16128                                 .ident = "NCR Corporation",
16129                                 .matches = {DMI_MATCH(DMI_SYS_VENDOR, "NCR Corporation"),
16130                                             DMI_MATCH(DMI_PRODUCT_NAME, ""),
16131                                 },
16132                         },
16133                         { }  /* terminating entry */
16134                 },
16135                 .hook = quirk_invert_brightness,
16136         },
16137 };
16138
16139 static struct intel_quirk intel_quirks[] = {
16140         /* Toshiba Protege R-205, S-209 needs pipe A force quirk */
16141         { 0x2592, 0x1179, 0x0001, quirk_pipea_force },
16142
16143         /* ThinkPad T60 needs pipe A force quirk (bug #16494) */
16144         { 0x2782, 0x17aa, 0x201a, quirk_pipea_force },
16145
16146         /* 830 needs to leave pipe A & dpll A up */
16147         { 0x3577, PCI_ANY_ID, PCI_ANY_ID, quirk_pipea_force },
16148
16149         /* 830 needs to leave pipe B & dpll B up */
16150         { 0x3577, PCI_ANY_ID, PCI_ANY_ID, quirk_pipeb_force },
16151
16152         /* Lenovo U160 cannot use SSC on LVDS */
16153         { 0x0046, 0x17aa, 0x3920, quirk_ssc_force_disable },
16154
16155         /* Sony Vaio Y cannot use SSC on LVDS */
16156         { 0x0046, 0x104d, 0x9076, quirk_ssc_force_disable },
16157
16158         /* Acer Aspire 5734Z must invert backlight brightness */
16159         { 0x2a42, 0x1025, 0x0459, quirk_invert_brightness },
16160
16161         /* Acer/eMachines G725 */
16162         { 0x2a42, 0x1025, 0x0210, quirk_invert_brightness },
16163
16164         /* Acer/eMachines e725 */
16165         { 0x2a42, 0x1025, 0x0212, quirk_invert_brightness },
16166
16167         /* Acer/Packard Bell NCL20 */
16168         { 0x2a42, 0x1025, 0x034b, quirk_invert_brightness },
16169
16170         /* Acer Aspire 4736Z */
16171         { 0x2a42, 0x1025, 0x0260, quirk_invert_brightness },
16172
16173         /* Acer Aspire 5336 */
16174         { 0x2a42, 0x1025, 0x048a, quirk_invert_brightness },
16175
16176         /* Acer C720 and C720P Chromebooks (Celeron 2955U) have backlights */
16177         { 0x0a06, 0x1025, 0x0a11, quirk_backlight_present },
16178
16179         /* Acer C720 Chromebook (Core i3 4005U) */
16180         { 0x0a16, 0x1025, 0x0a11, quirk_backlight_present },
16181
16182         /* Apple Macbook 2,1 (Core 2 T7400) */
16183         { 0x27a2, 0x8086, 0x7270, quirk_backlight_present },
16184
16185         /* Apple Macbook 4,1 */
16186         { 0x2a02, 0x106b, 0x00a1, quirk_backlight_present },
16187
16188         /* Toshiba CB35 Chromebook (Celeron 2955U) */
16189         { 0x0a06, 0x1179, 0x0a88, quirk_backlight_present },
16190
16191         /* HP Chromebook 14 (Celeron 2955U) */
16192         { 0x0a06, 0x103c, 0x21ed, quirk_backlight_present },
16193
16194         /* Dell Chromebook 11 */
16195         { 0x0a06, 0x1028, 0x0a35, quirk_backlight_present },
16196
16197         /* Dell Chromebook 11 (2015 version) */
16198         { 0x0a16, 0x1028, 0x0a35, quirk_backlight_present },
16199 };
16200
16201 static void intel_init_quirks(struct drm_device *dev)
16202 {
16203         struct pci_dev *d = dev->pdev;
16204         int i;
16205
16206         for (i = 0; i < ARRAY_SIZE(intel_quirks); i++) {
16207                 struct intel_quirk *q = &intel_quirks[i];
16208
16209                 if (d->device == q->device &&
16210                     (d->subsystem_vendor == q->subsystem_vendor ||
16211                      q->subsystem_vendor == PCI_ANY_ID) &&
16212                     (d->subsystem_device == q->subsystem_device ||
16213                      q->subsystem_device == PCI_ANY_ID))
16214                         q->hook(dev);
16215         }
16216         for (i = 0; i < ARRAY_SIZE(intel_dmi_quirks); i++) {
16217                 if (dmi_check_system(*intel_dmi_quirks[i].dmi_id_list) != 0)
16218                         intel_dmi_quirks[i].hook(dev);
16219         }
16220 }
16221
16222 /* Disable the VGA plane that we never use */
16223 static void i915_disable_vga(struct drm_device *dev)
16224 {
16225         struct drm_i915_private *dev_priv = to_i915(dev);
16226         struct pci_dev *pdev = dev_priv->drm.pdev;
16227         u8 sr1;
16228         i915_reg_t vga_reg = i915_vgacntrl_reg(dev);
16229
16230         /* WaEnableVGAAccessThroughIOPort:ctg,elk,ilk,snb,ivb,vlv,hsw */
16231         vga_get_uninterruptible(pdev, VGA_RSRC_LEGACY_IO);
16232         outb(SR01, VGA_SR_INDEX);
16233         sr1 = inb(VGA_SR_DATA);
16234         outb(sr1 | 1<<5, VGA_SR_DATA);
16235         vga_put(pdev, VGA_RSRC_LEGACY_IO);
16236         udelay(300);
16237
16238         I915_WRITE(vga_reg, VGA_DISP_DISABLE);
16239         POSTING_READ(vga_reg);
16240 }
16241
16242 void intel_modeset_init_hw(struct drm_device *dev)
16243 {
16244         struct drm_i915_private *dev_priv = to_i915(dev);
16245
16246         intel_update_cdclk(dev);
16247
16248         dev_priv->atomic_cdclk_freq = dev_priv->cdclk_freq;
16249
16250         intel_init_clock_gating(dev);
16251 }
16252
16253 /*
16254  * Calculate what we think the watermarks should be for the state we've read
16255  * out of the hardware and then immediately program those watermarks so that
16256  * we ensure the hardware settings match our internal state.
16257  *
16258  * We can calculate what we think WM's should be by creating a duplicate of the
16259  * current state (which was constructed during hardware readout) and running it
16260  * through the atomic check code to calculate new watermark values in the
16261  * state object.
16262  */
16263 static void sanitize_watermarks(struct drm_device *dev)
16264 {
16265         struct drm_i915_private *dev_priv = to_i915(dev);
16266         struct drm_atomic_state *state;
16267         struct drm_crtc *crtc;
16268         struct drm_crtc_state *cstate;
16269         struct drm_modeset_acquire_ctx ctx;
16270         int ret;
16271         int i;
16272
16273         /* Only supported on platforms that use atomic watermark design */
16274         if (!dev_priv->display.optimize_watermarks)
16275                 return;
16276
16277         /*
16278          * We need to hold connection_mutex before calling duplicate_state so
16279          * that the connector loop is protected.
16280          */
16281         drm_modeset_acquire_init(&ctx, 0);
16282 retry:
16283         ret = drm_modeset_lock_all_ctx(dev, &ctx);
16284         if (ret == -EDEADLK) {
16285                 drm_modeset_backoff(&ctx);
16286                 goto retry;
16287         } else if (WARN_ON(ret)) {
16288                 goto fail;
16289         }
16290
16291         state = drm_atomic_helper_duplicate_state(dev, &ctx);
16292         if (WARN_ON(IS_ERR(state)))
16293                 goto fail;
16294
16295         /*
16296          * Hardware readout is the only time we don't want to calculate
16297          * intermediate watermarks (since we don't trust the current
16298          * watermarks).
16299          */
16300         to_intel_atomic_state(state)->skip_intermediate_wm = true;
16301
16302         ret = intel_atomic_check(dev, state);
16303         if (ret) {
16304                 /*
16305                  * If we fail here, it means that the hardware appears to be
16306                  * programmed in a way that shouldn't be possible, given our
16307                  * understanding of watermark requirements.  This might mean a
16308                  * mistake in the hardware readout code or a mistake in the
16309                  * watermark calculations for a given platform.  Raise a WARN
16310                  * so that this is noticeable.
16311                  *
16312                  * If this actually happens, we'll have to just leave the
16313                  * BIOS-programmed watermarks untouched and hope for the best.
16314                  */
16315                 WARN(true, "Could not determine valid watermarks for inherited state\n");
16316                 goto fail;
16317         }
16318
16319         /* Write calculated watermark values back */
16320         for_each_crtc_in_state(state, crtc, cstate, i) {
16321                 struct intel_crtc_state *cs = to_intel_crtc_state(cstate);
16322
16323                 cs->wm.need_postvbl_update = true;
16324                 dev_priv->display.optimize_watermarks(cs);
16325         }
16326
16327         drm_atomic_state_free(state);
16328 fail:
16329         drm_modeset_drop_locks(&ctx);
16330         drm_modeset_acquire_fini(&ctx);
16331 }
16332
16333 void intel_modeset_init(struct drm_device *dev)
16334 {
16335         struct drm_i915_private *dev_priv = to_i915(dev);
16336         struct i915_ggtt *ggtt = &dev_priv->ggtt;
16337         int sprite, ret;
16338         enum pipe pipe;
16339         struct intel_crtc *crtc;
16340
16341         drm_mode_config_init(dev);
16342
16343         dev->mode_config.min_width = 0;
16344         dev->mode_config.min_height = 0;
16345
16346         dev->mode_config.preferred_depth = 24;
16347         dev->mode_config.prefer_shadow = 1;
16348
16349         dev->mode_config.allow_fb_modifiers = true;
16350
16351         dev->mode_config.funcs = &intel_mode_funcs;
16352
16353         intel_init_quirks(dev);
16354
16355         intel_init_pm(dev);
16356
16357         if (INTEL_INFO(dev)->num_pipes == 0)
16358                 return;
16359
16360         /*
16361          * There may be no VBT; and if the BIOS enabled SSC we can
16362          * just keep using it to avoid unnecessary flicker.  Whereas if the
16363          * BIOS isn't using it, don't assume it will work even if the VBT
16364          * indicates as much.
16365          */
16366         if (HAS_PCH_IBX(dev_priv) || HAS_PCH_CPT(dev_priv)) {
16367                 bool bios_lvds_use_ssc = !!(I915_READ(PCH_DREF_CONTROL) &
16368                                             DREF_SSC1_ENABLE);
16369
16370                 if (dev_priv->vbt.lvds_use_ssc != bios_lvds_use_ssc) {
16371                         DRM_DEBUG_KMS("SSC %sabled by BIOS, overriding VBT which says %sabled\n",
16372                                      bios_lvds_use_ssc ? "en" : "dis",
16373                                      dev_priv->vbt.lvds_use_ssc ? "en" : "dis");
16374                         dev_priv->vbt.lvds_use_ssc = bios_lvds_use_ssc;
16375                 }
16376         }
16377
16378         if (IS_GEN2(dev)) {
16379                 dev->mode_config.max_width = 2048;
16380                 dev->mode_config.max_height = 2048;
16381         } else if (IS_GEN3(dev)) {
16382                 dev->mode_config.max_width = 4096;
16383                 dev->mode_config.max_height = 4096;
16384         } else {
16385                 dev->mode_config.max_width = 8192;
16386                 dev->mode_config.max_height = 8192;
16387         }
16388
16389         if (IS_845G(dev_priv) || IS_I865G(dev_priv)) {
16390                 dev->mode_config.cursor_width = IS_845G(dev_priv) ? 64 : 512;
16391                 dev->mode_config.cursor_height = 1023;
16392         } else if (IS_GEN2(dev)) {
16393                 dev->mode_config.cursor_width = GEN2_CURSOR_WIDTH;
16394                 dev->mode_config.cursor_height = GEN2_CURSOR_HEIGHT;
16395         } else {
16396                 dev->mode_config.cursor_width = MAX_CURSOR_WIDTH;
16397                 dev->mode_config.cursor_height = MAX_CURSOR_HEIGHT;
16398         }
16399
16400         dev->mode_config.fb_base = ggtt->mappable_base;
16401
16402         DRM_DEBUG_KMS("%d display pipe%s available.\n",
16403                       INTEL_INFO(dev)->num_pipes,
16404                       INTEL_INFO(dev)->num_pipes > 1 ? "s" : "");
16405
16406         for_each_pipe(dev_priv, pipe) {
16407                 intel_crtc_init(dev, pipe);
16408                 for_each_sprite(dev_priv, pipe, sprite) {
16409                         ret = intel_plane_init(dev, pipe, sprite);
16410                         if (ret)
16411                                 DRM_DEBUG_KMS("pipe %c sprite %c init failed: %d\n",
16412                                               pipe_name(pipe), sprite_name(pipe, sprite), ret);
16413                 }
16414         }
16415
16416         intel_update_czclk(dev_priv);
16417         intel_update_cdclk(dev);
16418
16419         intel_shared_dpll_init(dev);
16420
16421         if (dev_priv->max_cdclk_freq == 0)
16422                 intel_update_max_cdclk(dev);
16423
16424         /* Just disable it once at startup */
16425         i915_disable_vga(dev);
16426         intel_setup_outputs(dev);
16427
16428         drm_modeset_lock_all(dev);
16429         intel_modeset_setup_hw_state(dev);
16430         drm_modeset_unlock_all(dev);
16431
16432         for_each_intel_crtc(dev, crtc) {
16433                 struct intel_initial_plane_config plane_config = {};
16434
16435                 if (!crtc->active)
16436                         continue;
16437
16438                 /*
16439                  * Note that reserving the BIOS fb up front prevents us
16440                  * from stuffing other stolen allocations like the ring
16441                  * on top.  This prevents some ugliness at boot time, and
16442                  * can even allow for smooth boot transitions if the BIOS
16443                  * fb is large enough for the active pipe configuration.
16444                  */
16445                 dev_priv->display.get_initial_plane_config(crtc,
16446                                                            &plane_config);
16447
16448                 /*
16449                  * If the fb is shared between multiple heads, we'll
16450                  * just get the first one.
16451                  */
16452                 intel_find_initial_plane_obj(crtc, &plane_config);
16453         }
16454
16455         /*
16456          * Make sure hardware watermarks really match the state we read out.
16457          * Note that we need to do this after reconstructing the BIOS fb's
16458          * since the watermark calculation done here will use pstate->fb.
16459          */
16460         sanitize_watermarks(dev);
16461 }
16462
16463 static void intel_enable_pipe_a(struct drm_device *dev)
16464 {
16465         struct intel_connector *connector;
16466         struct drm_connector *crt = NULL;
16467         struct intel_load_detect_pipe load_detect_temp;
16468         struct drm_modeset_acquire_ctx *ctx = dev->mode_config.acquire_ctx;
16469
16470         /* We can't just switch on the pipe A, we need to set things up with a
16471          * proper mode and output configuration. As a gross hack, enable pipe A
16472          * by enabling the load detect pipe once. */
16473         for_each_intel_connector(dev, connector) {
16474                 if (connector->encoder->type == INTEL_OUTPUT_ANALOG) {
16475                         crt = &connector->base;
16476                         break;
16477                 }
16478         }
16479
16480         if (!crt)
16481                 return;
16482
16483         if (intel_get_load_detect_pipe(crt, NULL, &load_detect_temp, ctx))
16484                 intel_release_load_detect_pipe(crt, &load_detect_temp, ctx);
16485 }
16486
16487 static bool
16488 intel_check_plane_mapping(struct intel_crtc *crtc)
16489 {
16490         struct drm_device *dev = crtc->base.dev;
16491         struct drm_i915_private *dev_priv = to_i915(dev);
16492         u32 val;
16493
16494         if (INTEL_INFO(dev)->num_pipes == 1)
16495                 return true;
16496
16497         val = I915_READ(DSPCNTR(!crtc->plane));
16498
16499         if ((val & DISPLAY_PLANE_ENABLE) &&
16500             (!!(val & DISPPLANE_SEL_PIPE_MASK) == crtc->pipe))
16501                 return false;
16502
16503         return true;
16504 }
16505
16506 static bool intel_crtc_has_encoders(struct intel_crtc *crtc)
16507 {
16508         struct drm_device *dev = crtc->base.dev;
16509         struct intel_encoder *encoder;
16510
16511         for_each_encoder_on_crtc(dev, &crtc->base, encoder)
16512                 return true;
16513
16514         return false;
16515 }
16516
16517 static struct intel_connector *intel_encoder_find_connector(struct intel_encoder *encoder)
16518 {
16519         struct drm_device *dev = encoder->base.dev;
16520         struct intel_connector *connector;
16521
16522         for_each_connector_on_encoder(dev, &encoder->base, connector)
16523                 return connector;
16524
16525         return NULL;
16526 }
16527
16528 static bool has_pch_trancoder(struct drm_i915_private *dev_priv,
16529                               enum transcoder pch_transcoder)
16530 {
16531         return HAS_PCH_IBX(dev_priv) || HAS_PCH_CPT(dev_priv) ||
16532                 (HAS_PCH_LPT_H(dev_priv) && pch_transcoder == TRANSCODER_A);
16533 }
16534
16535 static void intel_sanitize_crtc(struct intel_crtc *crtc)
16536 {
16537         struct drm_device *dev = crtc->base.dev;
16538         struct drm_i915_private *dev_priv = to_i915(dev);
16539         enum transcoder cpu_transcoder = crtc->config->cpu_transcoder;
16540
16541         /* Clear any frame start delays used for debugging left by the BIOS */
16542         if (!transcoder_is_dsi(cpu_transcoder)) {
16543                 i915_reg_t reg = PIPECONF(cpu_transcoder);
16544
16545                 I915_WRITE(reg,
16546                            I915_READ(reg) & ~PIPECONF_FRAME_START_DELAY_MASK);
16547         }
16548
16549         /* restore vblank interrupts to correct state */
16550         drm_crtc_vblank_reset(&crtc->base);
16551         if (crtc->active) {
16552                 struct intel_plane *plane;
16553
16554                 drm_crtc_vblank_on(&crtc->base);
16555
16556                 /* Disable everything but the primary plane */
16557                 for_each_intel_plane_on_crtc(dev, crtc, plane) {
16558                         if (plane->base.type == DRM_PLANE_TYPE_PRIMARY)
16559                                 continue;
16560
16561                         plane->disable_plane(&plane->base, &crtc->base);
16562                 }
16563         }
16564
16565         /* We need to sanitize the plane -> pipe mapping first because this will
16566          * disable the crtc (and hence change the state) if it is wrong. Note
16567          * that gen4+ has a fixed plane -> pipe mapping.  */
16568         if (INTEL_INFO(dev)->gen < 4 && !intel_check_plane_mapping(crtc)) {
16569                 bool plane;
16570
16571                 DRM_DEBUG_KMS("[CRTC:%d:%s] wrong plane connection detected!\n",
16572                               crtc->base.base.id, crtc->base.name);
16573
16574                 /* Pipe has the wrong plane attached and the plane is active.
16575                  * Temporarily change the plane mapping and disable everything
16576                  * ...  */
16577                 plane = crtc->plane;
16578                 to_intel_plane_state(crtc->base.primary->state)->base.visible = true;
16579                 crtc->plane = !plane;
16580                 intel_crtc_disable_noatomic(&crtc->base);
16581                 crtc->plane = plane;
16582         }
16583
16584         if (dev_priv->quirks & QUIRK_PIPEA_FORCE &&
16585             crtc->pipe == PIPE_A && !crtc->active) {
16586                 /* BIOS forgot to enable pipe A, this mostly happens after
16587                  * resume. Force-enable the pipe to fix this, the update_dpms
16588                  * call below we restore the pipe to the right state, but leave
16589                  * the required bits on. */
16590                 intel_enable_pipe_a(dev);
16591         }
16592
16593         /* Adjust the state of the output pipe according to whether we
16594          * have active connectors/encoders. */
16595         if (crtc->active && !intel_crtc_has_encoders(crtc))
16596                 intel_crtc_disable_noatomic(&crtc->base);
16597
16598         if (crtc->active || HAS_GMCH_DISPLAY(dev_priv)) {
16599                 /*
16600                  * We start out with underrun reporting disabled to avoid races.
16601                  * For correct bookkeeping mark this on active crtcs.
16602                  *
16603                  * Also on gmch platforms we dont have any hardware bits to
16604                  * disable the underrun reporting. Which means we need to start
16605                  * out with underrun reporting disabled also on inactive pipes,
16606                  * since otherwise we'll complain about the garbage we read when
16607                  * e.g. coming up after runtime pm.
16608                  *
16609                  * No protection against concurrent access is required - at
16610                  * worst a fifo underrun happens which also sets this to false.
16611                  */
16612                 crtc->cpu_fifo_underrun_disabled = true;
16613                 /*
16614                  * We track the PCH trancoder underrun reporting state
16615                  * within the crtc. With crtc for pipe A housing the underrun
16616                  * reporting state for PCH transcoder A, crtc for pipe B housing
16617                  * it for PCH transcoder B, etc. LPT-H has only PCH transcoder A,
16618                  * and marking underrun reporting as disabled for the non-existing
16619                  * PCH transcoders B and C would prevent enabling the south
16620                  * error interrupt (see cpt_can_enable_serr_int()).
16621                  */
16622                 if (has_pch_trancoder(dev_priv, (enum transcoder)crtc->pipe))
16623                         crtc->pch_fifo_underrun_disabled = true;
16624         }
16625 }
16626
16627 static void intel_sanitize_encoder(struct intel_encoder *encoder)
16628 {
16629         struct intel_connector *connector;
16630
16631         /* We need to check both for a crtc link (meaning that the
16632          * encoder is active and trying to read from a pipe) and the
16633          * pipe itself being active. */
16634         bool has_active_crtc = encoder->base.crtc &&
16635                 to_intel_crtc(encoder->base.crtc)->active;
16636
16637         connector = intel_encoder_find_connector(encoder);
16638         if (connector && !has_active_crtc) {
16639                 DRM_DEBUG_KMS("[ENCODER:%d:%s] has active connectors but no active pipe!\n",
16640                               encoder->base.base.id,
16641                               encoder->base.name);
16642
16643                 /* Connector is active, but has no active pipe. This is
16644                  * fallout from our resume register restoring. Disable
16645                  * the encoder manually again. */
16646                 if (encoder->base.crtc) {
16647                         struct drm_crtc_state *crtc_state = encoder->base.crtc->state;
16648
16649                         DRM_DEBUG_KMS("[ENCODER:%d:%s] manually disabled\n",
16650                                       encoder->base.base.id,
16651                                       encoder->base.name);
16652                         encoder->disable(encoder, to_intel_crtc_state(crtc_state), connector->base.state);
16653                         if (encoder->post_disable)
16654                                 encoder->post_disable(encoder, to_intel_crtc_state(crtc_state), connector->base.state);
16655                 }
16656                 encoder->base.crtc = NULL;
16657
16658                 /* Inconsistent output/port/pipe state happens presumably due to
16659                  * a bug in one of the get_hw_state functions. Or someplace else
16660                  * in our code, like the register restore mess on resume. Clamp
16661                  * things to off as a safer default. */
16662
16663                 connector->base.dpms = DRM_MODE_DPMS_OFF;
16664                 connector->base.encoder = NULL;
16665         }
16666         /* Enabled encoders without active connectors will be fixed in
16667          * the crtc fixup. */
16668 }
16669
16670 void i915_redisable_vga_power_on(struct drm_device *dev)
16671 {
16672         struct drm_i915_private *dev_priv = to_i915(dev);
16673         i915_reg_t vga_reg = i915_vgacntrl_reg(dev);
16674
16675         if (!(I915_READ(vga_reg) & VGA_DISP_DISABLE)) {
16676                 DRM_DEBUG_KMS("Something enabled VGA plane, disabling it\n");
16677                 i915_disable_vga(dev);
16678         }
16679 }
16680
16681 void i915_redisable_vga(struct drm_device *dev)
16682 {
16683         struct drm_i915_private *dev_priv = to_i915(dev);
16684
16685         /* This function can be called both from intel_modeset_setup_hw_state or
16686          * at a very early point in our resume sequence, where the power well
16687          * structures are not yet restored. Since this function is at a very
16688          * paranoid "someone might have enabled VGA while we were not looking"
16689          * level, just check if the power well is enabled instead of trying to
16690          * follow the "don't touch the power well if we don't need it" policy
16691          * the rest of the driver uses. */
16692         if (!intel_display_power_get_if_enabled(dev_priv, POWER_DOMAIN_VGA))
16693                 return;
16694
16695         i915_redisable_vga_power_on(dev);
16696
16697         intel_display_power_put(dev_priv, POWER_DOMAIN_VGA);
16698 }
16699
16700 static bool primary_get_hw_state(struct intel_plane *plane)
16701 {
16702         struct drm_i915_private *dev_priv = to_i915(plane->base.dev);
16703
16704         return I915_READ(DSPCNTR(plane->plane)) & DISPLAY_PLANE_ENABLE;
16705 }
16706
16707 /* FIXME read out full plane state for all planes */
16708 static void readout_plane_state(struct intel_crtc *crtc)
16709 {
16710         struct drm_plane *primary = crtc->base.primary;
16711         struct intel_plane_state *plane_state =
16712                 to_intel_plane_state(primary->state);
16713
16714         plane_state->base.visible = crtc->active &&
16715                 primary_get_hw_state(to_intel_plane(primary));
16716
16717         if (plane_state->base.visible)
16718                 crtc->base.state->plane_mask |= 1 << drm_plane_index(primary);
16719 }
16720
16721 static void intel_modeset_readout_hw_state(struct drm_device *dev)
16722 {
16723         struct drm_i915_private *dev_priv = to_i915(dev);
16724         enum pipe pipe;
16725         struct intel_crtc *crtc;
16726         struct intel_encoder *encoder;
16727         struct intel_connector *connector;
16728         int i;
16729
16730         dev_priv->active_crtcs = 0;
16731
16732         for_each_intel_crtc(dev, crtc) {
16733                 struct intel_crtc_state *crtc_state = crtc->config;
16734                 int pixclk = 0;
16735
16736                 __drm_atomic_helper_crtc_destroy_state(&crtc_state->base);
16737                 memset(crtc_state, 0, sizeof(*crtc_state));
16738                 crtc_state->base.crtc = &crtc->base;
16739
16740                 crtc_state->base.active = crtc_state->base.enable =
16741                         dev_priv->display.get_pipe_config(crtc, crtc_state);
16742
16743                 crtc->base.enabled = crtc_state->base.enable;
16744                 crtc->active = crtc_state->base.active;
16745
16746                 if (crtc_state->base.active) {
16747                         dev_priv->active_crtcs |= 1 << crtc->pipe;
16748
16749                         if (INTEL_GEN(dev_priv) >= 9 || IS_BROADWELL(dev_priv))
16750                                 pixclk = ilk_pipe_pixel_rate(crtc_state);
16751                         else if (IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv))
16752                                 pixclk = crtc_state->base.adjusted_mode.crtc_clock;
16753                         else
16754                                 WARN_ON(dev_priv->display.modeset_calc_cdclk);
16755
16756                         /* pixel rate mustn't exceed 95% of cdclk with IPS on BDW */
16757                         if (IS_BROADWELL(dev_priv) && crtc_state->ips_enabled)
16758                                 pixclk = DIV_ROUND_UP(pixclk * 100, 95);
16759                 }
16760
16761                 dev_priv->min_pixclk[crtc->pipe] = pixclk;
16762
16763                 readout_plane_state(crtc);
16764
16765                 DRM_DEBUG_KMS("[CRTC:%d:%s] hw state readout: %s\n",
16766                               crtc->base.base.id, crtc->base.name,
16767                               crtc->active ? "enabled" : "disabled");
16768         }
16769
16770         for (i = 0; i < dev_priv->num_shared_dpll; i++) {
16771                 struct intel_shared_dpll *pll = &dev_priv->shared_dplls[i];
16772
16773                 pll->on = pll->funcs.get_hw_state(dev_priv, pll,
16774                                                   &pll->config.hw_state);
16775                 pll->config.crtc_mask = 0;
16776                 for_each_intel_crtc(dev, crtc) {
16777                         if (crtc->active && crtc->config->shared_dpll == pll)
16778                                 pll->config.crtc_mask |= 1 << crtc->pipe;
16779                 }
16780                 pll->active_mask = pll->config.crtc_mask;
16781
16782                 DRM_DEBUG_KMS("%s hw state readout: crtc_mask 0x%08x, on %i\n",
16783                               pll->name, pll->config.crtc_mask, pll->on);
16784         }
16785
16786         for_each_intel_encoder(dev, encoder) {
16787                 pipe = 0;
16788
16789                 if (encoder->get_hw_state(encoder, &pipe)) {
16790                         crtc = to_intel_crtc(dev_priv->pipe_to_crtc_mapping[pipe]);
16791                         encoder->base.crtc = &crtc->base;
16792                         crtc->config->output_types |= 1 << encoder->type;
16793                         encoder->get_config(encoder, crtc->config);
16794                 } else {
16795                         encoder->base.crtc = NULL;
16796                 }
16797
16798                 DRM_DEBUG_KMS("[ENCODER:%d:%s] hw state readout: %s, pipe %c\n",
16799                               encoder->base.base.id,
16800                               encoder->base.name,
16801                               encoder->base.crtc ? "enabled" : "disabled",
16802                               pipe_name(pipe));
16803         }
16804
16805         for_each_intel_connector(dev, connector) {
16806                 if (connector->get_hw_state(connector)) {
16807                         connector->base.dpms = DRM_MODE_DPMS_ON;
16808
16809                         encoder = connector->encoder;
16810                         connector->base.encoder = &encoder->base;
16811
16812                         if (encoder->base.crtc &&
16813                             encoder->base.crtc->state->active) {
16814                                 /*
16815                                  * This has to be done during hardware readout
16816                                  * because anything calling .crtc_disable may
16817                                  * rely on the connector_mask being accurate.
16818                                  */
16819                                 encoder->base.crtc->state->connector_mask |=
16820                                         1 << drm_connector_index(&connector->base);
16821                                 encoder->base.crtc->state->encoder_mask |=
16822                                         1 << drm_encoder_index(&encoder->base);
16823                         }
16824
16825                 } else {
16826                         connector->base.dpms = DRM_MODE_DPMS_OFF;
16827                         connector->base.encoder = NULL;
16828                 }
16829                 DRM_DEBUG_KMS("[CONNECTOR:%d:%s] hw state readout: %s\n",
16830                               connector->base.base.id,
16831                               connector->base.name,
16832                               connector->base.encoder ? "enabled" : "disabled");
16833         }
16834
16835         for_each_intel_crtc(dev, crtc) {
16836                 crtc->base.hwmode = crtc->config->base.adjusted_mode;
16837
16838                 memset(&crtc->base.mode, 0, sizeof(crtc->base.mode));
16839                 if (crtc->base.state->active) {
16840                         intel_mode_from_pipe_config(&crtc->base.mode, crtc->config);
16841                         intel_mode_from_pipe_config(&crtc->base.state->adjusted_mode, crtc->config);
16842                         WARN_ON(drm_atomic_set_mode_for_crtc(crtc->base.state, &crtc->base.mode));
16843
16844                         /*
16845                          * The initial mode needs to be set in order to keep
16846                          * the atomic core happy. It wants a valid mode if the
16847                          * crtc's enabled, so we do the above call.
16848                          *
16849                          * At this point some state updated by the connectors
16850                          * in their ->detect() callback has not run yet, so
16851                          * no recalculation can be done yet.
16852                          *
16853                          * Even if we could do a recalculation and modeset
16854                          * right now it would cause a double modeset if
16855                          * fbdev or userspace chooses a different initial mode.
16856                          *
16857                          * If that happens, someone indicated they wanted a
16858                          * mode change, which means it's safe to do a full
16859                          * recalculation.
16860                          */
16861                         crtc->base.state->mode.private_flags = I915_MODE_FLAG_INHERITED;
16862
16863                         drm_calc_timestamping_constants(&crtc->base, &crtc->base.hwmode);
16864                         update_scanline_offset(crtc);
16865                 }
16866
16867                 intel_pipe_config_sanity_check(dev_priv, crtc->config);
16868         }
16869 }
16870
16871 /* Scan out the current hw modeset state,
16872  * and sanitizes it to the current state
16873  */
16874 static void
16875 intel_modeset_setup_hw_state(struct drm_device *dev)
16876 {
16877         struct drm_i915_private *dev_priv = to_i915(dev);
16878         enum pipe pipe;
16879         struct intel_crtc *crtc;
16880         struct intel_encoder *encoder;
16881         int i;
16882
16883         intel_modeset_readout_hw_state(dev);
16884
16885         /* HW state is read out, now we need to sanitize this mess. */
16886         for_each_intel_encoder(dev, encoder) {
16887                 intel_sanitize_encoder(encoder);
16888         }
16889
16890         for_each_pipe(dev_priv, pipe) {
16891                 crtc = to_intel_crtc(dev_priv->pipe_to_crtc_mapping[pipe]);
16892                 intel_sanitize_crtc(crtc);
16893                 intel_dump_pipe_config(crtc, crtc->config,
16894                                        "[setup_hw_state]");
16895         }
16896
16897         intel_modeset_update_connector_atomic_state(dev);
16898
16899         for (i = 0; i < dev_priv->num_shared_dpll; i++) {
16900                 struct intel_shared_dpll *pll = &dev_priv->shared_dplls[i];
16901
16902                 if (!pll->on || pll->active_mask)
16903                         continue;
16904
16905                 DRM_DEBUG_KMS("%s enabled but not in use, disabling\n", pll->name);
16906
16907                 pll->funcs.disable(dev_priv, pll);
16908                 pll->on = false;
16909         }
16910
16911         if (IS_VALLEYVIEW(dev) || IS_CHERRYVIEW(dev))
16912                 vlv_wm_get_hw_state(dev);
16913         else if (IS_GEN9(dev))
16914                 skl_wm_get_hw_state(dev);
16915         else if (HAS_PCH_SPLIT(dev_priv))
16916                 ilk_wm_get_hw_state(dev);
16917
16918         for_each_intel_crtc(dev, crtc) {
16919                 unsigned long put_domains;
16920
16921                 put_domains = modeset_get_crtc_power_domains(&crtc->base, crtc->config);
16922                 if (WARN_ON(put_domains))
16923                         modeset_put_power_domains(dev_priv, put_domains);
16924         }
16925         intel_display_set_init_power(dev_priv, false);
16926
16927         intel_fbc_init_pipe_state(dev_priv);
16928 }
16929
16930 void intel_display_resume(struct drm_device *dev)
16931 {
16932         struct drm_i915_private *dev_priv = to_i915(dev);
16933         struct drm_atomic_state *state = dev_priv->modeset_restore_state;
16934         struct drm_modeset_acquire_ctx ctx;
16935         int ret;
16936
16937         dev_priv->modeset_restore_state = NULL;
16938         if (state)
16939                 state->acquire_ctx = &ctx;
16940
16941         /*
16942          * This is a cludge because with real atomic modeset mode_config.mutex
16943          * won't be taken. Unfortunately some probed state like
16944          * audio_codec_enable is still protected by mode_config.mutex, so lock
16945          * it here for now.
16946          */
16947         mutex_lock(&dev->mode_config.mutex);
16948         drm_modeset_acquire_init(&ctx, 0);
16949
16950         while (1) {
16951                 ret = drm_modeset_lock_all_ctx(dev, &ctx);
16952                 if (ret != -EDEADLK)
16953                         break;
16954
16955                 drm_modeset_backoff(&ctx);
16956         }
16957
16958         if (!ret)
16959                 ret = __intel_display_resume(dev, state);
16960
16961         drm_modeset_drop_locks(&ctx);
16962         drm_modeset_acquire_fini(&ctx);
16963         mutex_unlock(&dev->mode_config.mutex);
16964
16965         if (ret) {
16966                 DRM_ERROR("Restoring old state failed with %i\n", ret);
16967                 drm_atomic_state_free(state);
16968         }
16969 }
16970
16971 void intel_modeset_gem_init(struct drm_device *dev)
16972 {
16973         struct drm_i915_private *dev_priv = to_i915(dev);
16974         struct drm_crtc *c;
16975         struct drm_i915_gem_object *obj;
16976
16977         intel_init_gt_powersave(dev_priv);
16978
16979         intel_modeset_init_hw(dev);
16980
16981         intel_setup_overlay(dev_priv);
16982
16983         /*
16984          * Make sure any fbs we allocated at startup are properly
16985          * pinned & fenced.  When we do the allocation it's too early
16986          * for this.
16987          */
16988         for_each_crtc(dev, c) {
16989                 struct i915_vma *vma;
16990
16991                 obj = intel_fb_obj(c->primary->fb);
16992                 if (obj == NULL)
16993                         continue;
16994
16995                 mutex_lock(&dev->struct_mutex);
16996                 vma = intel_pin_and_fence_fb_obj(c->primary->fb,
16997                                                  c->primary->state->rotation);
16998                 mutex_unlock(&dev->struct_mutex);
16999                 if (IS_ERR(vma)) {
17000                         DRM_ERROR("failed to pin boot fb on pipe %d\n",
17001                                   to_intel_crtc(c)->pipe);
17002                         drm_framebuffer_unreference(c->primary->fb);
17003                         c->primary->fb = NULL;
17004                         c->primary->crtc = c->primary->state->crtc = NULL;
17005                         update_state_fb(c->primary);
17006                         c->state->plane_mask &= ~(1 << drm_plane_index(c->primary));
17007                 }
17008         }
17009 }
17010
17011 int intel_connector_register(struct drm_connector *connector)
17012 {
17013         struct intel_connector *intel_connector = to_intel_connector(connector);
17014         int ret;
17015
17016         ret = intel_backlight_device_register(intel_connector);
17017         if (ret)
17018                 goto err;
17019
17020         return 0;
17021
17022 err:
17023         return ret;
17024 }
17025
17026 void intel_connector_unregister(struct drm_connector *connector)
17027 {
17028         struct intel_connector *intel_connector = to_intel_connector(connector);
17029
17030         intel_backlight_device_unregister(intel_connector);
17031         intel_panel_destroy_backlight(connector);
17032 }
17033
17034 void intel_modeset_cleanup(struct drm_device *dev)
17035 {
17036         struct drm_i915_private *dev_priv = to_i915(dev);
17037
17038         intel_disable_gt_powersave(dev_priv);
17039
17040         /*
17041          * Interrupts and polling as the first thing to avoid creating havoc.
17042          * Too much stuff here (turning of connectors, ...) would
17043          * experience fancy races otherwise.
17044          */
17045         intel_irq_uninstall(dev_priv);
17046
17047         /*
17048          * Due to the hpd irq storm handling the hotplug work can re-arm the
17049          * poll handlers. Hence disable polling after hpd handling is shut down.
17050          */
17051         drm_kms_helper_poll_fini(dev);
17052
17053         intel_unregister_dsm_handler();
17054
17055         intel_fbc_global_disable(dev_priv);
17056
17057         /* flush any delayed tasks or pending work */
17058         flush_scheduled_work();
17059
17060         drm_mode_config_cleanup(dev);
17061
17062         intel_cleanup_overlay(dev_priv);
17063
17064         intel_cleanup_gt_powersave(dev_priv);
17065
17066         intel_teardown_gmbus(dev);
17067 }
17068
17069 void intel_connector_attach_encoder(struct intel_connector *connector,
17070                                     struct intel_encoder *encoder)
17071 {
17072         connector->encoder = encoder;
17073         drm_mode_connector_attach_encoder(&connector->base,
17074                                           &encoder->base);
17075 }
17076
17077 /*
17078  * set vga decode state - true == enable VGA decode
17079  */
17080 int intel_modeset_vga_set_state(struct drm_device *dev, bool state)
17081 {
17082         struct drm_i915_private *dev_priv = to_i915(dev);
17083         unsigned reg = INTEL_INFO(dev)->gen >= 6 ? SNB_GMCH_CTRL : INTEL_GMCH_CTRL;
17084         u16 gmch_ctrl;
17085
17086         if (pci_read_config_word(dev_priv->bridge_dev, reg, &gmch_ctrl)) {
17087                 DRM_ERROR("failed to read control word\n");
17088                 return -EIO;
17089         }
17090
17091         if (!!(gmch_ctrl & INTEL_GMCH_VGA_DISABLE) == !state)
17092                 return 0;
17093
17094         if (state)
17095                 gmch_ctrl &= ~INTEL_GMCH_VGA_DISABLE;
17096         else
17097                 gmch_ctrl |= INTEL_GMCH_VGA_DISABLE;
17098
17099         if (pci_write_config_word(dev_priv->bridge_dev, reg, gmch_ctrl)) {
17100                 DRM_ERROR("failed to write control word\n");
17101                 return -EIO;
17102         }
17103
17104         return 0;
17105 }
17106
17107 #if IS_ENABLED(CONFIG_DRM_I915_CAPTURE_ERROR)
17108
17109 struct intel_display_error_state {
17110
17111         u32 power_well_driver;
17112
17113         int num_transcoders;
17114
17115         struct intel_cursor_error_state {
17116                 u32 control;
17117                 u32 position;
17118                 u32 base;
17119                 u32 size;
17120         } cursor[I915_MAX_PIPES];
17121
17122         struct intel_pipe_error_state {
17123                 bool power_domain_on;
17124                 u32 source;
17125                 u32 stat;
17126         } pipe[I915_MAX_PIPES];
17127
17128         struct intel_plane_error_state {
17129                 u32 control;
17130                 u32 stride;
17131                 u32 size;
17132                 u32 pos;
17133                 u32 addr;
17134                 u32 surface;
17135                 u32 tile_offset;
17136         } plane[I915_MAX_PIPES];
17137
17138         struct intel_transcoder_error_state {
17139                 bool power_domain_on;
17140                 enum transcoder cpu_transcoder;
17141
17142                 u32 conf;
17143
17144                 u32 htotal;
17145                 u32 hblank;
17146                 u32 hsync;
17147                 u32 vtotal;
17148                 u32 vblank;
17149                 u32 vsync;
17150         } transcoder[4];
17151 };
17152
17153 struct intel_display_error_state *
17154 intel_display_capture_error_state(struct drm_i915_private *dev_priv)
17155 {
17156         struct intel_display_error_state *error;
17157         int transcoders[] = {
17158                 TRANSCODER_A,
17159                 TRANSCODER_B,
17160                 TRANSCODER_C,
17161                 TRANSCODER_EDP,
17162         };
17163         int i;
17164
17165         if (INTEL_INFO(dev_priv)->num_pipes == 0)
17166                 return NULL;
17167
17168         error = kzalloc(sizeof(*error), GFP_ATOMIC);
17169         if (error == NULL)
17170                 return NULL;
17171
17172         if (IS_HASWELL(dev_priv) || IS_BROADWELL(dev_priv))
17173                 error->power_well_driver = I915_READ(HSW_PWR_WELL_DRIVER);
17174
17175         for_each_pipe(dev_priv, i) {
17176                 error->pipe[i].power_domain_on =
17177                         __intel_display_power_is_enabled(dev_priv,
17178                                                          POWER_DOMAIN_PIPE(i));
17179                 if (!error->pipe[i].power_domain_on)
17180                         continue;
17181
17182                 error->cursor[i].control = I915_READ(CURCNTR(i));
17183                 error->cursor[i].position = I915_READ(CURPOS(i));
17184                 error->cursor[i].base = I915_READ(CURBASE(i));
17185
17186                 error->plane[i].control = I915_READ(DSPCNTR(i));
17187                 error->plane[i].stride = I915_READ(DSPSTRIDE(i));
17188                 if (INTEL_GEN(dev_priv) <= 3) {
17189                         error->plane[i].size = I915_READ(DSPSIZE(i));
17190                         error->plane[i].pos = I915_READ(DSPPOS(i));
17191                 }
17192                 if (INTEL_GEN(dev_priv) <= 7 && !IS_HASWELL(dev_priv))
17193                         error->plane[i].addr = I915_READ(DSPADDR(i));
17194                 if (INTEL_GEN(dev_priv) >= 4) {
17195                         error->plane[i].surface = I915_READ(DSPSURF(i));
17196                         error->plane[i].tile_offset = I915_READ(DSPTILEOFF(i));
17197                 }
17198
17199                 error->pipe[i].source = I915_READ(PIPESRC(i));
17200
17201                 if (HAS_GMCH_DISPLAY(dev_priv))
17202                         error->pipe[i].stat = I915_READ(PIPESTAT(i));
17203         }
17204
17205         /* Note: this does not include DSI transcoders. */
17206         error->num_transcoders = INTEL_INFO(dev_priv)->num_pipes;
17207         if (HAS_DDI(dev_priv))
17208                 error->num_transcoders++; /* Account for eDP. */
17209
17210         for (i = 0; i < error->num_transcoders; i++) {
17211                 enum transcoder cpu_transcoder = transcoders[i];
17212
17213                 error->transcoder[i].power_domain_on =
17214                         __intel_display_power_is_enabled(dev_priv,
17215                                 POWER_DOMAIN_TRANSCODER(cpu_transcoder));
17216                 if (!error->transcoder[i].power_domain_on)
17217                         continue;
17218
17219                 error->transcoder[i].cpu_transcoder = cpu_transcoder;
17220
17221                 error->transcoder[i].conf = I915_READ(PIPECONF(cpu_transcoder));
17222                 error->transcoder[i].htotal = I915_READ(HTOTAL(cpu_transcoder));
17223                 error->transcoder[i].hblank = I915_READ(HBLANK(cpu_transcoder));
17224                 error->transcoder[i].hsync = I915_READ(HSYNC(cpu_transcoder));
17225                 error->transcoder[i].vtotal = I915_READ(VTOTAL(cpu_transcoder));
17226                 error->transcoder[i].vblank = I915_READ(VBLANK(cpu_transcoder));
17227                 error->transcoder[i].vsync = I915_READ(VSYNC(cpu_transcoder));
17228         }
17229
17230         return error;
17231 }
17232
17233 #define err_printf(e, ...) i915_error_printf(e, __VA_ARGS__)
17234
17235 void
17236 intel_display_print_error_state(struct drm_i915_error_state_buf *m,
17237                                 struct drm_device *dev,
17238                                 struct intel_display_error_state *error)
17239 {
17240         struct drm_i915_private *dev_priv = to_i915(dev);
17241         int i;
17242
17243         if (!error)
17244                 return;
17245
17246         err_printf(m, "Num Pipes: %d\n", INTEL_INFO(dev)->num_pipes);
17247         if (IS_HASWELL(dev) || IS_BROADWELL(dev))
17248                 err_printf(m, "PWR_WELL_CTL2: %08x\n",
17249                            error->power_well_driver);
17250         for_each_pipe(dev_priv, i) {
17251                 err_printf(m, "Pipe [%d]:\n", i);
17252                 err_printf(m, "  Power: %s\n",
17253                            onoff(error->pipe[i].power_domain_on));
17254                 err_printf(m, "  SRC: %08x\n", error->pipe[i].source);
17255                 err_printf(m, "  STAT: %08x\n", error->pipe[i].stat);
17256
17257                 err_printf(m, "Plane [%d]:\n", i);
17258                 err_printf(m, "  CNTR: %08x\n", error->plane[i].control);
17259                 err_printf(m, "  STRIDE: %08x\n", error->plane[i].stride);
17260                 if (INTEL_INFO(dev)->gen <= 3) {
17261                         err_printf(m, "  SIZE: %08x\n", error->plane[i].size);
17262                         err_printf(m, "  POS: %08x\n", error->plane[i].pos);
17263                 }
17264                 if (INTEL_INFO(dev)->gen <= 7 && !IS_HASWELL(dev))
17265                         err_printf(m, "  ADDR: %08x\n", error->plane[i].addr);
17266                 if (INTEL_INFO(dev)->gen >= 4) {
17267                         err_printf(m, "  SURF: %08x\n", error->plane[i].surface);
17268                         err_printf(m, "  TILEOFF: %08x\n", error->plane[i].tile_offset);
17269                 }
17270
17271                 err_printf(m, "Cursor [%d]:\n", i);
17272                 err_printf(m, "  CNTR: %08x\n", error->cursor[i].control);
17273                 err_printf(m, "  POS: %08x\n", error->cursor[i].position);
17274                 err_printf(m, "  BASE: %08x\n", error->cursor[i].base);
17275         }
17276
17277         for (i = 0; i < error->num_transcoders; i++) {
17278                 err_printf(m, "CPU transcoder: %s\n",
17279                            transcoder_name(error->transcoder[i].cpu_transcoder));
17280                 err_printf(m, "  Power: %s\n",
17281                            onoff(error->transcoder[i].power_domain_on));
17282                 err_printf(m, "  CONF: %08x\n", error->transcoder[i].conf);
17283                 err_printf(m, "  HTOTAL: %08x\n", error->transcoder[i].htotal);
17284                 err_printf(m, "  HBLANK: %08x\n", error->transcoder[i].hblank);
17285                 err_printf(m, "  HSYNC: %08x\n", error->transcoder[i].hsync);
17286                 err_printf(m, "  VTOTAL: %08x\n", error->transcoder[i].vtotal);
17287                 err_printf(m, "  VBLANK: %08x\n", error->transcoder[i].vblank);
17288                 err_printf(m, "  VSYNC: %08x\n", error->transcoder[i].vsync);
17289         }
17290 }
17291
17292 #endif