27b4b880dfcd28ac6c2e927fc0e143f47e0f96f4
[linux-2.6-block.git] / drivers / gpu / drm / i915 / intel_display.c
1 /*
2  * Copyright © 2006-2007 Intel Corporation
3  *
4  * Permission is hereby granted, free of charge, to any person obtaining a
5  * copy of this software and associated documentation files (the "Software"),
6  * to deal in the Software without restriction, including without limitation
7  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
8  * and/or sell copies of the Software, and to permit persons to whom the
9  * Software is furnished to do so, subject to the following conditions:
10  *
11  * The above copyright notice and this permission notice (including the next
12  * paragraph) shall be included in all copies or substantial portions of the
13  * Software.
14  *
15  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
18  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
20  * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
21  * DEALINGS IN THE SOFTWARE.
22  *
23  * Authors:
24  *      Eric Anholt <eric@anholt.net>
25  */
26
27 #include <linux/dmi.h>
28 #include <linux/module.h>
29 #include <linux/input.h>
30 #include <linux/i2c.h>
31 #include <linux/kernel.h>
32 #include <linux/slab.h>
33 #include <linux/vgaarb.h>
34 #include <drm/drm_edid.h>
35 #include <drm/drmP.h>
36 #include "intel_drv.h"
37 #include <drm/i915_drm.h>
38 #include "i915_drv.h"
39 #include "intel_dsi.h"
40 #include "i915_trace.h"
41 #include <drm/drm_atomic.h>
42 #include <drm/drm_atomic_helper.h>
43 #include <drm/drm_dp_helper.h>
44 #include <drm/drm_crtc_helper.h>
45 #include <drm/drm_plane_helper.h>
46 #include <drm/drm_rect.h>
47 #include <linux/dma_remapping.h>
48 #include <linux/reservation.h>
49 #include <linux/dma-buf.h>
50
51 /* Primary plane formats for gen <= 3 */
52 static const uint32_t i8xx_primary_formats[] = {
53         DRM_FORMAT_C8,
54         DRM_FORMAT_RGB565,
55         DRM_FORMAT_XRGB1555,
56         DRM_FORMAT_XRGB8888,
57 };
58
59 /* Primary plane formats for gen >= 4 */
60 static const uint32_t i965_primary_formats[] = {
61         DRM_FORMAT_C8,
62         DRM_FORMAT_RGB565,
63         DRM_FORMAT_XRGB8888,
64         DRM_FORMAT_XBGR8888,
65         DRM_FORMAT_XRGB2101010,
66         DRM_FORMAT_XBGR2101010,
67 };
68
69 static const uint32_t skl_primary_formats[] = {
70         DRM_FORMAT_C8,
71         DRM_FORMAT_RGB565,
72         DRM_FORMAT_XRGB8888,
73         DRM_FORMAT_XBGR8888,
74         DRM_FORMAT_ARGB8888,
75         DRM_FORMAT_ABGR8888,
76         DRM_FORMAT_XRGB2101010,
77         DRM_FORMAT_XBGR2101010,
78         DRM_FORMAT_YUYV,
79         DRM_FORMAT_YVYU,
80         DRM_FORMAT_UYVY,
81         DRM_FORMAT_VYUY,
82 };
83
84 /* Cursor formats */
85 static const uint32_t intel_cursor_formats[] = {
86         DRM_FORMAT_ARGB8888,
87 };
88
89 static void i9xx_crtc_clock_get(struct intel_crtc *crtc,
90                                 struct intel_crtc_state *pipe_config);
91 static void ironlake_pch_clock_get(struct intel_crtc *crtc,
92                                    struct intel_crtc_state *pipe_config);
93
94 static int intel_framebuffer_init(struct drm_device *dev,
95                                   struct intel_framebuffer *ifb,
96                                   struct drm_mode_fb_cmd2 *mode_cmd,
97                                   struct drm_i915_gem_object *obj);
98 static void i9xx_set_pipeconf(struct intel_crtc *intel_crtc);
99 static void intel_set_pipe_timings(struct intel_crtc *intel_crtc);
100 static void intel_set_pipe_src_size(struct intel_crtc *intel_crtc);
101 static void intel_cpu_transcoder_set_m_n(struct intel_crtc *crtc,
102                                          struct intel_link_m_n *m_n,
103                                          struct intel_link_m_n *m2_n2);
104 static void ironlake_set_pipeconf(struct drm_crtc *crtc);
105 static void haswell_set_pipeconf(struct drm_crtc *crtc);
106 static void haswell_set_pipemisc(struct drm_crtc *crtc);
107 static void vlv_prepare_pll(struct intel_crtc *crtc,
108                             const struct intel_crtc_state *pipe_config);
109 static void chv_prepare_pll(struct intel_crtc *crtc,
110                             const struct intel_crtc_state *pipe_config);
111 static void skl_init_scalers(struct drm_device *dev, struct intel_crtc *intel_crtc,
112         struct intel_crtc_state *crtc_state);
113 static void skylake_pfit_enable(struct intel_crtc *crtc);
114 static void ironlake_pfit_disable(struct intel_crtc *crtc, bool force);
115 static void ironlake_pfit_enable(struct intel_crtc *crtc);
116 static void intel_modeset_setup_hw_state(struct drm_device *dev);
117 static void intel_pre_disable_primary_noatomic(struct drm_crtc *crtc);
118 static int ilk_max_pixel_rate(struct drm_atomic_state *state);
119 static void intel_modeset_verify_crtc(struct drm_crtc *crtc,
120                                       struct drm_crtc_state *old_state,
121                                       struct drm_crtc_state *new_state);
122
123 struct intel_limit {
124         struct {
125                 int min, max;
126         } dot, vco, n, m, m1, m2, p, p1;
127
128         struct {
129                 int dot_limit;
130                 int p2_slow, p2_fast;
131         } p2;
132 };
133
134 /* returns HPLL frequency in kHz */
135 static int valleyview_get_vco(struct drm_i915_private *dev_priv)
136 {
137         int hpll_freq, vco_freq[] = { 800, 1600, 2000, 2400 };
138
139         /* Obtain SKU information */
140         mutex_lock(&dev_priv->sb_lock);
141         hpll_freq = vlv_cck_read(dev_priv, CCK_FUSE_REG) &
142                 CCK_FUSE_HPLL_FREQ_MASK;
143         mutex_unlock(&dev_priv->sb_lock);
144
145         return vco_freq[hpll_freq] * 1000;
146 }
147
148 int vlv_get_cck_clock(struct drm_i915_private *dev_priv,
149                       const char *name, u32 reg, int ref_freq)
150 {
151         u32 val;
152         int divider;
153
154         mutex_lock(&dev_priv->sb_lock);
155         val = vlv_cck_read(dev_priv, reg);
156         mutex_unlock(&dev_priv->sb_lock);
157
158         divider = val & CCK_FREQUENCY_VALUES;
159
160         WARN((val & CCK_FREQUENCY_STATUS) !=
161              (divider << CCK_FREQUENCY_STATUS_SHIFT),
162              "%s change in progress\n", name);
163
164         return DIV_ROUND_CLOSEST(ref_freq << 1, divider + 1);
165 }
166
167 static int vlv_get_cck_clock_hpll(struct drm_i915_private *dev_priv,
168                                   const char *name, u32 reg)
169 {
170         if (dev_priv->hpll_freq == 0)
171                 dev_priv->hpll_freq = valleyview_get_vco(dev_priv);
172
173         return vlv_get_cck_clock(dev_priv, name, reg,
174                                  dev_priv->hpll_freq);
175 }
176
177 static int
178 intel_pch_rawclk(struct drm_i915_private *dev_priv)
179 {
180         return (I915_READ(PCH_RAWCLK_FREQ) & RAWCLK_FREQ_MASK) * 1000;
181 }
182
183 static int
184 intel_vlv_hrawclk(struct drm_i915_private *dev_priv)
185 {
186         /* RAWCLK_FREQ_VLV register updated from power well code */
187         return vlv_get_cck_clock_hpll(dev_priv, "hrawclk",
188                                       CCK_DISPLAY_REF_CLOCK_CONTROL);
189 }
190
191 static int
192 intel_g4x_hrawclk(struct drm_i915_private *dev_priv)
193 {
194         uint32_t clkcfg;
195
196         /* hrawclock is 1/4 the FSB frequency */
197         clkcfg = I915_READ(CLKCFG);
198         switch (clkcfg & CLKCFG_FSB_MASK) {
199         case CLKCFG_FSB_400:
200                 return 100000;
201         case CLKCFG_FSB_533:
202                 return 133333;
203         case CLKCFG_FSB_667:
204                 return 166667;
205         case CLKCFG_FSB_800:
206                 return 200000;
207         case CLKCFG_FSB_1067:
208                 return 266667;
209         case CLKCFG_FSB_1333:
210                 return 333333;
211         /* these two are just a guess; one of them might be right */
212         case CLKCFG_FSB_1600:
213         case CLKCFG_FSB_1600_ALT:
214                 return 400000;
215         default:
216                 return 133333;
217         }
218 }
219
220 void intel_update_rawclk(struct drm_i915_private *dev_priv)
221 {
222         if (HAS_PCH_SPLIT(dev_priv))
223                 dev_priv->rawclk_freq = intel_pch_rawclk(dev_priv);
224         else if (IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv))
225                 dev_priv->rawclk_freq = intel_vlv_hrawclk(dev_priv);
226         else if (IS_G4X(dev_priv) || IS_PINEVIEW(dev_priv))
227                 dev_priv->rawclk_freq = intel_g4x_hrawclk(dev_priv);
228         else
229                 return; /* no rawclk on other platforms, or no need to know it */
230
231         DRM_DEBUG_DRIVER("rawclk rate: %d kHz\n", dev_priv->rawclk_freq);
232 }
233
234 static void intel_update_czclk(struct drm_i915_private *dev_priv)
235 {
236         if (!(IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv)))
237                 return;
238
239         dev_priv->czclk_freq = vlv_get_cck_clock_hpll(dev_priv, "czclk",
240                                                       CCK_CZ_CLOCK_CONTROL);
241
242         DRM_DEBUG_DRIVER("CZ clock rate: %d kHz\n", dev_priv->czclk_freq);
243 }
244
245 static inline u32 /* units of 100MHz */
246 intel_fdi_link_freq(struct drm_i915_private *dev_priv,
247                     const struct intel_crtc_state *pipe_config)
248 {
249         if (HAS_DDI(dev_priv))
250                 return pipe_config->port_clock; /* SPLL */
251         else if (IS_GEN5(dev_priv))
252                 return ((I915_READ(FDI_PLL_BIOS_0) & FDI_PLL_FB_CLOCK_MASK) + 2) * 10000;
253         else
254                 return 270000;
255 }
256
257 static const struct intel_limit intel_limits_i8xx_dac = {
258         .dot = { .min = 25000, .max = 350000 },
259         .vco = { .min = 908000, .max = 1512000 },
260         .n = { .min = 2, .max = 16 },
261         .m = { .min = 96, .max = 140 },
262         .m1 = { .min = 18, .max = 26 },
263         .m2 = { .min = 6, .max = 16 },
264         .p = { .min = 4, .max = 128 },
265         .p1 = { .min = 2, .max = 33 },
266         .p2 = { .dot_limit = 165000,
267                 .p2_slow = 4, .p2_fast = 2 },
268 };
269
270 static const struct intel_limit intel_limits_i8xx_dvo = {
271         .dot = { .min = 25000, .max = 350000 },
272         .vco = { .min = 908000, .max = 1512000 },
273         .n = { .min = 2, .max = 16 },
274         .m = { .min = 96, .max = 140 },
275         .m1 = { .min = 18, .max = 26 },
276         .m2 = { .min = 6, .max = 16 },
277         .p = { .min = 4, .max = 128 },
278         .p1 = { .min = 2, .max = 33 },
279         .p2 = { .dot_limit = 165000,
280                 .p2_slow = 4, .p2_fast = 4 },
281 };
282
283 static const struct intel_limit intel_limits_i8xx_lvds = {
284         .dot = { .min = 25000, .max = 350000 },
285         .vco = { .min = 908000, .max = 1512000 },
286         .n = { .min = 2, .max = 16 },
287         .m = { .min = 96, .max = 140 },
288         .m1 = { .min = 18, .max = 26 },
289         .m2 = { .min = 6, .max = 16 },
290         .p = { .min = 4, .max = 128 },
291         .p1 = { .min = 1, .max = 6 },
292         .p2 = { .dot_limit = 165000,
293                 .p2_slow = 14, .p2_fast = 7 },
294 };
295
296 static const struct intel_limit intel_limits_i9xx_sdvo = {
297         .dot = { .min = 20000, .max = 400000 },
298         .vco = { .min = 1400000, .max = 2800000 },
299         .n = { .min = 1, .max = 6 },
300         .m = { .min = 70, .max = 120 },
301         .m1 = { .min = 8, .max = 18 },
302         .m2 = { .min = 3, .max = 7 },
303         .p = { .min = 5, .max = 80 },
304         .p1 = { .min = 1, .max = 8 },
305         .p2 = { .dot_limit = 200000,
306                 .p2_slow = 10, .p2_fast = 5 },
307 };
308
309 static const struct intel_limit intel_limits_i9xx_lvds = {
310         .dot = { .min = 20000, .max = 400000 },
311         .vco = { .min = 1400000, .max = 2800000 },
312         .n = { .min = 1, .max = 6 },
313         .m = { .min = 70, .max = 120 },
314         .m1 = { .min = 8, .max = 18 },
315         .m2 = { .min = 3, .max = 7 },
316         .p = { .min = 7, .max = 98 },
317         .p1 = { .min = 1, .max = 8 },
318         .p2 = { .dot_limit = 112000,
319                 .p2_slow = 14, .p2_fast = 7 },
320 };
321
322
323 static const struct intel_limit intel_limits_g4x_sdvo = {
324         .dot = { .min = 25000, .max = 270000 },
325         .vco = { .min = 1750000, .max = 3500000},
326         .n = { .min = 1, .max = 4 },
327         .m = { .min = 104, .max = 138 },
328         .m1 = { .min = 17, .max = 23 },
329         .m2 = { .min = 5, .max = 11 },
330         .p = { .min = 10, .max = 30 },
331         .p1 = { .min = 1, .max = 3},
332         .p2 = { .dot_limit = 270000,
333                 .p2_slow = 10,
334                 .p2_fast = 10
335         },
336 };
337
338 static const struct intel_limit intel_limits_g4x_hdmi = {
339         .dot = { .min = 22000, .max = 400000 },
340         .vco = { .min = 1750000, .max = 3500000},
341         .n = { .min = 1, .max = 4 },
342         .m = { .min = 104, .max = 138 },
343         .m1 = { .min = 16, .max = 23 },
344         .m2 = { .min = 5, .max = 11 },
345         .p = { .min = 5, .max = 80 },
346         .p1 = { .min = 1, .max = 8},
347         .p2 = { .dot_limit = 165000,
348                 .p2_slow = 10, .p2_fast = 5 },
349 };
350
351 static const struct intel_limit intel_limits_g4x_single_channel_lvds = {
352         .dot = { .min = 20000, .max = 115000 },
353         .vco = { .min = 1750000, .max = 3500000 },
354         .n = { .min = 1, .max = 3 },
355         .m = { .min = 104, .max = 138 },
356         .m1 = { .min = 17, .max = 23 },
357         .m2 = { .min = 5, .max = 11 },
358         .p = { .min = 28, .max = 112 },
359         .p1 = { .min = 2, .max = 8 },
360         .p2 = { .dot_limit = 0,
361                 .p2_slow = 14, .p2_fast = 14
362         },
363 };
364
365 static const struct intel_limit intel_limits_g4x_dual_channel_lvds = {
366         .dot = { .min = 80000, .max = 224000 },
367         .vco = { .min = 1750000, .max = 3500000 },
368         .n = { .min = 1, .max = 3 },
369         .m = { .min = 104, .max = 138 },
370         .m1 = { .min = 17, .max = 23 },
371         .m2 = { .min = 5, .max = 11 },
372         .p = { .min = 14, .max = 42 },
373         .p1 = { .min = 2, .max = 6 },
374         .p2 = { .dot_limit = 0,
375                 .p2_slow = 7, .p2_fast = 7
376         },
377 };
378
379 static const struct intel_limit intel_limits_pineview_sdvo = {
380         .dot = { .min = 20000, .max = 400000},
381         .vco = { .min = 1700000, .max = 3500000 },
382         /* Pineview's Ncounter is a ring counter */
383         .n = { .min = 3, .max = 6 },
384         .m = { .min = 2, .max = 256 },
385         /* Pineview only has one combined m divider, which we treat as m2. */
386         .m1 = { .min = 0, .max = 0 },
387         .m2 = { .min = 0, .max = 254 },
388         .p = { .min = 5, .max = 80 },
389         .p1 = { .min = 1, .max = 8 },
390         .p2 = { .dot_limit = 200000,
391                 .p2_slow = 10, .p2_fast = 5 },
392 };
393
394 static const struct intel_limit intel_limits_pineview_lvds = {
395         .dot = { .min = 20000, .max = 400000 },
396         .vco = { .min = 1700000, .max = 3500000 },
397         .n = { .min = 3, .max = 6 },
398         .m = { .min = 2, .max = 256 },
399         .m1 = { .min = 0, .max = 0 },
400         .m2 = { .min = 0, .max = 254 },
401         .p = { .min = 7, .max = 112 },
402         .p1 = { .min = 1, .max = 8 },
403         .p2 = { .dot_limit = 112000,
404                 .p2_slow = 14, .p2_fast = 14 },
405 };
406
407 /* Ironlake / Sandybridge
408  *
409  * We calculate clock using (register_value + 2) for N/M1/M2, so here
410  * the range value for them is (actual_value - 2).
411  */
412 static const struct intel_limit intel_limits_ironlake_dac = {
413         .dot = { .min = 25000, .max = 350000 },
414         .vco = { .min = 1760000, .max = 3510000 },
415         .n = { .min = 1, .max = 5 },
416         .m = { .min = 79, .max = 127 },
417         .m1 = { .min = 12, .max = 22 },
418         .m2 = { .min = 5, .max = 9 },
419         .p = { .min = 5, .max = 80 },
420         .p1 = { .min = 1, .max = 8 },
421         .p2 = { .dot_limit = 225000,
422                 .p2_slow = 10, .p2_fast = 5 },
423 };
424
425 static const struct intel_limit intel_limits_ironlake_single_lvds = {
426         .dot = { .min = 25000, .max = 350000 },
427         .vco = { .min = 1760000, .max = 3510000 },
428         .n = { .min = 1, .max = 3 },
429         .m = { .min = 79, .max = 118 },
430         .m1 = { .min = 12, .max = 22 },
431         .m2 = { .min = 5, .max = 9 },
432         .p = { .min = 28, .max = 112 },
433         .p1 = { .min = 2, .max = 8 },
434         .p2 = { .dot_limit = 225000,
435                 .p2_slow = 14, .p2_fast = 14 },
436 };
437
438 static const struct intel_limit intel_limits_ironlake_dual_lvds = {
439         .dot = { .min = 25000, .max = 350000 },
440         .vco = { .min = 1760000, .max = 3510000 },
441         .n = { .min = 1, .max = 3 },
442         .m = { .min = 79, .max = 127 },
443         .m1 = { .min = 12, .max = 22 },
444         .m2 = { .min = 5, .max = 9 },
445         .p = { .min = 14, .max = 56 },
446         .p1 = { .min = 2, .max = 8 },
447         .p2 = { .dot_limit = 225000,
448                 .p2_slow = 7, .p2_fast = 7 },
449 };
450
451 /* LVDS 100mhz refclk limits. */
452 static const struct intel_limit intel_limits_ironlake_single_lvds_100m = {
453         .dot = { .min = 25000, .max = 350000 },
454         .vco = { .min = 1760000, .max = 3510000 },
455         .n = { .min = 1, .max = 2 },
456         .m = { .min = 79, .max = 126 },
457         .m1 = { .min = 12, .max = 22 },
458         .m2 = { .min = 5, .max = 9 },
459         .p = { .min = 28, .max = 112 },
460         .p1 = { .min = 2, .max = 8 },
461         .p2 = { .dot_limit = 225000,
462                 .p2_slow = 14, .p2_fast = 14 },
463 };
464
465 static const struct intel_limit intel_limits_ironlake_dual_lvds_100m = {
466         .dot = { .min = 25000, .max = 350000 },
467         .vco = { .min = 1760000, .max = 3510000 },
468         .n = { .min = 1, .max = 3 },
469         .m = { .min = 79, .max = 126 },
470         .m1 = { .min = 12, .max = 22 },
471         .m2 = { .min = 5, .max = 9 },
472         .p = { .min = 14, .max = 42 },
473         .p1 = { .min = 2, .max = 6 },
474         .p2 = { .dot_limit = 225000,
475                 .p2_slow = 7, .p2_fast = 7 },
476 };
477
478 static const struct intel_limit intel_limits_vlv = {
479          /*
480           * These are the data rate limits (measured in fast clocks)
481           * since those are the strictest limits we have. The fast
482           * clock and actual rate limits are more relaxed, so checking
483           * them would make no difference.
484           */
485         .dot = { .min = 25000 * 5, .max = 270000 * 5 },
486         .vco = { .min = 4000000, .max = 6000000 },
487         .n = { .min = 1, .max = 7 },
488         .m1 = { .min = 2, .max = 3 },
489         .m2 = { .min = 11, .max = 156 },
490         .p1 = { .min = 2, .max = 3 },
491         .p2 = { .p2_slow = 2, .p2_fast = 20 }, /* slow=min, fast=max */
492 };
493
494 static const struct intel_limit intel_limits_chv = {
495         /*
496          * These are the data rate limits (measured in fast clocks)
497          * since those are the strictest limits we have.  The fast
498          * clock and actual rate limits are more relaxed, so checking
499          * them would make no difference.
500          */
501         .dot = { .min = 25000 * 5, .max = 540000 * 5},
502         .vco = { .min = 4800000, .max = 6480000 },
503         .n = { .min = 1, .max = 1 },
504         .m1 = { .min = 2, .max = 2 },
505         .m2 = { .min = 24 << 22, .max = 175 << 22 },
506         .p1 = { .min = 2, .max = 4 },
507         .p2 = { .p2_slow = 1, .p2_fast = 14 },
508 };
509
510 static const struct intel_limit intel_limits_bxt = {
511         /* FIXME: find real dot limits */
512         .dot = { .min = 0, .max = INT_MAX },
513         .vco = { .min = 4800000, .max = 6700000 },
514         .n = { .min = 1, .max = 1 },
515         .m1 = { .min = 2, .max = 2 },
516         /* FIXME: find real m2 limits */
517         .m2 = { .min = 2 << 22, .max = 255 << 22 },
518         .p1 = { .min = 2, .max = 4 },
519         .p2 = { .p2_slow = 1, .p2_fast = 20 },
520 };
521
522 static bool
523 needs_modeset(struct drm_crtc_state *state)
524 {
525         return drm_atomic_crtc_needs_modeset(state);
526 }
527
528 /**
529  * Returns whether any output on the specified pipe is of the specified type
530  */
531 bool intel_pipe_has_type(struct intel_crtc *crtc, enum intel_output_type type)
532 {
533         struct drm_device *dev = crtc->base.dev;
534         struct intel_encoder *encoder;
535
536         for_each_encoder_on_crtc(dev, &crtc->base, encoder)
537                 if (encoder->type == type)
538                         return true;
539
540         return false;
541 }
542
543 /**
544  * Returns whether any output on the specified pipe will have the specified
545  * type after a staged modeset is complete, i.e., the same as
546  * intel_pipe_has_type() but looking at encoder->new_crtc instead of
547  * encoder->crtc.
548  */
549 static bool intel_pipe_will_have_type(const struct intel_crtc_state *crtc_state,
550                                       int type)
551 {
552         struct drm_atomic_state *state = crtc_state->base.state;
553         struct drm_connector *connector;
554         struct drm_connector_state *connector_state;
555         struct intel_encoder *encoder;
556         int i, num_connectors = 0;
557
558         for_each_connector_in_state(state, connector, connector_state, i) {
559                 if (connector_state->crtc != crtc_state->base.crtc)
560                         continue;
561
562                 num_connectors++;
563
564                 encoder = to_intel_encoder(connector_state->best_encoder);
565                 if (encoder->type == type)
566                         return true;
567         }
568
569         WARN_ON(num_connectors == 0);
570
571         return false;
572 }
573
574 /*
575  * Platform specific helpers to calculate the port PLL loopback- (clock.m),
576  * and post-divider (clock.p) values, pre- (clock.vco) and post-divided fast
577  * (clock.dot) clock rates. This fast dot clock is fed to the port's IO logic.
578  * The helpers' return value is the rate of the clock that is fed to the
579  * display engine's pipe which can be the above fast dot clock rate or a
580  * divided-down version of it.
581  */
582 /* m1 is reserved as 0 in Pineview, n is a ring counter */
583 static int pnv_calc_dpll_params(int refclk, struct dpll *clock)
584 {
585         clock->m = clock->m2 + 2;
586         clock->p = clock->p1 * clock->p2;
587         if (WARN_ON(clock->n == 0 || clock->p == 0))
588                 return 0;
589         clock->vco = DIV_ROUND_CLOSEST(refclk * clock->m, clock->n);
590         clock->dot = DIV_ROUND_CLOSEST(clock->vco, clock->p);
591
592         return clock->dot;
593 }
594
595 static uint32_t i9xx_dpll_compute_m(struct dpll *dpll)
596 {
597         return 5 * (dpll->m1 + 2) + (dpll->m2 + 2);
598 }
599
600 static int i9xx_calc_dpll_params(int refclk, struct dpll *clock)
601 {
602         clock->m = i9xx_dpll_compute_m(clock);
603         clock->p = clock->p1 * clock->p2;
604         if (WARN_ON(clock->n + 2 == 0 || clock->p == 0))
605                 return 0;
606         clock->vco = DIV_ROUND_CLOSEST(refclk * clock->m, clock->n + 2);
607         clock->dot = DIV_ROUND_CLOSEST(clock->vco, clock->p);
608
609         return clock->dot;
610 }
611
612 static int vlv_calc_dpll_params(int refclk, struct dpll *clock)
613 {
614         clock->m = clock->m1 * clock->m2;
615         clock->p = clock->p1 * clock->p2;
616         if (WARN_ON(clock->n == 0 || clock->p == 0))
617                 return 0;
618         clock->vco = DIV_ROUND_CLOSEST(refclk * clock->m, clock->n);
619         clock->dot = DIV_ROUND_CLOSEST(clock->vco, clock->p);
620
621         return clock->dot / 5;
622 }
623
624 int chv_calc_dpll_params(int refclk, struct dpll *clock)
625 {
626         clock->m = clock->m1 * clock->m2;
627         clock->p = clock->p1 * clock->p2;
628         if (WARN_ON(clock->n == 0 || clock->p == 0))
629                 return 0;
630         clock->vco = DIV_ROUND_CLOSEST_ULL((uint64_t)refclk * clock->m,
631                         clock->n << 22);
632         clock->dot = DIV_ROUND_CLOSEST(clock->vco, clock->p);
633
634         return clock->dot / 5;
635 }
636
637 #define INTELPllInvalid(s)   do { /* DRM_DEBUG(s); */ return false; } while (0)
638 /**
639  * Returns whether the given set of divisors are valid for a given refclk with
640  * the given connectors.
641  */
642
643 static bool intel_PLL_is_valid(struct drm_device *dev,
644                                const struct intel_limit *limit,
645                                const struct dpll *clock)
646 {
647         if (clock->n   < limit->n.min   || limit->n.max   < clock->n)
648                 INTELPllInvalid("n out of range\n");
649         if (clock->p1  < limit->p1.min  || limit->p1.max  < clock->p1)
650                 INTELPllInvalid("p1 out of range\n");
651         if (clock->m2  < limit->m2.min  || limit->m2.max  < clock->m2)
652                 INTELPllInvalid("m2 out of range\n");
653         if (clock->m1  < limit->m1.min  || limit->m1.max  < clock->m1)
654                 INTELPllInvalid("m1 out of range\n");
655
656         if (!IS_PINEVIEW(dev) && !IS_VALLEYVIEW(dev) &&
657             !IS_CHERRYVIEW(dev) && !IS_BROXTON(dev))
658                 if (clock->m1 <= clock->m2)
659                         INTELPllInvalid("m1 <= m2\n");
660
661         if (!IS_VALLEYVIEW(dev) && !IS_CHERRYVIEW(dev) && !IS_BROXTON(dev)) {
662                 if (clock->p < limit->p.min || limit->p.max < clock->p)
663                         INTELPllInvalid("p out of range\n");
664                 if (clock->m < limit->m.min || limit->m.max < clock->m)
665                         INTELPllInvalid("m out of range\n");
666         }
667
668         if (clock->vco < limit->vco.min || limit->vco.max < clock->vco)
669                 INTELPllInvalid("vco out of range\n");
670         /* XXX: We may need to be checking "Dot clock" depending on the multiplier,
671          * connector, etc., rather than just a single range.
672          */
673         if (clock->dot < limit->dot.min || limit->dot.max < clock->dot)
674                 INTELPllInvalid("dot out of range\n");
675
676         return true;
677 }
678
679 static int
680 i9xx_select_p2_div(const struct intel_limit *limit,
681                    const struct intel_crtc_state *crtc_state,
682                    int target)
683 {
684         struct drm_device *dev = crtc_state->base.crtc->dev;
685
686         if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_LVDS)) {
687                 /*
688                  * For LVDS just rely on its current settings for dual-channel.
689                  * We haven't figured out how to reliably set up different
690                  * single/dual channel state, if we even can.
691                  */
692                 if (intel_is_dual_link_lvds(dev))
693                         return limit->p2.p2_fast;
694                 else
695                         return limit->p2.p2_slow;
696         } else {
697                 if (target < limit->p2.dot_limit)
698                         return limit->p2.p2_slow;
699                 else
700                         return limit->p2.p2_fast;
701         }
702 }
703
704 /*
705  * Returns a set of divisors for the desired target clock with the given
706  * refclk, or FALSE.  The returned values represent the clock equation:
707  * reflck * (5 * (m1 + 2) + (m2 + 2)) / (n + 2) / p1 / p2.
708  *
709  * Target and reference clocks are specified in kHz.
710  *
711  * If match_clock is provided, then best_clock P divider must match the P
712  * divider from @match_clock used for LVDS downclocking.
713  */
714 static bool
715 i9xx_find_best_dpll(const struct intel_limit *limit,
716                     struct intel_crtc_state *crtc_state,
717                     int target, int refclk, struct dpll *match_clock,
718                     struct dpll *best_clock)
719 {
720         struct drm_device *dev = crtc_state->base.crtc->dev;
721         struct dpll clock;
722         int err = target;
723
724         memset(best_clock, 0, sizeof(*best_clock));
725
726         clock.p2 = i9xx_select_p2_div(limit, crtc_state, target);
727
728         for (clock.m1 = limit->m1.min; clock.m1 <= limit->m1.max;
729              clock.m1++) {
730                 for (clock.m2 = limit->m2.min;
731                      clock.m2 <= limit->m2.max; clock.m2++) {
732                         if (clock.m2 >= clock.m1)
733                                 break;
734                         for (clock.n = limit->n.min;
735                              clock.n <= limit->n.max; clock.n++) {
736                                 for (clock.p1 = limit->p1.min;
737                                         clock.p1 <= limit->p1.max; clock.p1++) {
738                                         int this_err;
739
740                                         i9xx_calc_dpll_params(refclk, &clock);
741                                         if (!intel_PLL_is_valid(dev, limit,
742                                                                 &clock))
743                                                 continue;
744                                         if (match_clock &&
745                                             clock.p != match_clock->p)
746                                                 continue;
747
748                                         this_err = abs(clock.dot - target);
749                                         if (this_err < err) {
750                                                 *best_clock = clock;
751                                                 err = this_err;
752                                         }
753                                 }
754                         }
755                 }
756         }
757
758         return (err != target);
759 }
760
761 /*
762  * Returns a set of divisors for the desired target clock with the given
763  * refclk, or FALSE.  The returned values represent the clock equation:
764  * reflck * (5 * (m1 + 2) + (m2 + 2)) / (n + 2) / p1 / p2.
765  *
766  * Target and reference clocks are specified in kHz.
767  *
768  * If match_clock is provided, then best_clock P divider must match the P
769  * divider from @match_clock used for LVDS downclocking.
770  */
771 static bool
772 pnv_find_best_dpll(const struct intel_limit *limit,
773                    struct intel_crtc_state *crtc_state,
774                    int target, int refclk, struct dpll *match_clock,
775                    struct dpll *best_clock)
776 {
777         struct drm_device *dev = crtc_state->base.crtc->dev;
778         struct dpll clock;
779         int err = target;
780
781         memset(best_clock, 0, sizeof(*best_clock));
782
783         clock.p2 = i9xx_select_p2_div(limit, crtc_state, target);
784
785         for (clock.m1 = limit->m1.min; clock.m1 <= limit->m1.max;
786              clock.m1++) {
787                 for (clock.m2 = limit->m2.min;
788                      clock.m2 <= limit->m2.max; clock.m2++) {
789                         for (clock.n = limit->n.min;
790                              clock.n <= limit->n.max; clock.n++) {
791                                 for (clock.p1 = limit->p1.min;
792                                         clock.p1 <= limit->p1.max; clock.p1++) {
793                                         int this_err;
794
795                                         pnv_calc_dpll_params(refclk, &clock);
796                                         if (!intel_PLL_is_valid(dev, limit,
797                                                                 &clock))
798                                                 continue;
799                                         if (match_clock &&
800                                             clock.p != match_clock->p)
801                                                 continue;
802
803                                         this_err = abs(clock.dot - target);
804                                         if (this_err < err) {
805                                                 *best_clock = clock;
806                                                 err = this_err;
807                                         }
808                                 }
809                         }
810                 }
811         }
812
813         return (err != target);
814 }
815
816 /*
817  * Returns a set of divisors for the desired target clock with the given
818  * refclk, or FALSE.  The returned values represent the clock equation:
819  * reflck * (5 * (m1 + 2) + (m2 + 2)) / (n + 2) / p1 / p2.
820  *
821  * Target and reference clocks are specified in kHz.
822  *
823  * If match_clock is provided, then best_clock P divider must match the P
824  * divider from @match_clock used for LVDS downclocking.
825  */
826 static bool
827 g4x_find_best_dpll(const struct intel_limit *limit,
828                    struct intel_crtc_state *crtc_state,
829                    int target, int refclk, struct dpll *match_clock,
830                    struct dpll *best_clock)
831 {
832         struct drm_device *dev = crtc_state->base.crtc->dev;
833         struct dpll clock;
834         int max_n;
835         bool found = false;
836         /* approximately equals target * 0.00585 */
837         int err_most = (target >> 8) + (target >> 9);
838
839         memset(best_clock, 0, sizeof(*best_clock));
840
841         clock.p2 = i9xx_select_p2_div(limit, crtc_state, target);
842
843         max_n = limit->n.max;
844         /* based on hardware requirement, prefer smaller n to precision */
845         for (clock.n = limit->n.min; clock.n <= max_n; clock.n++) {
846                 /* based on hardware requirement, prefere larger m1,m2 */
847                 for (clock.m1 = limit->m1.max;
848                      clock.m1 >= limit->m1.min; clock.m1--) {
849                         for (clock.m2 = limit->m2.max;
850                              clock.m2 >= limit->m2.min; clock.m2--) {
851                                 for (clock.p1 = limit->p1.max;
852                                      clock.p1 >= limit->p1.min; clock.p1--) {
853                                         int this_err;
854
855                                         i9xx_calc_dpll_params(refclk, &clock);
856                                         if (!intel_PLL_is_valid(dev, limit,
857                                                                 &clock))
858                                                 continue;
859
860                                         this_err = abs(clock.dot - target);
861                                         if (this_err < err_most) {
862                                                 *best_clock = clock;
863                                                 err_most = this_err;
864                                                 max_n = clock.n;
865                                                 found = true;
866                                         }
867                                 }
868                         }
869                 }
870         }
871         return found;
872 }
873
874 /*
875  * Check if the calculated PLL configuration is more optimal compared to the
876  * best configuration and error found so far. Return the calculated error.
877  */
878 static bool vlv_PLL_is_optimal(struct drm_device *dev, int target_freq,
879                                const struct dpll *calculated_clock,
880                                const struct dpll *best_clock,
881                                unsigned int best_error_ppm,
882                                unsigned int *error_ppm)
883 {
884         /*
885          * For CHV ignore the error and consider only the P value.
886          * Prefer a bigger P value based on HW requirements.
887          */
888         if (IS_CHERRYVIEW(dev)) {
889                 *error_ppm = 0;
890
891                 return calculated_clock->p > best_clock->p;
892         }
893
894         if (WARN_ON_ONCE(!target_freq))
895                 return false;
896
897         *error_ppm = div_u64(1000000ULL *
898                                 abs(target_freq - calculated_clock->dot),
899                              target_freq);
900         /*
901          * Prefer a better P value over a better (smaller) error if the error
902          * is small. Ensure this preference for future configurations too by
903          * setting the error to 0.
904          */
905         if (*error_ppm < 100 && calculated_clock->p > best_clock->p) {
906                 *error_ppm = 0;
907
908                 return true;
909         }
910
911         return *error_ppm + 10 < best_error_ppm;
912 }
913
914 /*
915  * Returns a set of divisors for the desired target clock with the given
916  * refclk, or FALSE.  The returned values represent the clock equation:
917  * reflck * (5 * (m1 + 2) + (m2 + 2)) / (n + 2) / p1 / p2.
918  */
919 static bool
920 vlv_find_best_dpll(const struct intel_limit *limit,
921                    struct intel_crtc_state *crtc_state,
922                    int target, int refclk, struct dpll *match_clock,
923                    struct dpll *best_clock)
924 {
925         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
926         struct drm_device *dev = crtc->base.dev;
927         struct dpll clock;
928         unsigned int bestppm = 1000000;
929         /* min update 19.2 MHz */
930         int max_n = min(limit->n.max, refclk / 19200);
931         bool found = false;
932
933         target *= 5; /* fast clock */
934
935         memset(best_clock, 0, sizeof(*best_clock));
936
937         /* based on hardware requirement, prefer smaller n to precision */
938         for (clock.n = limit->n.min; clock.n <= max_n; clock.n++) {
939                 for (clock.p1 = limit->p1.max; clock.p1 >= limit->p1.min; clock.p1--) {
940                         for (clock.p2 = limit->p2.p2_fast; clock.p2 >= limit->p2.p2_slow;
941                              clock.p2 -= clock.p2 > 10 ? 2 : 1) {
942                                 clock.p = clock.p1 * clock.p2;
943                                 /* based on hardware requirement, prefer bigger m1,m2 values */
944                                 for (clock.m1 = limit->m1.min; clock.m1 <= limit->m1.max; clock.m1++) {
945                                         unsigned int ppm;
946
947                                         clock.m2 = DIV_ROUND_CLOSEST(target * clock.p * clock.n,
948                                                                      refclk * clock.m1);
949
950                                         vlv_calc_dpll_params(refclk, &clock);
951
952                                         if (!intel_PLL_is_valid(dev, limit,
953                                                                 &clock))
954                                                 continue;
955
956                                         if (!vlv_PLL_is_optimal(dev, target,
957                                                                 &clock,
958                                                                 best_clock,
959                                                                 bestppm, &ppm))
960                                                 continue;
961
962                                         *best_clock = clock;
963                                         bestppm = ppm;
964                                         found = true;
965                                 }
966                         }
967                 }
968         }
969
970         return found;
971 }
972
973 /*
974  * Returns a set of divisors for the desired target clock with the given
975  * refclk, or FALSE.  The returned values represent the clock equation:
976  * reflck * (5 * (m1 + 2) + (m2 + 2)) / (n + 2) / p1 / p2.
977  */
978 static bool
979 chv_find_best_dpll(const struct intel_limit *limit,
980                    struct intel_crtc_state *crtc_state,
981                    int target, int refclk, struct dpll *match_clock,
982                    struct dpll *best_clock)
983 {
984         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
985         struct drm_device *dev = crtc->base.dev;
986         unsigned int best_error_ppm;
987         struct dpll clock;
988         uint64_t m2;
989         int found = false;
990
991         memset(best_clock, 0, sizeof(*best_clock));
992         best_error_ppm = 1000000;
993
994         /*
995          * Based on hardware doc, the n always set to 1, and m1 always
996          * set to 2.  If requires to support 200Mhz refclk, we need to
997          * revisit this because n may not 1 anymore.
998          */
999         clock.n = 1, clock.m1 = 2;
1000         target *= 5;    /* fast clock */
1001
1002         for (clock.p1 = limit->p1.max; clock.p1 >= limit->p1.min; clock.p1--) {
1003                 for (clock.p2 = limit->p2.p2_fast;
1004                                 clock.p2 >= limit->p2.p2_slow;
1005                                 clock.p2 -= clock.p2 > 10 ? 2 : 1) {
1006                         unsigned int error_ppm;
1007
1008                         clock.p = clock.p1 * clock.p2;
1009
1010                         m2 = DIV_ROUND_CLOSEST_ULL(((uint64_t)target * clock.p *
1011                                         clock.n) << 22, refclk * clock.m1);
1012
1013                         if (m2 > INT_MAX/clock.m1)
1014                                 continue;
1015
1016                         clock.m2 = m2;
1017
1018                         chv_calc_dpll_params(refclk, &clock);
1019
1020                         if (!intel_PLL_is_valid(dev, limit, &clock))
1021                                 continue;
1022
1023                         if (!vlv_PLL_is_optimal(dev, target, &clock, best_clock,
1024                                                 best_error_ppm, &error_ppm))
1025                                 continue;
1026
1027                         *best_clock = clock;
1028                         best_error_ppm = error_ppm;
1029                         found = true;
1030                 }
1031         }
1032
1033         return found;
1034 }
1035
1036 bool bxt_find_best_dpll(struct intel_crtc_state *crtc_state, int target_clock,
1037                         struct dpll *best_clock)
1038 {
1039         int refclk = 100000;
1040         const struct intel_limit *limit = &intel_limits_bxt;
1041
1042         return chv_find_best_dpll(limit, crtc_state,
1043                                   target_clock, refclk, NULL, best_clock);
1044 }
1045
1046 bool intel_crtc_active(struct drm_crtc *crtc)
1047 {
1048         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
1049
1050         /* Be paranoid as we can arrive here with only partial
1051          * state retrieved from the hardware during setup.
1052          *
1053          * We can ditch the adjusted_mode.crtc_clock check as soon
1054          * as Haswell has gained clock readout/fastboot support.
1055          *
1056          * We can ditch the crtc->primary->fb check as soon as we can
1057          * properly reconstruct framebuffers.
1058          *
1059          * FIXME: The intel_crtc->active here should be switched to
1060          * crtc->state->active once we have proper CRTC states wired up
1061          * for atomic.
1062          */
1063         return intel_crtc->active && crtc->primary->state->fb &&
1064                 intel_crtc->config->base.adjusted_mode.crtc_clock;
1065 }
1066
1067 enum transcoder intel_pipe_to_cpu_transcoder(struct drm_i915_private *dev_priv,
1068                                              enum pipe pipe)
1069 {
1070         struct drm_crtc *crtc = dev_priv->pipe_to_crtc_mapping[pipe];
1071         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
1072
1073         return intel_crtc->config->cpu_transcoder;
1074 }
1075
1076 static bool pipe_dsl_stopped(struct drm_device *dev, enum pipe pipe)
1077 {
1078         struct drm_i915_private *dev_priv = dev->dev_private;
1079         i915_reg_t reg = PIPEDSL(pipe);
1080         u32 line1, line2;
1081         u32 line_mask;
1082
1083         if (IS_GEN2(dev))
1084                 line_mask = DSL_LINEMASK_GEN2;
1085         else
1086                 line_mask = DSL_LINEMASK_GEN3;
1087
1088         line1 = I915_READ(reg) & line_mask;
1089         msleep(5);
1090         line2 = I915_READ(reg) & line_mask;
1091
1092         return line1 == line2;
1093 }
1094
1095 /*
1096  * intel_wait_for_pipe_off - wait for pipe to turn off
1097  * @crtc: crtc whose pipe to wait for
1098  *
1099  * After disabling a pipe, we can't wait for vblank in the usual way,
1100  * spinning on the vblank interrupt status bit, since we won't actually
1101  * see an interrupt when the pipe is disabled.
1102  *
1103  * On Gen4 and above:
1104  *   wait for the pipe register state bit to turn off
1105  *
1106  * Otherwise:
1107  *   wait for the display line value to settle (it usually
1108  *   ends up stopping at the start of the next frame).
1109  *
1110  */
1111 static void intel_wait_for_pipe_off(struct intel_crtc *crtc)
1112 {
1113         struct drm_device *dev = crtc->base.dev;
1114         struct drm_i915_private *dev_priv = dev->dev_private;
1115         enum transcoder cpu_transcoder = crtc->config->cpu_transcoder;
1116         enum pipe pipe = crtc->pipe;
1117
1118         if (INTEL_INFO(dev)->gen >= 4) {
1119                 i915_reg_t reg = PIPECONF(cpu_transcoder);
1120
1121                 /* Wait for the Pipe State to go off */
1122                 if (wait_for((I915_READ(reg) & I965_PIPECONF_ACTIVE) == 0,
1123                              100))
1124                         WARN(1, "pipe_off wait timed out\n");
1125         } else {
1126                 /* Wait for the display line to settle */
1127                 if (wait_for(pipe_dsl_stopped(dev, pipe), 100))
1128                         WARN(1, "pipe_off wait timed out\n");
1129         }
1130 }
1131
1132 /* Only for pre-ILK configs */
1133 void assert_pll(struct drm_i915_private *dev_priv,
1134                 enum pipe pipe, bool state)
1135 {
1136         u32 val;
1137         bool cur_state;
1138
1139         val = I915_READ(DPLL(pipe));
1140         cur_state = !!(val & DPLL_VCO_ENABLE);
1141         I915_STATE_WARN(cur_state != state,
1142              "PLL state assertion failure (expected %s, current %s)\n",
1143                         onoff(state), onoff(cur_state));
1144 }
1145
1146 /* XXX: the dsi pll is shared between MIPI DSI ports */
1147 void assert_dsi_pll(struct drm_i915_private *dev_priv, bool state)
1148 {
1149         u32 val;
1150         bool cur_state;
1151
1152         mutex_lock(&dev_priv->sb_lock);
1153         val = vlv_cck_read(dev_priv, CCK_REG_DSI_PLL_CONTROL);
1154         mutex_unlock(&dev_priv->sb_lock);
1155
1156         cur_state = val & DSI_PLL_VCO_EN;
1157         I915_STATE_WARN(cur_state != state,
1158              "DSI PLL state assertion failure (expected %s, current %s)\n",
1159                         onoff(state), onoff(cur_state));
1160 }
1161
1162 static void assert_fdi_tx(struct drm_i915_private *dev_priv,
1163                           enum pipe pipe, bool state)
1164 {
1165         bool cur_state;
1166         enum transcoder cpu_transcoder = intel_pipe_to_cpu_transcoder(dev_priv,
1167                                                                       pipe);
1168
1169         if (HAS_DDI(dev_priv)) {
1170                 /* DDI does not have a specific FDI_TX register */
1171                 u32 val = I915_READ(TRANS_DDI_FUNC_CTL(cpu_transcoder));
1172                 cur_state = !!(val & TRANS_DDI_FUNC_ENABLE);
1173         } else {
1174                 u32 val = I915_READ(FDI_TX_CTL(pipe));
1175                 cur_state = !!(val & FDI_TX_ENABLE);
1176         }
1177         I915_STATE_WARN(cur_state != state,
1178              "FDI TX state assertion failure (expected %s, current %s)\n",
1179                         onoff(state), onoff(cur_state));
1180 }
1181 #define assert_fdi_tx_enabled(d, p) assert_fdi_tx(d, p, true)
1182 #define assert_fdi_tx_disabled(d, p) assert_fdi_tx(d, p, false)
1183
1184 static void assert_fdi_rx(struct drm_i915_private *dev_priv,
1185                           enum pipe pipe, bool state)
1186 {
1187         u32 val;
1188         bool cur_state;
1189
1190         val = I915_READ(FDI_RX_CTL(pipe));
1191         cur_state = !!(val & FDI_RX_ENABLE);
1192         I915_STATE_WARN(cur_state != state,
1193              "FDI RX state assertion failure (expected %s, current %s)\n",
1194                         onoff(state), onoff(cur_state));
1195 }
1196 #define assert_fdi_rx_enabled(d, p) assert_fdi_rx(d, p, true)
1197 #define assert_fdi_rx_disabled(d, p) assert_fdi_rx(d, p, false)
1198
1199 static void assert_fdi_tx_pll_enabled(struct drm_i915_private *dev_priv,
1200                                       enum pipe pipe)
1201 {
1202         u32 val;
1203
1204         /* ILK FDI PLL is always enabled */
1205         if (IS_GEN5(dev_priv))
1206                 return;
1207
1208         /* On Haswell, DDI ports are responsible for the FDI PLL setup */
1209         if (HAS_DDI(dev_priv))
1210                 return;
1211
1212         val = I915_READ(FDI_TX_CTL(pipe));
1213         I915_STATE_WARN(!(val & FDI_TX_PLL_ENABLE), "FDI TX PLL assertion failure, should be active but is disabled\n");
1214 }
1215
1216 void assert_fdi_rx_pll(struct drm_i915_private *dev_priv,
1217                        enum pipe pipe, bool state)
1218 {
1219         u32 val;
1220         bool cur_state;
1221
1222         val = I915_READ(FDI_RX_CTL(pipe));
1223         cur_state = !!(val & FDI_RX_PLL_ENABLE);
1224         I915_STATE_WARN(cur_state != state,
1225              "FDI RX PLL assertion failure (expected %s, current %s)\n",
1226                         onoff(state), onoff(cur_state));
1227 }
1228
1229 void assert_panel_unlocked(struct drm_i915_private *dev_priv,
1230                            enum pipe pipe)
1231 {
1232         struct drm_device *dev = dev_priv->dev;
1233         i915_reg_t pp_reg;
1234         u32 val;
1235         enum pipe panel_pipe = PIPE_A;
1236         bool locked = true;
1237
1238         if (WARN_ON(HAS_DDI(dev)))
1239                 return;
1240
1241         if (HAS_PCH_SPLIT(dev)) {
1242                 u32 port_sel;
1243
1244                 pp_reg = PCH_PP_CONTROL;
1245                 port_sel = I915_READ(PCH_PP_ON_DELAYS) & PANEL_PORT_SELECT_MASK;
1246
1247                 if (port_sel == PANEL_PORT_SELECT_LVDS &&
1248                     I915_READ(PCH_LVDS) & LVDS_PIPEB_SELECT)
1249                         panel_pipe = PIPE_B;
1250                 /* XXX: else fix for eDP */
1251         } else if (IS_VALLEYVIEW(dev) || IS_CHERRYVIEW(dev)) {
1252                 /* presumably write lock depends on pipe, not port select */
1253                 pp_reg = VLV_PIPE_PP_CONTROL(pipe);
1254                 panel_pipe = pipe;
1255         } else {
1256                 pp_reg = PP_CONTROL;
1257                 if (I915_READ(LVDS) & LVDS_PIPEB_SELECT)
1258                         panel_pipe = PIPE_B;
1259         }
1260
1261         val = I915_READ(pp_reg);
1262         if (!(val & PANEL_POWER_ON) ||
1263             ((val & PANEL_UNLOCK_MASK) == PANEL_UNLOCK_REGS))
1264                 locked = false;
1265
1266         I915_STATE_WARN(panel_pipe == pipe && locked,
1267              "panel assertion failure, pipe %c regs locked\n",
1268              pipe_name(pipe));
1269 }
1270
1271 static void assert_cursor(struct drm_i915_private *dev_priv,
1272                           enum pipe pipe, bool state)
1273 {
1274         struct drm_device *dev = dev_priv->dev;
1275         bool cur_state;
1276
1277         if (IS_845G(dev) || IS_I865G(dev))
1278                 cur_state = I915_READ(CURCNTR(PIPE_A)) & CURSOR_ENABLE;
1279         else
1280                 cur_state = I915_READ(CURCNTR(pipe)) & CURSOR_MODE;
1281
1282         I915_STATE_WARN(cur_state != state,
1283              "cursor on pipe %c assertion failure (expected %s, current %s)\n",
1284                         pipe_name(pipe), onoff(state), onoff(cur_state));
1285 }
1286 #define assert_cursor_enabled(d, p) assert_cursor(d, p, true)
1287 #define assert_cursor_disabled(d, p) assert_cursor(d, p, false)
1288
1289 void assert_pipe(struct drm_i915_private *dev_priv,
1290                  enum pipe pipe, bool state)
1291 {
1292         bool cur_state;
1293         enum transcoder cpu_transcoder = intel_pipe_to_cpu_transcoder(dev_priv,
1294                                                                       pipe);
1295         enum intel_display_power_domain power_domain;
1296
1297         /* if we need the pipe quirk it must be always on */
1298         if ((pipe == PIPE_A && dev_priv->quirks & QUIRK_PIPEA_FORCE) ||
1299             (pipe == PIPE_B && dev_priv->quirks & QUIRK_PIPEB_FORCE))
1300                 state = true;
1301
1302         power_domain = POWER_DOMAIN_TRANSCODER(cpu_transcoder);
1303         if (intel_display_power_get_if_enabled(dev_priv, power_domain)) {
1304                 u32 val = I915_READ(PIPECONF(cpu_transcoder));
1305                 cur_state = !!(val & PIPECONF_ENABLE);
1306
1307                 intel_display_power_put(dev_priv, power_domain);
1308         } else {
1309                 cur_state = false;
1310         }
1311
1312         I915_STATE_WARN(cur_state != state,
1313              "pipe %c assertion failure (expected %s, current %s)\n",
1314                         pipe_name(pipe), onoff(state), onoff(cur_state));
1315 }
1316
1317 static void assert_plane(struct drm_i915_private *dev_priv,
1318                          enum plane plane, bool state)
1319 {
1320         u32 val;
1321         bool cur_state;
1322
1323         val = I915_READ(DSPCNTR(plane));
1324         cur_state = !!(val & DISPLAY_PLANE_ENABLE);
1325         I915_STATE_WARN(cur_state != state,
1326              "plane %c assertion failure (expected %s, current %s)\n",
1327                         plane_name(plane), onoff(state), onoff(cur_state));
1328 }
1329
1330 #define assert_plane_enabled(d, p) assert_plane(d, p, true)
1331 #define assert_plane_disabled(d, p) assert_plane(d, p, false)
1332
1333 static void assert_planes_disabled(struct drm_i915_private *dev_priv,
1334                                    enum pipe pipe)
1335 {
1336         struct drm_device *dev = dev_priv->dev;
1337         int i;
1338
1339         /* Primary planes are fixed to pipes on gen4+ */
1340         if (INTEL_INFO(dev)->gen >= 4) {
1341                 u32 val = I915_READ(DSPCNTR(pipe));
1342                 I915_STATE_WARN(val & DISPLAY_PLANE_ENABLE,
1343                      "plane %c assertion failure, should be disabled but not\n",
1344                      plane_name(pipe));
1345                 return;
1346         }
1347
1348         /* Need to check both planes against the pipe */
1349         for_each_pipe(dev_priv, i) {
1350                 u32 val = I915_READ(DSPCNTR(i));
1351                 enum pipe cur_pipe = (val & DISPPLANE_SEL_PIPE_MASK) >>
1352                         DISPPLANE_SEL_PIPE_SHIFT;
1353                 I915_STATE_WARN((val & DISPLAY_PLANE_ENABLE) && pipe == cur_pipe,
1354                      "plane %c assertion failure, should be off on pipe %c but is still active\n",
1355                      plane_name(i), pipe_name(pipe));
1356         }
1357 }
1358
1359 static void assert_sprites_disabled(struct drm_i915_private *dev_priv,
1360                                     enum pipe pipe)
1361 {
1362         struct drm_device *dev = dev_priv->dev;
1363         int sprite;
1364
1365         if (INTEL_INFO(dev)->gen >= 9) {
1366                 for_each_sprite(dev_priv, pipe, sprite) {
1367                         u32 val = I915_READ(PLANE_CTL(pipe, sprite));
1368                         I915_STATE_WARN(val & PLANE_CTL_ENABLE,
1369                              "plane %d assertion failure, should be off on pipe %c but is still active\n",
1370                              sprite, pipe_name(pipe));
1371                 }
1372         } else if (IS_VALLEYVIEW(dev) || IS_CHERRYVIEW(dev)) {
1373                 for_each_sprite(dev_priv, pipe, sprite) {
1374                         u32 val = I915_READ(SPCNTR(pipe, sprite));
1375                         I915_STATE_WARN(val & SP_ENABLE,
1376                              "sprite %c assertion failure, should be off on pipe %c but is still active\n",
1377                              sprite_name(pipe, sprite), pipe_name(pipe));
1378                 }
1379         } else if (INTEL_INFO(dev)->gen >= 7) {
1380                 u32 val = I915_READ(SPRCTL(pipe));
1381                 I915_STATE_WARN(val & SPRITE_ENABLE,
1382                      "sprite %c assertion failure, should be off on pipe %c but is still active\n",
1383                      plane_name(pipe), pipe_name(pipe));
1384         } else if (INTEL_INFO(dev)->gen >= 5) {
1385                 u32 val = I915_READ(DVSCNTR(pipe));
1386                 I915_STATE_WARN(val & DVS_ENABLE,
1387                      "sprite %c assertion failure, should be off on pipe %c but is still active\n",
1388                      plane_name(pipe), pipe_name(pipe));
1389         }
1390 }
1391
1392 static void assert_vblank_disabled(struct drm_crtc *crtc)
1393 {
1394         if (I915_STATE_WARN_ON(drm_crtc_vblank_get(crtc) == 0))
1395                 drm_crtc_vblank_put(crtc);
1396 }
1397
1398 void assert_pch_transcoder_disabled(struct drm_i915_private *dev_priv,
1399                                     enum pipe pipe)
1400 {
1401         u32 val;
1402         bool enabled;
1403
1404         val = I915_READ(PCH_TRANSCONF(pipe));
1405         enabled = !!(val & TRANS_ENABLE);
1406         I915_STATE_WARN(enabled,
1407              "transcoder assertion failed, should be off on pipe %c but is still active\n",
1408              pipe_name(pipe));
1409 }
1410
1411 static bool dp_pipe_enabled(struct drm_i915_private *dev_priv,
1412                             enum pipe pipe, u32 port_sel, u32 val)
1413 {
1414         if ((val & DP_PORT_EN) == 0)
1415                 return false;
1416
1417         if (HAS_PCH_CPT(dev_priv)) {
1418                 u32 trans_dp_ctl = I915_READ(TRANS_DP_CTL(pipe));
1419                 if ((trans_dp_ctl & TRANS_DP_PORT_SEL_MASK) != port_sel)
1420                         return false;
1421         } else if (IS_CHERRYVIEW(dev_priv)) {
1422                 if ((val & DP_PIPE_MASK_CHV) != DP_PIPE_SELECT_CHV(pipe))
1423                         return false;
1424         } else {
1425                 if ((val & DP_PIPE_MASK) != (pipe << 30))
1426                         return false;
1427         }
1428         return true;
1429 }
1430
1431 static bool hdmi_pipe_enabled(struct drm_i915_private *dev_priv,
1432                               enum pipe pipe, u32 val)
1433 {
1434         if ((val & SDVO_ENABLE) == 0)
1435                 return false;
1436
1437         if (HAS_PCH_CPT(dev_priv)) {
1438                 if ((val & SDVO_PIPE_SEL_MASK_CPT) != SDVO_PIPE_SEL_CPT(pipe))
1439                         return false;
1440         } else if (IS_CHERRYVIEW(dev_priv)) {
1441                 if ((val & SDVO_PIPE_SEL_MASK_CHV) != SDVO_PIPE_SEL_CHV(pipe))
1442                         return false;
1443         } else {
1444                 if ((val & SDVO_PIPE_SEL_MASK) != SDVO_PIPE_SEL(pipe))
1445                         return false;
1446         }
1447         return true;
1448 }
1449
1450 static bool lvds_pipe_enabled(struct drm_i915_private *dev_priv,
1451                               enum pipe pipe, u32 val)
1452 {
1453         if ((val & LVDS_PORT_EN) == 0)
1454                 return false;
1455
1456         if (HAS_PCH_CPT(dev_priv)) {
1457                 if ((val & PORT_TRANS_SEL_MASK) != PORT_TRANS_SEL_CPT(pipe))
1458                         return false;
1459         } else {
1460                 if ((val & LVDS_PIPE_MASK) != LVDS_PIPE(pipe))
1461                         return false;
1462         }
1463         return true;
1464 }
1465
1466 static bool adpa_pipe_enabled(struct drm_i915_private *dev_priv,
1467                               enum pipe pipe, u32 val)
1468 {
1469         if ((val & ADPA_DAC_ENABLE) == 0)
1470                 return false;
1471         if (HAS_PCH_CPT(dev_priv)) {
1472                 if ((val & PORT_TRANS_SEL_MASK) != PORT_TRANS_SEL_CPT(pipe))
1473                         return false;
1474         } else {
1475                 if ((val & ADPA_PIPE_SELECT_MASK) != ADPA_PIPE_SELECT(pipe))
1476                         return false;
1477         }
1478         return true;
1479 }
1480
1481 static void assert_pch_dp_disabled(struct drm_i915_private *dev_priv,
1482                                    enum pipe pipe, i915_reg_t reg,
1483                                    u32 port_sel)
1484 {
1485         u32 val = I915_READ(reg);
1486         I915_STATE_WARN(dp_pipe_enabled(dev_priv, pipe, port_sel, val),
1487              "PCH DP (0x%08x) enabled on transcoder %c, should be disabled\n",
1488              i915_mmio_reg_offset(reg), pipe_name(pipe));
1489
1490         I915_STATE_WARN(HAS_PCH_IBX(dev_priv) && (val & DP_PORT_EN) == 0
1491              && (val & DP_PIPEB_SELECT),
1492              "IBX PCH dp port still using transcoder B\n");
1493 }
1494
1495 static void assert_pch_hdmi_disabled(struct drm_i915_private *dev_priv,
1496                                      enum pipe pipe, i915_reg_t reg)
1497 {
1498         u32 val = I915_READ(reg);
1499         I915_STATE_WARN(hdmi_pipe_enabled(dev_priv, pipe, val),
1500              "PCH HDMI (0x%08x) enabled on transcoder %c, should be disabled\n",
1501              i915_mmio_reg_offset(reg), pipe_name(pipe));
1502
1503         I915_STATE_WARN(HAS_PCH_IBX(dev_priv) && (val & SDVO_ENABLE) == 0
1504              && (val & SDVO_PIPE_B_SELECT),
1505              "IBX PCH hdmi port still using transcoder B\n");
1506 }
1507
1508 static void assert_pch_ports_disabled(struct drm_i915_private *dev_priv,
1509                                       enum pipe pipe)
1510 {
1511         u32 val;
1512
1513         assert_pch_dp_disabled(dev_priv, pipe, PCH_DP_B, TRANS_DP_PORT_SEL_B);
1514         assert_pch_dp_disabled(dev_priv, pipe, PCH_DP_C, TRANS_DP_PORT_SEL_C);
1515         assert_pch_dp_disabled(dev_priv, pipe, PCH_DP_D, TRANS_DP_PORT_SEL_D);
1516
1517         val = I915_READ(PCH_ADPA);
1518         I915_STATE_WARN(adpa_pipe_enabled(dev_priv, pipe, val),
1519              "PCH VGA enabled on transcoder %c, should be disabled\n",
1520              pipe_name(pipe));
1521
1522         val = I915_READ(PCH_LVDS);
1523         I915_STATE_WARN(lvds_pipe_enabled(dev_priv, pipe, val),
1524              "PCH LVDS enabled on transcoder %c, should be disabled\n",
1525              pipe_name(pipe));
1526
1527         assert_pch_hdmi_disabled(dev_priv, pipe, PCH_HDMIB);
1528         assert_pch_hdmi_disabled(dev_priv, pipe, PCH_HDMIC);
1529         assert_pch_hdmi_disabled(dev_priv, pipe, PCH_HDMID);
1530 }
1531
1532 static void _vlv_enable_pll(struct intel_crtc *crtc,
1533                             const struct intel_crtc_state *pipe_config)
1534 {
1535         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
1536         enum pipe pipe = crtc->pipe;
1537
1538         I915_WRITE(DPLL(pipe), pipe_config->dpll_hw_state.dpll);
1539         POSTING_READ(DPLL(pipe));
1540         udelay(150);
1541
1542         if (wait_for(((I915_READ(DPLL(pipe)) & DPLL_LOCK_VLV) == DPLL_LOCK_VLV), 1))
1543                 DRM_ERROR("DPLL %d failed to lock\n", pipe);
1544 }
1545
1546 static void vlv_enable_pll(struct intel_crtc *crtc,
1547                            const struct intel_crtc_state *pipe_config)
1548 {
1549         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
1550         enum pipe pipe = crtc->pipe;
1551
1552         assert_pipe_disabled(dev_priv, pipe);
1553
1554         /* PLL is protected by panel, make sure we can write it */
1555         assert_panel_unlocked(dev_priv, pipe);
1556
1557         if (pipe_config->dpll_hw_state.dpll & DPLL_VCO_ENABLE)
1558                 _vlv_enable_pll(crtc, pipe_config);
1559
1560         I915_WRITE(DPLL_MD(pipe), pipe_config->dpll_hw_state.dpll_md);
1561         POSTING_READ(DPLL_MD(pipe));
1562 }
1563
1564
1565 static void _chv_enable_pll(struct intel_crtc *crtc,
1566                             const struct intel_crtc_state *pipe_config)
1567 {
1568         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
1569         enum pipe pipe = crtc->pipe;
1570         enum dpio_channel port = vlv_pipe_to_channel(pipe);
1571         u32 tmp;
1572
1573         mutex_lock(&dev_priv->sb_lock);
1574
1575         /* Enable back the 10bit clock to display controller */
1576         tmp = vlv_dpio_read(dev_priv, pipe, CHV_CMN_DW14(port));
1577         tmp |= DPIO_DCLKP_EN;
1578         vlv_dpio_write(dev_priv, pipe, CHV_CMN_DW14(port), tmp);
1579
1580         mutex_unlock(&dev_priv->sb_lock);
1581
1582         /*
1583          * Need to wait > 100ns between dclkp clock enable bit and PLL enable.
1584          */
1585         udelay(1);
1586
1587         /* Enable PLL */
1588         I915_WRITE(DPLL(pipe), pipe_config->dpll_hw_state.dpll);
1589
1590         /* Check PLL is locked */
1591         if (wait_for(((I915_READ(DPLL(pipe)) & DPLL_LOCK_VLV) == DPLL_LOCK_VLV), 1))
1592                 DRM_ERROR("PLL %d failed to lock\n", pipe);
1593 }
1594
1595 static void chv_enable_pll(struct intel_crtc *crtc,
1596                            const struct intel_crtc_state *pipe_config)
1597 {
1598         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
1599         enum pipe pipe = crtc->pipe;
1600
1601         assert_pipe_disabled(dev_priv, pipe);
1602
1603         /* PLL is protected by panel, make sure we can write it */
1604         assert_panel_unlocked(dev_priv, pipe);
1605
1606         if (pipe_config->dpll_hw_state.dpll & DPLL_VCO_ENABLE)
1607                 _chv_enable_pll(crtc, pipe_config);
1608
1609         if (pipe != PIPE_A) {
1610                 /*
1611                  * WaPixelRepeatModeFixForC0:chv
1612                  *
1613                  * DPLLCMD is AWOL. Use chicken bits to propagate
1614                  * the value from DPLLBMD to either pipe B or C.
1615                  */
1616                 I915_WRITE(CBR4_VLV, pipe == PIPE_B ? CBR_DPLLBMD_PIPE_B : CBR_DPLLBMD_PIPE_C);
1617                 I915_WRITE(DPLL_MD(PIPE_B), pipe_config->dpll_hw_state.dpll_md);
1618                 I915_WRITE(CBR4_VLV, 0);
1619                 dev_priv->chv_dpll_md[pipe] = pipe_config->dpll_hw_state.dpll_md;
1620
1621                 /*
1622                  * DPLLB VGA mode also seems to cause problems.
1623                  * We should always have it disabled.
1624                  */
1625                 WARN_ON((I915_READ(DPLL(PIPE_B)) & DPLL_VGA_MODE_DIS) == 0);
1626         } else {
1627                 I915_WRITE(DPLL_MD(pipe), pipe_config->dpll_hw_state.dpll_md);
1628                 POSTING_READ(DPLL_MD(pipe));
1629         }
1630 }
1631
1632 static int intel_num_dvo_pipes(struct drm_device *dev)
1633 {
1634         struct intel_crtc *crtc;
1635         int count = 0;
1636
1637         for_each_intel_crtc(dev, crtc)
1638                 count += crtc->base.state->active &&
1639                         intel_pipe_has_type(crtc, INTEL_OUTPUT_DVO);
1640
1641         return count;
1642 }
1643
1644 static void i9xx_enable_pll(struct intel_crtc *crtc)
1645 {
1646         struct drm_device *dev = crtc->base.dev;
1647         struct drm_i915_private *dev_priv = dev->dev_private;
1648         i915_reg_t reg = DPLL(crtc->pipe);
1649         u32 dpll = crtc->config->dpll_hw_state.dpll;
1650
1651         assert_pipe_disabled(dev_priv, crtc->pipe);
1652
1653         /* PLL is protected by panel, make sure we can write it */
1654         if (IS_MOBILE(dev) && !IS_I830(dev))
1655                 assert_panel_unlocked(dev_priv, crtc->pipe);
1656
1657         /* Enable DVO 2x clock on both PLLs if necessary */
1658         if (IS_I830(dev) && intel_num_dvo_pipes(dev) > 0) {
1659                 /*
1660                  * It appears to be important that we don't enable this
1661                  * for the current pipe before otherwise configuring the
1662                  * PLL. No idea how this should be handled if multiple
1663                  * DVO outputs are enabled simultaneosly.
1664                  */
1665                 dpll |= DPLL_DVO_2X_MODE;
1666                 I915_WRITE(DPLL(!crtc->pipe),
1667                            I915_READ(DPLL(!crtc->pipe)) | DPLL_DVO_2X_MODE);
1668         }
1669
1670         /*
1671          * Apparently we need to have VGA mode enabled prior to changing
1672          * the P1/P2 dividers. Otherwise the DPLL will keep using the old
1673          * dividers, even though the register value does change.
1674          */
1675         I915_WRITE(reg, 0);
1676
1677         I915_WRITE(reg, dpll);
1678
1679         /* Wait for the clocks to stabilize. */
1680         POSTING_READ(reg);
1681         udelay(150);
1682
1683         if (INTEL_INFO(dev)->gen >= 4) {
1684                 I915_WRITE(DPLL_MD(crtc->pipe),
1685                            crtc->config->dpll_hw_state.dpll_md);
1686         } else {
1687                 /* The pixel multiplier can only be updated once the
1688                  * DPLL is enabled and the clocks are stable.
1689                  *
1690                  * So write it again.
1691                  */
1692                 I915_WRITE(reg, dpll);
1693         }
1694
1695         /* We do this three times for luck */
1696         I915_WRITE(reg, dpll);
1697         POSTING_READ(reg);
1698         udelay(150); /* wait for warmup */
1699         I915_WRITE(reg, dpll);
1700         POSTING_READ(reg);
1701         udelay(150); /* wait for warmup */
1702         I915_WRITE(reg, dpll);
1703         POSTING_READ(reg);
1704         udelay(150); /* wait for warmup */
1705 }
1706
1707 /**
1708  * i9xx_disable_pll - disable a PLL
1709  * @dev_priv: i915 private structure
1710  * @pipe: pipe PLL to disable
1711  *
1712  * Disable the PLL for @pipe, making sure the pipe is off first.
1713  *
1714  * Note!  This is for pre-ILK only.
1715  */
1716 static void i9xx_disable_pll(struct intel_crtc *crtc)
1717 {
1718         struct drm_device *dev = crtc->base.dev;
1719         struct drm_i915_private *dev_priv = dev->dev_private;
1720         enum pipe pipe = crtc->pipe;
1721
1722         /* Disable DVO 2x clock on both PLLs if necessary */
1723         if (IS_I830(dev) &&
1724             intel_pipe_has_type(crtc, INTEL_OUTPUT_DVO) &&
1725             !intel_num_dvo_pipes(dev)) {
1726                 I915_WRITE(DPLL(PIPE_B),
1727                            I915_READ(DPLL(PIPE_B)) & ~DPLL_DVO_2X_MODE);
1728                 I915_WRITE(DPLL(PIPE_A),
1729                            I915_READ(DPLL(PIPE_A)) & ~DPLL_DVO_2X_MODE);
1730         }
1731
1732         /* Don't disable pipe or pipe PLLs if needed */
1733         if ((pipe == PIPE_A && dev_priv->quirks & QUIRK_PIPEA_FORCE) ||
1734             (pipe == PIPE_B && dev_priv->quirks & QUIRK_PIPEB_FORCE))
1735                 return;
1736
1737         /* Make sure the pipe isn't still relying on us */
1738         assert_pipe_disabled(dev_priv, pipe);
1739
1740         I915_WRITE(DPLL(pipe), DPLL_VGA_MODE_DIS);
1741         POSTING_READ(DPLL(pipe));
1742 }
1743
1744 static void vlv_disable_pll(struct drm_i915_private *dev_priv, enum pipe pipe)
1745 {
1746         u32 val;
1747
1748         /* Make sure the pipe isn't still relying on us */
1749         assert_pipe_disabled(dev_priv, pipe);
1750
1751         val = DPLL_INTEGRATED_REF_CLK_VLV |
1752                 DPLL_REF_CLK_ENABLE_VLV | DPLL_VGA_MODE_DIS;
1753         if (pipe != PIPE_A)
1754                 val |= DPLL_INTEGRATED_CRI_CLK_VLV;
1755
1756         I915_WRITE(DPLL(pipe), val);
1757         POSTING_READ(DPLL(pipe));
1758 }
1759
1760 static void chv_disable_pll(struct drm_i915_private *dev_priv, enum pipe pipe)
1761 {
1762         enum dpio_channel port = vlv_pipe_to_channel(pipe);
1763         u32 val;
1764
1765         /* Make sure the pipe isn't still relying on us */
1766         assert_pipe_disabled(dev_priv, pipe);
1767
1768         val = DPLL_SSC_REF_CLK_CHV |
1769                 DPLL_REF_CLK_ENABLE_VLV | DPLL_VGA_MODE_DIS;
1770         if (pipe != PIPE_A)
1771                 val |= DPLL_INTEGRATED_CRI_CLK_VLV;
1772
1773         I915_WRITE(DPLL(pipe), val);
1774         POSTING_READ(DPLL(pipe));
1775
1776         mutex_lock(&dev_priv->sb_lock);
1777
1778         /* Disable 10bit clock to display controller */
1779         val = vlv_dpio_read(dev_priv, pipe, CHV_CMN_DW14(port));
1780         val &= ~DPIO_DCLKP_EN;
1781         vlv_dpio_write(dev_priv, pipe, CHV_CMN_DW14(port), val);
1782
1783         mutex_unlock(&dev_priv->sb_lock);
1784 }
1785
1786 void vlv_wait_port_ready(struct drm_i915_private *dev_priv,
1787                          struct intel_digital_port *dport,
1788                          unsigned int expected_mask)
1789 {
1790         u32 port_mask;
1791         i915_reg_t dpll_reg;
1792
1793         switch (dport->port) {
1794         case PORT_B:
1795                 port_mask = DPLL_PORTB_READY_MASK;
1796                 dpll_reg = DPLL(0);
1797                 break;
1798         case PORT_C:
1799                 port_mask = DPLL_PORTC_READY_MASK;
1800                 dpll_reg = DPLL(0);
1801                 expected_mask <<= 4;
1802                 break;
1803         case PORT_D:
1804                 port_mask = DPLL_PORTD_READY_MASK;
1805                 dpll_reg = DPIO_PHY_STATUS;
1806                 break;
1807         default:
1808                 BUG();
1809         }
1810
1811         if (wait_for((I915_READ(dpll_reg) & port_mask) == expected_mask, 1000))
1812                 WARN(1, "timed out waiting for port %c ready: got 0x%x, expected 0x%x\n",
1813                      port_name(dport->port), I915_READ(dpll_reg) & port_mask, expected_mask);
1814 }
1815
1816 static void ironlake_enable_pch_transcoder(struct drm_i915_private *dev_priv,
1817                                            enum pipe pipe)
1818 {
1819         struct drm_device *dev = dev_priv->dev;
1820         struct drm_crtc *crtc = dev_priv->pipe_to_crtc_mapping[pipe];
1821         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
1822         i915_reg_t reg;
1823         uint32_t val, pipeconf_val;
1824
1825         /* Make sure PCH DPLL is enabled */
1826         assert_shared_dpll_enabled(dev_priv, intel_crtc->config->shared_dpll);
1827
1828         /* FDI must be feeding us bits for PCH ports */
1829         assert_fdi_tx_enabled(dev_priv, pipe);
1830         assert_fdi_rx_enabled(dev_priv, pipe);
1831
1832         if (HAS_PCH_CPT(dev)) {
1833                 /* Workaround: Set the timing override bit before enabling the
1834                  * pch transcoder. */
1835                 reg = TRANS_CHICKEN2(pipe);
1836                 val = I915_READ(reg);
1837                 val |= TRANS_CHICKEN2_TIMING_OVERRIDE;
1838                 I915_WRITE(reg, val);
1839         }
1840
1841         reg = PCH_TRANSCONF(pipe);
1842         val = I915_READ(reg);
1843         pipeconf_val = I915_READ(PIPECONF(pipe));
1844
1845         if (HAS_PCH_IBX(dev_priv)) {
1846                 /*
1847                  * Make the BPC in transcoder be consistent with
1848                  * that in pipeconf reg. For HDMI we must use 8bpc
1849                  * here for both 8bpc and 12bpc.
1850                  */
1851                 val &= ~PIPECONF_BPC_MASK;
1852                 if (intel_pipe_has_type(intel_crtc, INTEL_OUTPUT_HDMI))
1853                         val |= PIPECONF_8BPC;
1854                 else
1855                         val |= pipeconf_val & PIPECONF_BPC_MASK;
1856         }
1857
1858         val &= ~TRANS_INTERLACE_MASK;
1859         if ((pipeconf_val & PIPECONF_INTERLACE_MASK) == PIPECONF_INTERLACED_ILK)
1860                 if (HAS_PCH_IBX(dev_priv) &&
1861                     intel_pipe_has_type(intel_crtc, INTEL_OUTPUT_SDVO))
1862                         val |= TRANS_LEGACY_INTERLACED_ILK;
1863                 else
1864                         val |= TRANS_INTERLACED;
1865         else
1866                 val |= TRANS_PROGRESSIVE;
1867
1868         I915_WRITE(reg, val | TRANS_ENABLE);
1869         if (wait_for(I915_READ(reg) & TRANS_STATE_ENABLE, 100))
1870                 DRM_ERROR("failed to enable transcoder %c\n", pipe_name(pipe));
1871 }
1872
1873 static void lpt_enable_pch_transcoder(struct drm_i915_private *dev_priv,
1874                                       enum transcoder cpu_transcoder)
1875 {
1876         u32 val, pipeconf_val;
1877
1878         /* FDI must be feeding us bits for PCH ports */
1879         assert_fdi_tx_enabled(dev_priv, (enum pipe) cpu_transcoder);
1880         assert_fdi_rx_enabled(dev_priv, TRANSCODER_A);
1881
1882         /* Workaround: set timing override bit. */
1883         val = I915_READ(TRANS_CHICKEN2(PIPE_A));
1884         val |= TRANS_CHICKEN2_TIMING_OVERRIDE;
1885         I915_WRITE(TRANS_CHICKEN2(PIPE_A), val);
1886
1887         val = TRANS_ENABLE;
1888         pipeconf_val = I915_READ(PIPECONF(cpu_transcoder));
1889
1890         if ((pipeconf_val & PIPECONF_INTERLACE_MASK_HSW) ==
1891             PIPECONF_INTERLACED_ILK)
1892                 val |= TRANS_INTERLACED;
1893         else
1894                 val |= TRANS_PROGRESSIVE;
1895
1896         I915_WRITE(LPT_TRANSCONF, val);
1897         if (wait_for(I915_READ(LPT_TRANSCONF) & TRANS_STATE_ENABLE, 100))
1898                 DRM_ERROR("Failed to enable PCH transcoder\n");
1899 }
1900
1901 static void ironlake_disable_pch_transcoder(struct drm_i915_private *dev_priv,
1902                                             enum pipe pipe)
1903 {
1904         struct drm_device *dev = dev_priv->dev;
1905         i915_reg_t reg;
1906         uint32_t val;
1907
1908         /* FDI relies on the transcoder */
1909         assert_fdi_tx_disabled(dev_priv, pipe);
1910         assert_fdi_rx_disabled(dev_priv, pipe);
1911
1912         /* Ports must be off as well */
1913         assert_pch_ports_disabled(dev_priv, pipe);
1914
1915         reg = PCH_TRANSCONF(pipe);
1916         val = I915_READ(reg);
1917         val &= ~TRANS_ENABLE;
1918         I915_WRITE(reg, val);
1919         /* wait for PCH transcoder off, transcoder state */
1920         if (wait_for((I915_READ(reg) & TRANS_STATE_ENABLE) == 0, 50))
1921                 DRM_ERROR("failed to disable transcoder %c\n", pipe_name(pipe));
1922
1923         if (HAS_PCH_CPT(dev)) {
1924                 /* Workaround: Clear the timing override chicken bit again. */
1925                 reg = TRANS_CHICKEN2(pipe);
1926                 val = I915_READ(reg);
1927                 val &= ~TRANS_CHICKEN2_TIMING_OVERRIDE;
1928                 I915_WRITE(reg, val);
1929         }
1930 }
1931
1932 static void lpt_disable_pch_transcoder(struct drm_i915_private *dev_priv)
1933 {
1934         u32 val;
1935
1936         val = I915_READ(LPT_TRANSCONF);
1937         val &= ~TRANS_ENABLE;
1938         I915_WRITE(LPT_TRANSCONF, val);
1939         /* wait for PCH transcoder off, transcoder state */
1940         if (wait_for((I915_READ(LPT_TRANSCONF) & TRANS_STATE_ENABLE) == 0, 50))
1941                 DRM_ERROR("Failed to disable PCH transcoder\n");
1942
1943         /* Workaround: clear timing override bit. */
1944         val = I915_READ(TRANS_CHICKEN2(PIPE_A));
1945         val &= ~TRANS_CHICKEN2_TIMING_OVERRIDE;
1946         I915_WRITE(TRANS_CHICKEN2(PIPE_A), val);
1947 }
1948
1949 /**
1950  * intel_enable_pipe - enable a pipe, asserting requirements
1951  * @crtc: crtc responsible for the pipe
1952  *
1953  * Enable @crtc's pipe, making sure that various hardware specific requirements
1954  * are met, if applicable, e.g. PLL enabled, LVDS pairs enabled, etc.
1955  */
1956 static void intel_enable_pipe(struct intel_crtc *crtc)
1957 {
1958         struct drm_device *dev = crtc->base.dev;
1959         struct drm_i915_private *dev_priv = dev->dev_private;
1960         enum pipe pipe = crtc->pipe;
1961         enum transcoder cpu_transcoder = crtc->config->cpu_transcoder;
1962         enum pipe pch_transcoder;
1963         i915_reg_t reg;
1964         u32 val;
1965
1966         DRM_DEBUG_KMS("enabling pipe %c\n", pipe_name(pipe));
1967
1968         assert_planes_disabled(dev_priv, pipe);
1969         assert_cursor_disabled(dev_priv, pipe);
1970         assert_sprites_disabled(dev_priv, pipe);
1971
1972         if (HAS_PCH_LPT(dev_priv))
1973                 pch_transcoder = TRANSCODER_A;
1974         else
1975                 pch_transcoder = pipe;
1976
1977         /*
1978          * A pipe without a PLL won't actually be able to drive bits from
1979          * a plane.  On ILK+ the pipe PLLs are integrated, so we don't
1980          * need the check.
1981          */
1982         if (HAS_GMCH_DISPLAY(dev_priv))
1983                 if (crtc->config->has_dsi_encoder)
1984                         assert_dsi_pll_enabled(dev_priv);
1985                 else
1986                         assert_pll_enabled(dev_priv, pipe);
1987         else {
1988                 if (crtc->config->has_pch_encoder) {
1989                         /* if driving the PCH, we need FDI enabled */
1990                         assert_fdi_rx_pll_enabled(dev_priv, pch_transcoder);
1991                         assert_fdi_tx_pll_enabled(dev_priv,
1992                                                   (enum pipe) cpu_transcoder);
1993                 }
1994                 /* FIXME: assert CPU port conditions for SNB+ */
1995         }
1996
1997         reg = PIPECONF(cpu_transcoder);
1998         val = I915_READ(reg);
1999         if (val & PIPECONF_ENABLE) {
2000                 WARN_ON(!((pipe == PIPE_A && dev_priv->quirks & QUIRK_PIPEA_FORCE) ||
2001                           (pipe == PIPE_B && dev_priv->quirks & QUIRK_PIPEB_FORCE)));
2002                 return;
2003         }
2004
2005         I915_WRITE(reg, val | PIPECONF_ENABLE);
2006         POSTING_READ(reg);
2007
2008         /*
2009          * Until the pipe starts DSL will read as 0, which would cause
2010          * an apparent vblank timestamp jump, which messes up also the
2011          * frame count when it's derived from the timestamps. So let's
2012          * wait for the pipe to start properly before we call
2013          * drm_crtc_vblank_on()
2014          */
2015         if (dev->max_vblank_count == 0 &&
2016             wait_for(intel_get_crtc_scanline(crtc) != crtc->scanline_offset, 50))
2017                 DRM_ERROR("pipe %c didn't start\n", pipe_name(pipe));
2018 }
2019
2020 /**
2021  * intel_disable_pipe - disable a pipe, asserting requirements
2022  * @crtc: crtc whose pipes is to be disabled
2023  *
2024  * Disable the pipe of @crtc, making sure that various hardware
2025  * specific requirements are met, if applicable, e.g. plane
2026  * disabled, panel fitter off, etc.
2027  *
2028  * Will wait until the pipe has shut down before returning.
2029  */
2030 static void intel_disable_pipe(struct intel_crtc *crtc)
2031 {
2032         struct drm_i915_private *dev_priv = crtc->base.dev->dev_private;
2033         enum transcoder cpu_transcoder = crtc->config->cpu_transcoder;
2034         enum pipe pipe = crtc->pipe;
2035         i915_reg_t reg;
2036         u32 val;
2037
2038         DRM_DEBUG_KMS("disabling pipe %c\n", pipe_name(pipe));
2039
2040         /*
2041          * Make sure planes won't keep trying to pump pixels to us,
2042          * or we might hang the display.
2043          */
2044         assert_planes_disabled(dev_priv, pipe);
2045         assert_cursor_disabled(dev_priv, pipe);
2046         assert_sprites_disabled(dev_priv, pipe);
2047
2048         reg = PIPECONF(cpu_transcoder);
2049         val = I915_READ(reg);
2050         if ((val & PIPECONF_ENABLE) == 0)
2051                 return;
2052
2053         /*
2054          * Double wide has implications for planes
2055          * so best keep it disabled when not needed.
2056          */
2057         if (crtc->config->double_wide)
2058                 val &= ~PIPECONF_DOUBLE_WIDE;
2059
2060         /* Don't disable pipe or pipe PLLs if needed */
2061         if (!(pipe == PIPE_A && dev_priv->quirks & QUIRK_PIPEA_FORCE) &&
2062             !(pipe == PIPE_B && dev_priv->quirks & QUIRK_PIPEB_FORCE))
2063                 val &= ~PIPECONF_ENABLE;
2064
2065         I915_WRITE(reg, val);
2066         if ((val & PIPECONF_ENABLE) == 0)
2067                 intel_wait_for_pipe_off(crtc);
2068 }
2069
2070 static bool need_vtd_wa(struct drm_device *dev)
2071 {
2072 #ifdef CONFIG_INTEL_IOMMU
2073         if (INTEL_INFO(dev)->gen >= 6 && intel_iommu_gfx_mapped)
2074                 return true;
2075 #endif
2076         return false;
2077 }
2078
2079 static unsigned int intel_tile_size(const struct drm_i915_private *dev_priv)
2080 {
2081         return IS_GEN2(dev_priv) ? 2048 : 4096;
2082 }
2083
2084 static unsigned int intel_tile_width_bytes(const struct drm_i915_private *dev_priv,
2085                                            uint64_t fb_modifier, unsigned int cpp)
2086 {
2087         switch (fb_modifier) {
2088         case DRM_FORMAT_MOD_NONE:
2089                 return cpp;
2090         case I915_FORMAT_MOD_X_TILED:
2091                 if (IS_GEN2(dev_priv))
2092                         return 128;
2093                 else
2094                         return 512;
2095         case I915_FORMAT_MOD_Y_TILED:
2096                 if (IS_GEN2(dev_priv) || HAS_128_BYTE_Y_TILING(dev_priv))
2097                         return 128;
2098                 else
2099                         return 512;
2100         case I915_FORMAT_MOD_Yf_TILED:
2101                 switch (cpp) {
2102                 case 1:
2103                         return 64;
2104                 case 2:
2105                 case 4:
2106                         return 128;
2107                 case 8:
2108                 case 16:
2109                         return 256;
2110                 default:
2111                         MISSING_CASE(cpp);
2112                         return cpp;
2113                 }
2114                 break;
2115         default:
2116                 MISSING_CASE(fb_modifier);
2117                 return cpp;
2118         }
2119 }
2120
2121 unsigned int intel_tile_height(const struct drm_i915_private *dev_priv,
2122                                uint64_t fb_modifier, unsigned int cpp)
2123 {
2124         if (fb_modifier == DRM_FORMAT_MOD_NONE)
2125                 return 1;
2126         else
2127                 return intel_tile_size(dev_priv) /
2128                         intel_tile_width_bytes(dev_priv, fb_modifier, cpp);
2129 }
2130
2131 /* Return the tile dimensions in pixel units */
2132 static void intel_tile_dims(const struct drm_i915_private *dev_priv,
2133                             unsigned int *tile_width,
2134                             unsigned int *tile_height,
2135                             uint64_t fb_modifier,
2136                             unsigned int cpp)
2137 {
2138         unsigned int tile_width_bytes =
2139                 intel_tile_width_bytes(dev_priv, fb_modifier, cpp);
2140
2141         *tile_width = tile_width_bytes / cpp;
2142         *tile_height = intel_tile_size(dev_priv) / tile_width_bytes;
2143 }
2144
2145 unsigned int
2146 intel_fb_align_height(struct drm_device *dev, unsigned int height,
2147                       uint32_t pixel_format, uint64_t fb_modifier)
2148 {
2149         unsigned int cpp = drm_format_plane_cpp(pixel_format, 0);
2150         unsigned int tile_height = intel_tile_height(to_i915(dev), fb_modifier, cpp);
2151
2152         return ALIGN(height, tile_height);
2153 }
2154
2155 unsigned int intel_rotation_info_size(const struct intel_rotation_info *rot_info)
2156 {
2157         unsigned int size = 0;
2158         int i;
2159
2160         for (i = 0 ; i < ARRAY_SIZE(rot_info->plane); i++)
2161                 size += rot_info->plane[i].width * rot_info->plane[i].height;
2162
2163         return size;
2164 }
2165
2166 static void
2167 intel_fill_fb_ggtt_view(struct i915_ggtt_view *view,
2168                         const struct drm_framebuffer *fb,
2169                         unsigned int rotation)
2170 {
2171         if (intel_rotation_90_or_270(rotation)) {
2172                 *view = i915_ggtt_view_rotated;
2173                 view->params.rotated = to_intel_framebuffer(fb)->rot_info;
2174         } else {
2175                 *view = i915_ggtt_view_normal;
2176         }
2177 }
2178
2179 static void
2180 intel_fill_fb_info(struct drm_i915_private *dev_priv,
2181                    struct drm_framebuffer *fb)
2182 {
2183         struct intel_rotation_info *info = &to_intel_framebuffer(fb)->rot_info;
2184         unsigned int tile_size, tile_width, tile_height, cpp;
2185
2186         tile_size = intel_tile_size(dev_priv);
2187
2188         cpp = drm_format_plane_cpp(fb->pixel_format, 0);
2189         intel_tile_dims(dev_priv, &tile_width, &tile_height,
2190                         fb->modifier[0], cpp);
2191
2192         info->plane[0].width = DIV_ROUND_UP(fb->pitches[0], tile_width * cpp);
2193         info->plane[0].height = DIV_ROUND_UP(fb->height, tile_height);
2194
2195         if (info->pixel_format == DRM_FORMAT_NV12) {
2196                 cpp = drm_format_plane_cpp(fb->pixel_format, 1);
2197                 intel_tile_dims(dev_priv, &tile_width, &tile_height,
2198                                 fb->modifier[1], cpp);
2199
2200                 info->uv_offset = fb->offsets[1];
2201                 info->plane[1].width = DIV_ROUND_UP(fb->pitches[1], tile_width * cpp);
2202                 info->plane[1].height = DIV_ROUND_UP(fb->height / 2, tile_height);
2203         }
2204 }
2205
2206 static unsigned int intel_linear_alignment(const struct drm_i915_private *dev_priv)
2207 {
2208         if (INTEL_INFO(dev_priv)->gen >= 9)
2209                 return 256 * 1024;
2210         else if (IS_BROADWATER(dev_priv) || IS_CRESTLINE(dev_priv) ||
2211                  IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv))
2212                 return 128 * 1024;
2213         else if (INTEL_INFO(dev_priv)->gen >= 4)
2214                 return 4 * 1024;
2215         else
2216                 return 0;
2217 }
2218
2219 static unsigned int intel_surf_alignment(const struct drm_i915_private *dev_priv,
2220                                          uint64_t fb_modifier)
2221 {
2222         switch (fb_modifier) {
2223         case DRM_FORMAT_MOD_NONE:
2224                 return intel_linear_alignment(dev_priv);
2225         case I915_FORMAT_MOD_X_TILED:
2226                 if (INTEL_INFO(dev_priv)->gen >= 9)
2227                         return 256 * 1024;
2228                 return 0;
2229         case I915_FORMAT_MOD_Y_TILED:
2230         case I915_FORMAT_MOD_Yf_TILED:
2231                 return 1 * 1024 * 1024;
2232         default:
2233                 MISSING_CASE(fb_modifier);
2234                 return 0;
2235         }
2236 }
2237
2238 int
2239 intel_pin_and_fence_fb_obj(struct drm_framebuffer *fb,
2240                            unsigned int rotation)
2241 {
2242         struct drm_device *dev = fb->dev;
2243         struct drm_i915_private *dev_priv = dev->dev_private;
2244         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
2245         struct i915_ggtt_view view;
2246         u32 alignment;
2247         int ret;
2248
2249         WARN_ON(!mutex_is_locked(&dev->struct_mutex));
2250
2251         alignment = intel_surf_alignment(dev_priv, fb->modifier[0]);
2252
2253         intel_fill_fb_ggtt_view(&view, fb, rotation);
2254
2255         /* Note that the w/a also requires 64 PTE of padding following the
2256          * bo. We currently fill all unused PTE with the shadow page and so
2257          * we should always have valid PTE following the scanout preventing
2258          * the VT-d warning.
2259          */
2260         if (need_vtd_wa(dev) && alignment < 256 * 1024)
2261                 alignment = 256 * 1024;
2262
2263         /*
2264          * Global gtt pte registers are special registers which actually forward
2265          * writes to a chunk of system memory. Which means that there is no risk
2266          * that the register values disappear as soon as we call
2267          * intel_runtime_pm_put(), so it is correct to wrap only the
2268          * pin/unpin/fence and not more.
2269          */
2270         intel_runtime_pm_get(dev_priv);
2271
2272         ret = i915_gem_object_pin_to_display_plane(obj, alignment,
2273                                                    &view);
2274         if (ret)
2275                 goto err_pm;
2276
2277         /* Install a fence for tiled scan-out. Pre-i965 always needs a
2278          * fence, whereas 965+ only requires a fence if using
2279          * framebuffer compression.  For simplicity, we always install
2280          * a fence as the cost is not that onerous.
2281          */
2282         if (view.type == I915_GGTT_VIEW_NORMAL) {
2283                 ret = i915_gem_object_get_fence(obj);
2284                 if (ret == -EDEADLK) {
2285                         /*
2286                          * -EDEADLK means there are no free fences
2287                          * no pending flips.
2288                          *
2289                          * This is propagated to atomic, but it uses
2290                          * -EDEADLK to force a locking recovery, so
2291                          * change the returned error to -EBUSY.
2292                          */
2293                         ret = -EBUSY;
2294                         goto err_unpin;
2295                 } else if (ret)
2296                         goto err_unpin;
2297
2298                 i915_gem_object_pin_fence(obj);
2299         }
2300
2301         intel_runtime_pm_put(dev_priv);
2302         return 0;
2303
2304 err_unpin:
2305         i915_gem_object_unpin_from_display_plane(obj, &view);
2306 err_pm:
2307         intel_runtime_pm_put(dev_priv);
2308         return ret;
2309 }
2310
2311 void intel_unpin_fb_obj(struct drm_framebuffer *fb, unsigned int rotation)
2312 {
2313         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
2314         struct i915_ggtt_view view;
2315
2316         WARN_ON(!mutex_is_locked(&obj->base.dev->struct_mutex));
2317
2318         intel_fill_fb_ggtt_view(&view, fb, rotation);
2319
2320         if (view.type == I915_GGTT_VIEW_NORMAL)
2321                 i915_gem_object_unpin_fence(obj);
2322
2323         i915_gem_object_unpin_from_display_plane(obj, &view);
2324 }
2325
2326 /*
2327  * Adjust the tile offset by moving the difference into
2328  * the x/y offsets.
2329  *
2330  * Input tile dimensions and pitch must already be
2331  * rotated to match x and y, and in pixel units.
2332  */
2333 static u32 intel_adjust_tile_offset(int *x, int *y,
2334                                     unsigned int tile_width,
2335                                     unsigned int tile_height,
2336                                     unsigned int tile_size,
2337                                     unsigned int pitch_tiles,
2338                                     u32 old_offset,
2339                                     u32 new_offset)
2340 {
2341         unsigned int tiles;
2342
2343         WARN_ON(old_offset & (tile_size - 1));
2344         WARN_ON(new_offset & (tile_size - 1));
2345         WARN_ON(new_offset > old_offset);
2346
2347         tiles = (old_offset - new_offset) / tile_size;
2348
2349         *y += tiles / pitch_tiles * tile_height;
2350         *x += tiles % pitch_tiles * tile_width;
2351
2352         return new_offset;
2353 }
2354
2355 /*
2356  * Computes the linear offset to the base tile and adjusts
2357  * x, y. bytes per pixel is assumed to be a power-of-two.
2358  *
2359  * In the 90/270 rotated case, x and y are assumed
2360  * to be already rotated to match the rotated GTT view, and
2361  * pitch is the tile_height aligned framebuffer height.
2362  */
2363 u32 intel_compute_tile_offset(int *x, int *y,
2364                               const struct drm_framebuffer *fb, int plane,
2365                               unsigned int pitch,
2366                               unsigned int rotation)
2367 {
2368         const struct drm_i915_private *dev_priv = to_i915(fb->dev);
2369         uint64_t fb_modifier = fb->modifier[plane];
2370         unsigned int cpp = drm_format_plane_cpp(fb->pixel_format, plane);
2371         u32 offset, offset_aligned, alignment;
2372
2373         alignment = intel_surf_alignment(dev_priv, fb_modifier);
2374         if (alignment)
2375                 alignment--;
2376
2377         if (fb_modifier != DRM_FORMAT_MOD_NONE) {
2378                 unsigned int tile_size, tile_width, tile_height;
2379                 unsigned int tile_rows, tiles, pitch_tiles;
2380
2381                 tile_size = intel_tile_size(dev_priv);
2382                 intel_tile_dims(dev_priv, &tile_width, &tile_height,
2383                                 fb_modifier, cpp);
2384
2385                 if (intel_rotation_90_or_270(rotation)) {
2386                         pitch_tiles = pitch / tile_height;
2387                         swap(tile_width, tile_height);
2388                 } else {
2389                         pitch_tiles = pitch / (tile_width * cpp);
2390                 }
2391
2392                 tile_rows = *y / tile_height;
2393                 *y %= tile_height;
2394
2395                 tiles = *x / tile_width;
2396                 *x %= tile_width;
2397
2398                 offset = (tile_rows * pitch_tiles + tiles) * tile_size;
2399                 offset_aligned = offset & ~alignment;
2400
2401                 intel_adjust_tile_offset(x, y, tile_width, tile_height,
2402                                          tile_size, pitch_tiles,
2403                                          offset, offset_aligned);
2404         } else {
2405                 offset = *y * pitch + *x * cpp;
2406                 offset_aligned = offset & ~alignment;
2407
2408                 *y = (offset & alignment) / pitch;
2409                 *x = ((offset & alignment) - *y * pitch) / cpp;
2410         }
2411
2412         return offset_aligned;
2413 }
2414
2415 static int i9xx_format_to_fourcc(int format)
2416 {
2417         switch (format) {
2418         case DISPPLANE_8BPP:
2419                 return DRM_FORMAT_C8;
2420         case DISPPLANE_BGRX555:
2421                 return DRM_FORMAT_XRGB1555;
2422         case DISPPLANE_BGRX565:
2423                 return DRM_FORMAT_RGB565;
2424         default:
2425         case DISPPLANE_BGRX888:
2426                 return DRM_FORMAT_XRGB8888;
2427         case DISPPLANE_RGBX888:
2428                 return DRM_FORMAT_XBGR8888;
2429         case DISPPLANE_BGRX101010:
2430                 return DRM_FORMAT_XRGB2101010;
2431         case DISPPLANE_RGBX101010:
2432                 return DRM_FORMAT_XBGR2101010;
2433         }
2434 }
2435
2436 static int skl_format_to_fourcc(int format, bool rgb_order, bool alpha)
2437 {
2438         switch (format) {
2439         case PLANE_CTL_FORMAT_RGB_565:
2440                 return DRM_FORMAT_RGB565;
2441         default:
2442         case PLANE_CTL_FORMAT_XRGB_8888:
2443                 if (rgb_order) {
2444                         if (alpha)
2445                                 return DRM_FORMAT_ABGR8888;
2446                         else
2447                                 return DRM_FORMAT_XBGR8888;
2448                 } else {
2449                         if (alpha)
2450                                 return DRM_FORMAT_ARGB8888;
2451                         else
2452                                 return DRM_FORMAT_XRGB8888;
2453                 }
2454         case PLANE_CTL_FORMAT_XRGB_2101010:
2455                 if (rgb_order)
2456                         return DRM_FORMAT_XBGR2101010;
2457                 else
2458                         return DRM_FORMAT_XRGB2101010;
2459         }
2460 }
2461
2462 static bool
2463 intel_alloc_initial_plane_obj(struct intel_crtc *crtc,
2464                               struct intel_initial_plane_config *plane_config)
2465 {
2466         struct drm_device *dev = crtc->base.dev;
2467         struct drm_i915_private *dev_priv = to_i915(dev);
2468         struct i915_ggtt *ggtt = &dev_priv->ggtt;
2469         struct drm_i915_gem_object *obj = NULL;
2470         struct drm_mode_fb_cmd2 mode_cmd = { 0 };
2471         struct drm_framebuffer *fb = &plane_config->fb->base;
2472         u32 base_aligned = round_down(plane_config->base, PAGE_SIZE);
2473         u32 size_aligned = round_up(plane_config->base + plane_config->size,
2474                                     PAGE_SIZE);
2475
2476         size_aligned -= base_aligned;
2477
2478         if (plane_config->size == 0)
2479                 return false;
2480
2481         /* If the FB is too big, just don't use it since fbdev is not very
2482          * important and we should probably use that space with FBC or other
2483          * features. */
2484         if (size_aligned * 2 > ggtt->stolen_usable_size)
2485                 return false;
2486
2487         mutex_lock(&dev->struct_mutex);
2488
2489         obj = i915_gem_object_create_stolen_for_preallocated(dev,
2490                                                              base_aligned,
2491                                                              base_aligned,
2492                                                              size_aligned);
2493         if (!obj) {
2494                 mutex_unlock(&dev->struct_mutex);
2495                 return false;
2496         }
2497
2498         obj->tiling_mode = plane_config->tiling;
2499         if (obj->tiling_mode == I915_TILING_X)
2500                 obj->stride = fb->pitches[0];
2501
2502         mode_cmd.pixel_format = fb->pixel_format;
2503         mode_cmd.width = fb->width;
2504         mode_cmd.height = fb->height;
2505         mode_cmd.pitches[0] = fb->pitches[0];
2506         mode_cmd.modifier[0] = fb->modifier[0];
2507         mode_cmd.flags = DRM_MODE_FB_MODIFIERS;
2508
2509         if (intel_framebuffer_init(dev, to_intel_framebuffer(fb),
2510                                    &mode_cmd, obj)) {
2511                 DRM_DEBUG_KMS("intel fb init failed\n");
2512                 goto out_unref_obj;
2513         }
2514
2515         mutex_unlock(&dev->struct_mutex);
2516
2517         DRM_DEBUG_KMS("initial plane fb obj %p\n", obj);
2518         return true;
2519
2520 out_unref_obj:
2521         drm_gem_object_unreference(&obj->base);
2522         mutex_unlock(&dev->struct_mutex);
2523         return false;
2524 }
2525
2526 static void
2527 intel_find_initial_plane_obj(struct intel_crtc *intel_crtc,
2528                              struct intel_initial_plane_config *plane_config)
2529 {
2530         struct drm_device *dev = intel_crtc->base.dev;
2531         struct drm_i915_private *dev_priv = dev->dev_private;
2532         struct drm_crtc *c;
2533         struct intel_crtc *i;
2534         struct drm_i915_gem_object *obj;
2535         struct drm_plane *primary = intel_crtc->base.primary;
2536         struct drm_plane_state *plane_state = primary->state;
2537         struct drm_crtc_state *crtc_state = intel_crtc->base.state;
2538         struct intel_plane *intel_plane = to_intel_plane(primary);
2539         struct intel_plane_state *intel_state =
2540                 to_intel_plane_state(plane_state);
2541         struct drm_framebuffer *fb;
2542
2543         if (!plane_config->fb)
2544                 return;
2545
2546         if (intel_alloc_initial_plane_obj(intel_crtc, plane_config)) {
2547                 fb = &plane_config->fb->base;
2548                 goto valid_fb;
2549         }
2550
2551         kfree(plane_config->fb);
2552
2553         /*
2554          * Failed to alloc the obj, check to see if we should share
2555          * an fb with another CRTC instead
2556          */
2557         for_each_crtc(dev, c) {
2558                 i = to_intel_crtc(c);
2559
2560                 if (c == &intel_crtc->base)
2561                         continue;
2562
2563                 if (!i->active)
2564                         continue;
2565
2566                 fb = c->primary->fb;
2567                 if (!fb)
2568                         continue;
2569
2570                 obj = intel_fb_obj(fb);
2571                 if (i915_gem_obj_ggtt_offset(obj) == plane_config->base) {
2572                         drm_framebuffer_reference(fb);
2573                         goto valid_fb;
2574                 }
2575         }
2576
2577         /*
2578          * We've failed to reconstruct the BIOS FB.  Current display state
2579          * indicates that the primary plane is visible, but has a NULL FB,
2580          * which will lead to problems later if we don't fix it up.  The
2581          * simplest solution is to just disable the primary plane now and
2582          * pretend the BIOS never had it enabled.
2583          */
2584         to_intel_plane_state(plane_state)->visible = false;
2585         crtc_state->plane_mask &= ~(1 << drm_plane_index(primary));
2586         intel_pre_disable_primary_noatomic(&intel_crtc->base);
2587         intel_plane->disable_plane(primary, &intel_crtc->base);
2588
2589         return;
2590
2591 valid_fb:
2592         plane_state->src_x = 0;
2593         plane_state->src_y = 0;
2594         plane_state->src_w = fb->width << 16;
2595         plane_state->src_h = fb->height << 16;
2596
2597         plane_state->crtc_x = 0;
2598         plane_state->crtc_y = 0;
2599         plane_state->crtc_w = fb->width;
2600         plane_state->crtc_h = fb->height;
2601
2602         intel_state->src.x1 = plane_state->src_x;
2603         intel_state->src.y1 = plane_state->src_y;
2604         intel_state->src.x2 = plane_state->src_x + plane_state->src_w;
2605         intel_state->src.y2 = plane_state->src_y + plane_state->src_h;
2606         intel_state->dst.x1 = plane_state->crtc_x;
2607         intel_state->dst.y1 = plane_state->crtc_y;
2608         intel_state->dst.x2 = plane_state->crtc_x + plane_state->crtc_w;
2609         intel_state->dst.y2 = plane_state->crtc_y + plane_state->crtc_h;
2610
2611         obj = intel_fb_obj(fb);
2612         if (obj->tiling_mode != I915_TILING_NONE)
2613                 dev_priv->preserve_bios_swizzle = true;
2614
2615         drm_framebuffer_reference(fb);
2616         primary->fb = primary->state->fb = fb;
2617         primary->crtc = primary->state->crtc = &intel_crtc->base;
2618         intel_crtc->base.state->plane_mask |= (1 << drm_plane_index(primary));
2619         obj->frontbuffer_bits |= to_intel_plane(primary)->frontbuffer_bit;
2620 }
2621
2622 static void i9xx_update_primary_plane(struct drm_plane *primary,
2623                                       const struct intel_crtc_state *crtc_state,
2624                                       const struct intel_plane_state *plane_state)
2625 {
2626         struct drm_device *dev = primary->dev;
2627         struct drm_i915_private *dev_priv = dev->dev_private;
2628         struct intel_crtc *intel_crtc = to_intel_crtc(crtc_state->base.crtc);
2629         struct drm_framebuffer *fb = plane_state->base.fb;
2630         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
2631         int plane = intel_crtc->plane;
2632         u32 linear_offset;
2633         u32 dspcntr;
2634         i915_reg_t reg = DSPCNTR(plane);
2635         unsigned int rotation = plane_state->base.rotation;
2636         int cpp = drm_format_plane_cpp(fb->pixel_format, 0);
2637         int x = plane_state->src.x1 >> 16;
2638         int y = plane_state->src.y1 >> 16;
2639
2640         dspcntr = DISPPLANE_GAMMA_ENABLE;
2641
2642         dspcntr |= DISPLAY_PLANE_ENABLE;
2643
2644         if (INTEL_INFO(dev)->gen < 4) {
2645                 if (intel_crtc->pipe == PIPE_B)
2646                         dspcntr |= DISPPLANE_SEL_PIPE_B;
2647
2648                 /* pipesrc and dspsize control the size that is scaled from,
2649                  * which should always be the user's requested size.
2650                  */
2651                 I915_WRITE(DSPSIZE(plane),
2652                            ((crtc_state->pipe_src_h - 1) << 16) |
2653                            (crtc_state->pipe_src_w - 1));
2654                 I915_WRITE(DSPPOS(plane), 0);
2655         } else if (IS_CHERRYVIEW(dev) && plane == PLANE_B) {
2656                 I915_WRITE(PRIMSIZE(plane),
2657                            ((crtc_state->pipe_src_h - 1) << 16) |
2658                            (crtc_state->pipe_src_w - 1));
2659                 I915_WRITE(PRIMPOS(plane), 0);
2660                 I915_WRITE(PRIMCNSTALPHA(plane), 0);
2661         }
2662
2663         switch (fb->pixel_format) {
2664         case DRM_FORMAT_C8:
2665                 dspcntr |= DISPPLANE_8BPP;
2666                 break;
2667         case DRM_FORMAT_XRGB1555:
2668                 dspcntr |= DISPPLANE_BGRX555;
2669                 break;
2670         case DRM_FORMAT_RGB565:
2671                 dspcntr |= DISPPLANE_BGRX565;
2672                 break;
2673         case DRM_FORMAT_XRGB8888:
2674                 dspcntr |= DISPPLANE_BGRX888;
2675                 break;
2676         case DRM_FORMAT_XBGR8888:
2677                 dspcntr |= DISPPLANE_RGBX888;
2678                 break;
2679         case DRM_FORMAT_XRGB2101010:
2680                 dspcntr |= DISPPLANE_BGRX101010;
2681                 break;
2682         case DRM_FORMAT_XBGR2101010:
2683                 dspcntr |= DISPPLANE_RGBX101010;
2684                 break;
2685         default:
2686                 BUG();
2687         }
2688
2689         if (INTEL_INFO(dev)->gen >= 4 &&
2690             obj->tiling_mode != I915_TILING_NONE)
2691                 dspcntr |= DISPPLANE_TILED;
2692
2693         if (IS_G4X(dev))
2694                 dspcntr |= DISPPLANE_TRICKLE_FEED_DISABLE;
2695
2696         linear_offset = y * fb->pitches[0] + x * cpp;
2697
2698         if (INTEL_INFO(dev)->gen >= 4) {
2699                 intel_crtc->dspaddr_offset =
2700                         intel_compute_tile_offset(&x, &y, fb, 0,
2701                                                   fb->pitches[0], rotation);
2702                 linear_offset -= intel_crtc->dspaddr_offset;
2703         } else {
2704                 intel_crtc->dspaddr_offset = linear_offset;
2705         }
2706
2707         if (rotation == BIT(DRM_ROTATE_180)) {
2708                 dspcntr |= DISPPLANE_ROTATE_180;
2709
2710                 x += (crtc_state->pipe_src_w - 1);
2711                 y += (crtc_state->pipe_src_h - 1);
2712
2713                 /* Finding the last pixel of the last line of the display
2714                 data and adding to linear_offset*/
2715                 linear_offset +=
2716                         (crtc_state->pipe_src_h - 1) * fb->pitches[0] +
2717                         (crtc_state->pipe_src_w - 1) * cpp;
2718         }
2719
2720         intel_crtc->adjusted_x = x;
2721         intel_crtc->adjusted_y = y;
2722
2723         I915_WRITE(reg, dspcntr);
2724
2725         I915_WRITE(DSPSTRIDE(plane), fb->pitches[0]);
2726         if (INTEL_INFO(dev)->gen >= 4) {
2727                 I915_WRITE(DSPSURF(plane),
2728                            i915_gem_obj_ggtt_offset(obj) + intel_crtc->dspaddr_offset);
2729                 I915_WRITE(DSPTILEOFF(plane), (y << 16) | x);
2730                 I915_WRITE(DSPLINOFF(plane), linear_offset);
2731         } else
2732                 I915_WRITE(DSPADDR(plane), i915_gem_obj_ggtt_offset(obj) + linear_offset);
2733         POSTING_READ(reg);
2734 }
2735
2736 static void i9xx_disable_primary_plane(struct drm_plane *primary,
2737                                        struct drm_crtc *crtc)
2738 {
2739         struct drm_device *dev = crtc->dev;
2740         struct drm_i915_private *dev_priv = dev->dev_private;
2741         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
2742         int plane = intel_crtc->plane;
2743
2744         I915_WRITE(DSPCNTR(plane), 0);
2745         if (INTEL_INFO(dev_priv)->gen >= 4)
2746                 I915_WRITE(DSPSURF(plane), 0);
2747         else
2748                 I915_WRITE(DSPADDR(plane), 0);
2749         POSTING_READ(DSPCNTR(plane));
2750 }
2751
2752 static void ironlake_update_primary_plane(struct drm_plane *primary,
2753                                           const struct intel_crtc_state *crtc_state,
2754                                           const struct intel_plane_state *plane_state)
2755 {
2756         struct drm_device *dev = primary->dev;
2757         struct drm_i915_private *dev_priv = dev->dev_private;
2758         struct intel_crtc *intel_crtc = to_intel_crtc(crtc_state->base.crtc);
2759         struct drm_framebuffer *fb = plane_state->base.fb;
2760         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
2761         int plane = intel_crtc->plane;
2762         u32 linear_offset;
2763         u32 dspcntr;
2764         i915_reg_t reg = DSPCNTR(plane);
2765         unsigned int rotation = plane_state->base.rotation;
2766         int cpp = drm_format_plane_cpp(fb->pixel_format, 0);
2767         int x = plane_state->src.x1 >> 16;
2768         int y = plane_state->src.y1 >> 16;
2769
2770         dspcntr = DISPPLANE_GAMMA_ENABLE;
2771         dspcntr |= DISPLAY_PLANE_ENABLE;
2772
2773         if (IS_HASWELL(dev) || IS_BROADWELL(dev))
2774                 dspcntr |= DISPPLANE_PIPE_CSC_ENABLE;
2775
2776         switch (fb->pixel_format) {
2777         case DRM_FORMAT_C8:
2778                 dspcntr |= DISPPLANE_8BPP;
2779                 break;
2780         case DRM_FORMAT_RGB565:
2781                 dspcntr |= DISPPLANE_BGRX565;
2782                 break;
2783         case DRM_FORMAT_XRGB8888:
2784                 dspcntr |= DISPPLANE_BGRX888;
2785                 break;
2786         case DRM_FORMAT_XBGR8888:
2787                 dspcntr |= DISPPLANE_RGBX888;
2788                 break;
2789         case DRM_FORMAT_XRGB2101010:
2790                 dspcntr |= DISPPLANE_BGRX101010;
2791                 break;
2792         case DRM_FORMAT_XBGR2101010:
2793                 dspcntr |= DISPPLANE_RGBX101010;
2794                 break;
2795         default:
2796                 BUG();
2797         }
2798
2799         if (obj->tiling_mode != I915_TILING_NONE)
2800                 dspcntr |= DISPPLANE_TILED;
2801
2802         if (!IS_HASWELL(dev) && !IS_BROADWELL(dev))
2803                 dspcntr |= DISPPLANE_TRICKLE_FEED_DISABLE;
2804
2805         linear_offset = y * fb->pitches[0] + x * cpp;
2806         intel_crtc->dspaddr_offset =
2807                 intel_compute_tile_offset(&x, &y, fb, 0,
2808                                           fb->pitches[0], rotation);
2809         linear_offset -= intel_crtc->dspaddr_offset;
2810         if (rotation == BIT(DRM_ROTATE_180)) {
2811                 dspcntr |= DISPPLANE_ROTATE_180;
2812
2813                 if (!IS_HASWELL(dev) && !IS_BROADWELL(dev)) {
2814                         x += (crtc_state->pipe_src_w - 1);
2815                         y += (crtc_state->pipe_src_h - 1);
2816
2817                         /* Finding the last pixel of the last line of the display
2818                         data and adding to linear_offset*/
2819                         linear_offset +=
2820                                 (crtc_state->pipe_src_h - 1) * fb->pitches[0] +
2821                                 (crtc_state->pipe_src_w - 1) * cpp;
2822                 }
2823         }
2824
2825         intel_crtc->adjusted_x = x;
2826         intel_crtc->adjusted_y = y;
2827
2828         I915_WRITE(reg, dspcntr);
2829
2830         I915_WRITE(DSPSTRIDE(plane), fb->pitches[0]);
2831         I915_WRITE(DSPSURF(plane),
2832                    i915_gem_obj_ggtt_offset(obj) + intel_crtc->dspaddr_offset);
2833         if (IS_HASWELL(dev) || IS_BROADWELL(dev)) {
2834                 I915_WRITE(DSPOFFSET(plane), (y << 16) | x);
2835         } else {
2836                 I915_WRITE(DSPTILEOFF(plane), (y << 16) | x);
2837                 I915_WRITE(DSPLINOFF(plane), linear_offset);
2838         }
2839         POSTING_READ(reg);
2840 }
2841
2842 u32 intel_fb_stride_alignment(const struct drm_i915_private *dev_priv,
2843                               uint64_t fb_modifier, uint32_t pixel_format)
2844 {
2845         if (fb_modifier == DRM_FORMAT_MOD_NONE) {
2846                 return 64;
2847         } else {
2848                 int cpp = drm_format_plane_cpp(pixel_format, 0);
2849
2850                 return intel_tile_width_bytes(dev_priv, fb_modifier, cpp);
2851         }
2852 }
2853
2854 u32 intel_plane_obj_offset(struct intel_plane *intel_plane,
2855                            struct drm_i915_gem_object *obj,
2856                            unsigned int plane)
2857 {
2858         struct i915_ggtt_view view;
2859         struct i915_vma *vma;
2860         u64 offset;
2861
2862         intel_fill_fb_ggtt_view(&view, intel_plane->base.state->fb,
2863                                 intel_plane->base.state->rotation);
2864
2865         vma = i915_gem_obj_to_ggtt_view(obj, &view);
2866         if (WARN(!vma, "ggtt vma for display object not found! (view=%u)\n",
2867                 view.type))
2868                 return -1;
2869
2870         offset = vma->node.start;
2871
2872         if (plane == 1) {
2873                 offset += vma->ggtt_view.params.rotated.uv_start_page *
2874                           PAGE_SIZE;
2875         }
2876
2877         WARN_ON(upper_32_bits(offset));
2878
2879         return lower_32_bits(offset);
2880 }
2881
2882 static void skl_detach_scaler(struct intel_crtc *intel_crtc, int id)
2883 {
2884         struct drm_device *dev = intel_crtc->base.dev;
2885         struct drm_i915_private *dev_priv = dev->dev_private;
2886
2887         I915_WRITE(SKL_PS_CTRL(intel_crtc->pipe, id), 0);
2888         I915_WRITE(SKL_PS_WIN_POS(intel_crtc->pipe, id), 0);
2889         I915_WRITE(SKL_PS_WIN_SZ(intel_crtc->pipe, id), 0);
2890 }
2891
2892 /*
2893  * This function detaches (aka. unbinds) unused scalers in hardware
2894  */
2895 static void skl_detach_scalers(struct intel_crtc *intel_crtc)
2896 {
2897         struct intel_crtc_scaler_state *scaler_state;
2898         int i;
2899
2900         scaler_state = &intel_crtc->config->scaler_state;
2901
2902         /* loop through and disable scalers that aren't in use */
2903         for (i = 0; i < intel_crtc->num_scalers; i++) {
2904                 if (!scaler_state->scalers[i].in_use)
2905                         skl_detach_scaler(intel_crtc, i);
2906         }
2907 }
2908
2909 u32 skl_plane_ctl_format(uint32_t pixel_format)
2910 {
2911         switch (pixel_format) {
2912         case DRM_FORMAT_C8:
2913                 return PLANE_CTL_FORMAT_INDEXED;
2914         case DRM_FORMAT_RGB565:
2915                 return PLANE_CTL_FORMAT_RGB_565;
2916         case DRM_FORMAT_XBGR8888:
2917                 return PLANE_CTL_FORMAT_XRGB_8888 | PLANE_CTL_ORDER_RGBX;
2918         case DRM_FORMAT_XRGB8888:
2919                 return PLANE_CTL_FORMAT_XRGB_8888;
2920         /*
2921          * XXX: For ARBG/ABGR formats we default to expecting scanout buffers
2922          * to be already pre-multiplied. We need to add a knob (or a different
2923          * DRM_FORMAT) for user-space to configure that.
2924          */
2925         case DRM_FORMAT_ABGR8888:
2926                 return PLANE_CTL_FORMAT_XRGB_8888 | PLANE_CTL_ORDER_RGBX |
2927                         PLANE_CTL_ALPHA_SW_PREMULTIPLY;
2928         case DRM_FORMAT_ARGB8888:
2929                 return PLANE_CTL_FORMAT_XRGB_8888 |
2930                         PLANE_CTL_ALPHA_SW_PREMULTIPLY;
2931         case DRM_FORMAT_XRGB2101010:
2932                 return PLANE_CTL_FORMAT_XRGB_2101010;
2933         case DRM_FORMAT_XBGR2101010:
2934                 return PLANE_CTL_ORDER_RGBX | PLANE_CTL_FORMAT_XRGB_2101010;
2935         case DRM_FORMAT_YUYV:
2936                 return PLANE_CTL_FORMAT_YUV422 | PLANE_CTL_YUV422_YUYV;
2937         case DRM_FORMAT_YVYU:
2938                 return PLANE_CTL_FORMAT_YUV422 | PLANE_CTL_YUV422_YVYU;
2939         case DRM_FORMAT_UYVY:
2940                 return PLANE_CTL_FORMAT_YUV422 | PLANE_CTL_YUV422_UYVY;
2941         case DRM_FORMAT_VYUY:
2942                 return PLANE_CTL_FORMAT_YUV422 | PLANE_CTL_YUV422_VYUY;
2943         default:
2944                 MISSING_CASE(pixel_format);
2945         }
2946
2947         return 0;
2948 }
2949
2950 u32 skl_plane_ctl_tiling(uint64_t fb_modifier)
2951 {
2952         switch (fb_modifier) {
2953         case DRM_FORMAT_MOD_NONE:
2954                 break;
2955         case I915_FORMAT_MOD_X_TILED:
2956                 return PLANE_CTL_TILED_X;
2957         case I915_FORMAT_MOD_Y_TILED:
2958                 return PLANE_CTL_TILED_Y;
2959         case I915_FORMAT_MOD_Yf_TILED:
2960                 return PLANE_CTL_TILED_YF;
2961         default:
2962                 MISSING_CASE(fb_modifier);
2963         }
2964
2965         return 0;
2966 }
2967
2968 u32 skl_plane_ctl_rotation(unsigned int rotation)
2969 {
2970         switch (rotation) {
2971         case BIT(DRM_ROTATE_0):
2972                 break;
2973         /*
2974          * DRM_ROTATE_ is counter clockwise to stay compatible with Xrandr
2975          * while i915 HW rotation is clockwise, thats why this swapping.
2976          */
2977         case BIT(DRM_ROTATE_90):
2978                 return PLANE_CTL_ROTATE_270;
2979         case BIT(DRM_ROTATE_180):
2980                 return PLANE_CTL_ROTATE_180;
2981         case BIT(DRM_ROTATE_270):
2982                 return PLANE_CTL_ROTATE_90;
2983         default:
2984                 MISSING_CASE(rotation);
2985         }
2986
2987         return 0;
2988 }
2989
2990 static void skylake_update_primary_plane(struct drm_plane *plane,
2991                                          const struct intel_crtc_state *crtc_state,
2992                                          const struct intel_plane_state *plane_state)
2993 {
2994         struct drm_device *dev = plane->dev;
2995         struct drm_i915_private *dev_priv = dev->dev_private;
2996         struct intel_crtc *intel_crtc = to_intel_crtc(crtc_state->base.crtc);
2997         struct drm_framebuffer *fb = plane_state->base.fb;
2998         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
2999         int pipe = intel_crtc->pipe;
3000         u32 plane_ctl, stride_div, stride;
3001         u32 tile_height, plane_offset, plane_size;
3002         unsigned int rotation = plane_state->base.rotation;
3003         int x_offset, y_offset;
3004         u32 surf_addr;
3005         int scaler_id = plane_state->scaler_id;
3006         int src_x = plane_state->src.x1 >> 16;
3007         int src_y = plane_state->src.y1 >> 16;
3008         int src_w = drm_rect_width(&plane_state->src) >> 16;
3009         int src_h = drm_rect_height(&plane_state->src) >> 16;
3010         int dst_x = plane_state->dst.x1;
3011         int dst_y = plane_state->dst.y1;
3012         int dst_w = drm_rect_width(&plane_state->dst);
3013         int dst_h = drm_rect_height(&plane_state->dst);
3014
3015         plane_ctl = PLANE_CTL_ENABLE |
3016                     PLANE_CTL_PIPE_GAMMA_ENABLE |
3017                     PLANE_CTL_PIPE_CSC_ENABLE;
3018
3019         plane_ctl |= skl_plane_ctl_format(fb->pixel_format);
3020         plane_ctl |= skl_plane_ctl_tiling(fb->modifier[0]);
3021         plane_ctl |= PLANE_CTL_PLANE_GAMMA_DISABLE;
3022         plane_ctl |= skl_plane_ctl_rotation(rotation);
3023
3024         stride_div = intel_fb_stride_alignment(dev_priv, fb->modifier[0],
3025                                                fb->pixel_format);
3026         surf_addr = intel_plane_obj_offset(to_intel_plane(plane), obj, 0);
3027
3028         WARN_ON(drm_rect_width(&plane_state->src) == 0);
3029
3030         if (intel_rotation_90_or_270(rotation)) {
3031                 int cpp = drm_format_plane_cpp(fb->pixel_format, 0);
3032
3033                 /* stride = Surface height in tiles */
3034                 tile_height = intel_tile_height(dev_priv, fb->modifier[0], cpp);
3035                 stride = DIV_ROUND_UP(fb->height, tile_height);
3036                 x_offset = stride * tile_height - src_y - src_h;
3037                 y_offset = src_x;
3038                 plane_size = (src_w - 1) << 16 | (src_h - 1);
3039         } else {
3040                 stride = fb->pitches[0] / stride_div;
3041                 x_offset = src_x;
3042                 y_offset = src_y;
3043                 plane_size = (src_h - 1) << 16 | (src_w - 1);
3044         }
3045         plane_offset = y_offset << 16 | x_offset;
3046
3047         intel_crtc->adjusted_x = x_offset;
3048         intel_crtc->adjusted_y = y_offset;
3049
3050         I915_WRITE(PLANE_CTL(pipe, 0), plane_ctl);
3051         I915_WRITE(PLANE_OFFSET(pipe, 0), plane_offset);
3052         I915_WRITE(PLANE_SIZE(pipe, 0), plane_size);
3053         I915_WRITE(PLANE_STRIDE(pipe, 0), stride);
3054
3055         if (scaler_id >= 0) {
3056                 uint32_t ps_ctrl = 0;
3057
3058                 WARN_ON(!dst_w || !dst_h);
3059                 ps_ctrl = PS_SCALER_EN | PS_PLANE_SEL(0) |
3060                         crtc_state->scaler_state.scalers[scaler_id].mode;
3061                 I915_WRITE(SKL_PS_CTRL(pipe, scaler_id), ps_ctrl);
3062                 I915_WRITE(SKL_PS_PWR_GATE(pipe, scaler_id), 0);
3063                 I915_WRITE(SKL_PS_WIN_POS(pipe, scaler_id), (dst_x << 16) | dst_y);
3064                 I915_WRITE(SKL_PS_WIN_SZ(pipe, scaler_id), (dst_w << 16) | dst_h);
3065                 I915_WRITE(PLANE_POS(pipe, 0), 0);
3066         } else {
3067                 I915_WRITE(PLANE_POS(pipe, 0), (dst_y << 16) | dst_x);
3068         }
3069
3070         I915_WRITE(PLANE_SURF(pipe, 0), surf_addr);
3071
3072         POSTING_READ(PLANE_SURF(pipe, 0));
3073 }
3074
3075 static void skylake_disable_primary_plane(struct drm_plane *primary,
3076                                           struct drm_crtc *crtc)
3077 {
3078         struct drm_device *dev = crtc->dev;
3079         struct drm_i915_private *dev_priv = dev->dev_private;
3080         int pipe = to_intel_crtc(crtc)->pipe;
3081
3082         I915_WRITE(PLANE_CTL(pipe, 0), 0);
3083         I915_WRITE(PLANE_SURF(pipe, 0), 0);
3084         POSTING_READ(PLANE_SURF(pipe, 0));
3085 }
3086
3087 /* Assume fb object is pinned & idle & fenced and just update base pointers */
3088 static int
3089 intel_pipe_set_base_atomic(struct drm_crtc *crtc, struct drm_framebuffer *fb,
3090                            int x, int y, enum mode_set_atomic state)
3091 {
3092         /* Support for kgdboc is disabled, this needs a major rework. */
3093         DRM_ERROR("legacy panic handler not supported any more.\n");
3094
3095         return -ENODEV;
3096 }
3097
3098 static void intel_update_primary_planes(struct drm_device *dev)
3099 {
3100         struct drm_crtc *crtc;
3101
3102         for_each_crtc(dev, crtc) {
3103                 struct intel_plane *plane = to_intel_plane(crtc->primary);
3104                 struct intel_plane_state *plane_state;
3105
3106                 drm_modeset_lock_crtc(crtc, &plane->base);
3107                 plane_state = to_intel_plane_state(plane->base.state);
3108
3109                 if (plane_state->visible)
3110                         plane->update_plane(&plane->base,
3111                                             to_intel_crtc_state(crtc->state),
3112                                             plane_state);
3113
3114                 drm_modeset_unlock_crtc(crtc);
3115         }
3116 }
3117
3118 void intel_prepare_reset(struct drm_i915_private *dev_priv)
3119 {
3120         /* no reset support for gen2 */
3121         if (IS_GEN2(dev_priv))
3122                 return;
3123
3124         /* reset doesn't touch the display */
3125         if (INTEL_GEN(dev_priv) >= 5 || IS_G4X(dev_priv))
3126                 return;
3127
3128         drm_modeset_lock_all(dev_priv->dev);
3129         /*
3130          * Disabling the crtcs gracefully seems nicer. Also the
3131          * g33 docs say we should at least disable all the planes.
3132          */
3133         intel_display_suspend(dev_priv->dev);
3134 }
3135
3136 void intel_finish_reset(struct drm_i915_private *dev_priv)
3137 {
3138         /* no reset support for gen2 */
3139         if (IS_GEN2(dev_priv))
3140                 return;
3141
3142         /* reset doesn't touch the display */
3143         if (INTEL_GEN(dev_priv) >= 5 || IS_G4X(dev_priv)) {
3144                 /*
3145                  * Flips in the rings have been nuked by the reset,
3146                  * so update the base address of all primary
3147                  * planes to the the last fb to make sure we're
3148                  * showing the correct fb after a reset.
3149                  *
3150                  * FIXME: Atomic will make this obsolete since we won't schedule
3151                  * CS-based flips (which might get lost in gpu resets) any more.
3152                  */
3153                 intel_update_primary_planes(dev_priv->dev);
3154                 return;
3155         }
3156
3157         /*
3158          * The display has been reset as well,
3159          * so need a full re-initialization.
3160          */
3161         intel_runtime_pm_disable_interrupts(dev_priv);
3162         intel_runtime_pm_enable_interrupts(dev_priv);
3163
3164         intel_modeset_init_hw(dev_priv->dev);
3165
3166         spin_lock_irq(&dev_priv->irq_lock);
3167         if (dev_priv->display.hpd_irq_setup)
3168                 dev_priv->display.hpd_irq_setup(dev_priv);
3169         spin_unlock_irq(&dev_priv->irq_lock);
3170
3171         intel_display_resume(dev_priv->dev);
3172
3173         intel_hpd_init(dev_priv);
3174
3175         drm_modeset_unlock_all(dev_priv->dev);
3176 }
3177
3178 static bool intel_crtc_has_pending_flip(struct drm_crtc *crtc)
3179 {
3180         return !list_empty_careful(&to_intel_crtc(crtc)->flip_work);
3181 }
3182
3183 static void intel_update_pipe_config(struct intel_crtc *crtc,
3184                                      struct intel_crtc_state *old_crtc_state)
3185 {
3186         struct drm_device *dev = crtc->base.dev;
3187         struct drm_i915_private *dev_priv = dev->dev_private;
3188         struct intel_crtc_state *pipe_config =
3189                 to_intel_crtc_state(crtc->base.state);
3190
3191         /* drm_atomic_helper_update_legacy_modeset_state might not be called. */
3192         crtc->base.mode = crtc->base.state->mode;
3193
3194         DRM_DEBUG_KMS("Updating pipe size %ix%i -> %ix%i\n",
3195                       old_crtc_state->pipe_src_w, old_crtc_state->pipe_src_h,
3196                       pipe_config->pipe_src_w, pipe_config->pipe_src_h);
3197
3198         /*
3199          * Update pipe size and adjust fitter if needed: the reason for this is
3200          * that in compute_mode_changes we check the native mode (not the pfit
3201          * mode) to see if we can flip rather than do a full mode set. In the
3202          * fastboot case, we'll flip, but if we don't update the pipesrc and
3203          * pfit state, we'll end up with a big fb scanned out into the wrong
3204          * sized surface.
3205          */
3206
3207         I915_WRITE(PIPESRC(crtc->pipe),
3208                    ((pipe_config->pipe_src_w - 1) << 16) |
3209                    (pipe_config->pipe_src_h - 1));
3210
3211         /* on skylake this is done by detaching scalers */
3212         if (INTEL_INFO(dev)->gen >= 9) {
3213                 skl_detach_scalers(crtc);
3214
3215                 if (pipe_config->pch_pfit.enabled)
3216                         skylake_pfit_enable(crtc);
3217         } else if (HAS_PCH_SPLIT(dev)) {
3218                 if (pipe_config->pch_pfit.enabled)
3219                         ironlake_pfit_enable(crtc);
3220                 else if (old_crtc_state->pch_pfit.enabled)
3221                         ironlake_pfit_disable(crtc, true);
3222         }
3223 }
3224
3225 static void intel_fdi_normal_train(struct drm_crtc *crtc)
3226 {
3227         struct drm_device *dev = crtc->dev;
3228         struct drm_i915_private *dev_priv = dev->dev_private;
3229         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
3230         int pipe = intel_crtc->pipe;
3231         i915_reg_t reg;
3232         u32 temp;
3233
3234         /* enable normal train */
3235         reg = FDI_TX_CTL(pipe);
3236         temp = I915_READ(reg);
3237         if (IS_IVYBRIDGE(dev)) {
3238                 temp &= ~FDI_LINK_TRAIN_NONE_IVB;
3239                 temp |= FDI_LINK_TRAIN_NONE_IVB | FDI_TX_ENHANCE_FRAME_ENABLE;
3240         } else {
3241                 temp &= ~FDI_LINK_TRAIN_NONE;
3242                 temp |= FDI_LINK_TRAIN_NONE | FDI_TX_ENHANCE_FRAME_ENABLE;
3243         }
3244         I915_WRITE(reg, temp);
3245
3246         reg = FDI_RX_CTL(pipe);
3247         temp = I915_READ(reg);
3248         if (HAS_PCH_CPT(dev)) {
3249                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
3250                 temp |= FDI_LINK_TRAIN_NORMAL_CPT;
3251         } else {
3252                 temp &= ~FDI_LINK_TRAIN_NONE;
3253                 temp |= FDI_LINK_TRAIN_NONE;
3254         }
3255         I915_WRITE(reg, temp | FDI_RX_ENHANCE_FRAME_ENABLE);
3256
3257         /* wait one idle pattern time */
3258         POSTING_READ(reg);
3259         udelay(1000);
3260
3261         /* IVB wants error correction enabled */
3262         if (IS_IVYBRIDGE(dev))
3263                 I915_WRITE(reg, I915_READ(reg) | FDI_FS_ERRC_ENABLE |
3264                            FDI_FE_ERRC_ENABLE);
3265 }
3266
3267 /* The FDI link training functions for ILK/Ibexpeak. */
3268 static void ironlake_fdi_link_train(struct drm_crtc *crtc)
3269 {
3270         struct drm_device *dev = crtc->dev;
3271         struct drm_i915_private *dev_priv = dev->dev_private;
3272         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
3273         int pipe = intel_crtc->pipe;
3274         i915_reg_t reg;
3275         u32 temp, tries;
3276
3277         /* FDI needs bits from pipe first */
3278         assert_pipe_enabled(dev_priv, pipe);
3279
3280         /* Train 1: umask FDI RX Interrupt symbol_lock and bit_lock bit
3281            for train result */
3282         reg = FDI_RX_IMR(pipe);
3283         temp = I915_READ(reg);
3284         temp &= ~FDI_RX_SYMBOL_LOCK;
3285         temp &= ~FDI_RX_BIT_LOCK;
3286         I915_WRITE(reg, temp);
3287         I915_READ(reg);
3288         udelay(150);
3289
3290         /* enable CPU FDI TX and PCH FDI RX */
3291         reg = FDI_TX_CTL(pipe);
3292         temp = I915_READ(reg);
3293         temp &= ~FDI_DP_PORT_WIDTH_MASK;
3294         temp |= FDI_DP_PORT_WIDTH(intel_crtc->config->fdi_lanes);
3295         temp &= ~FDI_LINK_TRAIN_NONE;
3296         temp |= FDI_LINK_TRAIN_PATTERN_1;
3297         I915_WRITE(reg, temp | FDI_TX_ENABLE);
3298
3299         reg = FDI_RX_CTL(pipe);
3300         temp = I915_READ(reg);
3301         temp &= ~FDI_LINK_TRAIN_NONE;
3302         temp |= FDI_LINK_TRAIN_PATTERN_1;
3303         I915_WRITE(reg, temp | FDI_RX_ENABLE);
3304
3305         POSTING_READ(reg);
3306         udelay(150);
3307
3308         /* Ironlake workaround, enable clock pointer after FDI enable*/
3309         I915_WRITE(FDI_RX_CHICKEN(pipe), FDI_RX_PHASE_SYNC_POINTER_OVR);
3310         I915_WRITE(FDI_RX_CHICKEN(pipe), FDI_RX_PHASE_SYNC_POINTER_OVR |
3311                    FDI_RX_PHASE_SYNC_POINTER_EN);
3312
3313         reg = FDI_RX_IIR(pipe);
3314         for (tries = 0; tries < 5; tries++) {
3315                 temp = I915_READ(reg);
3316                 DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
3317
3318                 if ((temp & FDI_RX_BIT_LOCK)) {
3319                         DRM_DEBUG_KMS("FDI train 1 done.\n");
3320                         I915_WRITE(reg, temp | FDI_RX_BIT_LOCK);
3321                         break;
3322                 }
3323         }
3324         if (tries == 5)
3325                 DRM_ERROR("FDI train 1 fail!\n");
3326
3327         /* Train 2 */
3328         reg = FDI_TX_CTL(pipe);
3329         temp = I915_READ(reg);
3330         temp &= ~FDI_LINK_TRAIN_NONE;
3331         temp |= FDI_LINK_TRAIN_PATTERN_2;
3332         I915_WRITE(reg, temp);
3333
3334         reg = FDI_RX_CTL(pipe);
3335         temp = I915_READ(reg);
3336         temp &= ~FDI_LINK_TRAIN_NONE;
3337         temp |= FDI_LINK_TRAIN_PATTERN_2;
3338         I915_WRITE(reg, temp);
3339
3340         POSTING_READ(reg);
3341         udelay(150);
3342
3343         reg = FDI_RX_IIR(pipe);
3344         for (tries = 0; tries < 5; tries++) {
3345                 temp = I915_READ(reg);
3346                 DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
3347
3348                 if (temp & FDI_RX_SYMBOL_LOCK) {
3349                         I915_WRITE(reg, temp | FDI_RX_SYMBOL_LOCK);
3350                         DRM_DEBUG_KMS("FDI train 2 done.\n");
3351                         break;
3352                 }
3353         }
3354         if (tries == 5)
3355                 DRM_ERROR("FDI train 2 fail!\n");
3356
3357         DRM_DEBUG_KMS("FDI train done\n");
3358
3359 }
3360
3361 static const int snb_b_fdi_train_param[] = {
3362         FDI_LINK_TRAIN_400MV_0DB_SNB_B,
3363         FDI_LINK_TRAIN_400MV_6DB_SNB_B,
3364         FDI_LINK_TRAIN_600MV_3_5DB_SNB_B,
3365         FDI_LINK_TRAIN_800MV_0DB_SNB_B,
3366 };
3367
3368 /* The FDI link training functions for SNB/Cougarpoint. */
3369 static void gen6_fdi_link_train(struct drm_crtc *crtc)
3370 {
3371         struct drm_device *dev = crtc->dev;
3372         struct drm_i915_private *dev_priv = dev->dev_private;
3373         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
3374         int pipe = intel_crtc->pipe;
3375         i915_reg_t reg;
3376         u32 temp, i, retry;
3377
3378         /* Train 1: umask FDI RX Interrupt symbol_lock and bit_lock bit
3379            for train result */
3380         reg = FDI_RX_IMR(pipe);
3381         temp = I915_READ(reg);
3382         temp &= ~FDI_RX_SYMBOL_LOCK;
3383         temp &= ~FDI_RX_BIT_LOCK;
3384         I915_WRITE(reg, temp);
3385
3386         POSTING_READ(reg);
3387         udelay(150);
3388
3389         /* enable CPU FDI TX and PCH FDI RX */
3390         reg = FDI_TX_CTL(pipe);
3391         temp = I915_READ(reg);
3392         temp &= ~FDI_DP_PORT_WIDTH_MASK;
3393         temp |= FDI_DP_PORT_WIDTH(intel_crtc->config->fdi_lanes);
3394         temp &= ~FDI_LINK_TRAIN_NONE;
3395         temp |= FDI_LINK_TRAIN_PATTERN_1;
3396         temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
3397         /* SNB-B */
3398         temp |= FDI_LINK_TRAIN_400MV_0DB_SNB_B;
3399         I915_WRITE(reg, temp | FDI_TX_ENABLE);
3400
3401         I915_WRITE(FDI_RX_MISC(pipe),
3402                    FDI_RX_TP1_TO_TP2_48 | FDI_RX_FDI_DELAY_90);
3403
3404         reg = FDI_RX_CTL(pipe);
3405         temp = I915_READ(reg);
3406         if (HAS_PCH_CPT(dev)) {
3407                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
3408                 temp |= FDI_LINK_TRAIN_PATTERN_1_CPT;
3409         } else {
3410                 temp &= ~FDI_LINK_TRAIN_NONE;
3411                 temp |= FDI_LINK_TRAIN_PATTERN_1;
3412         }
3413         I915_WRITE(reg, temp | FDI_RX_ENABLE);
3414
3415         POSTING_READ(reg);
3416         udelay(150);
3417
3418         for (i = 0; i < 4; i++) {
3419                 reg = FDI_TX_CTL(pipe);
3420                 temp = I915_READ(reg);
3421                 temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
3422                 temp |= snb_b_fdi_train_param[i];
3423                 I915_WRITE(reg, temp);
3424
3425                 POSTING_READ(reg);
3426                 udelay(500);
3427
3428                 for (retry = 0; retry < 5; retry++) {
3429                         reg = FDI_RX_IIR(pipe);
3430                         temp = I915_READ(reg);
3431                         DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
3432                         if (temp & FDI_RX_BIT_LOCK) {
3433                                 I915_WRITE(reg, temp | FDI_RX_BIT_LOCK);
3434                                 DRM_DEBUG_KMS("FDI train 1 done.\n");
3435                                 break;
3436                         }
3437                         udelay(50);
3438                 }
3439                 if (retry < 5)
3440                         break;
3441         }
3442         if (i == 4)
3443                 DRM_ERROR("FDI train 1 fail!\n");
3444
3445         /* Train 2 */
3446         reg = FDI_TX_CTL(pipe);
3447         temp = I915_READ(reg);
3448         temp &= ~FDI_LINK_TRAIN_NONE;
3449         temp |= FDI_LINK_TRAIN_PATTERN_2;
3450         if (IS_GEN6(dev)) {
3451                 temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
3452                 /* SNB-B */
3453                 temp |= FDI_LINK_TRAIN_400MV_0DB_SNB_B;
3454         }
3455         I915_WRITE(reg, temp);
3456
3457         reg = FDI_RX_CTL(pipe);
3458         temp = I915_READ(reg);
3459         if (HAS_PCH_CPT(dev)) {
3460                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
3461                 temp |= FDI_LINK_TRAIN_PATTERN_2_CPT;
3462         } else {
3463                 temp &= ~FDI_LINK_TRAIN_NONE;
3464                 temp |= FDI_LINK_TRAIN_PATTERN_2;
3465         }
3466         I915_WRITE(reg, temp);
3467
3468         POSTING_READ(reg);
3469         udelay(150);
3470
3471         for (i = 0; i < 4; i++) {
3472                 reg = FDI_TX_CTL(pipe);
3473                 temp = I915_READ(reg);
3474                 temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
3475                 temp |= snb_b_fdi_train_param[i];
3476                 I915_WRITE(reg, temp);
3477
3478                 POSTING_READ(reg);
3479                 udelay(500);
3480
3481                 for (retry = 0; retry < 5; retry++) {
3482                         reg = FDI_RX_IIR(pipe);
3483                         temp = I915_READ(reg);
3484                         DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
3485                         if (temp & FDI_RX_SYMBOL_LOCK) {
3486                                 I915_WRITE(reg, temp | FDI_RX_SYMBOL_LOCK);
3487                                 DRM_DEBUG_KMS("FDI train 2 done.\n");
3488                                 break;
3489                         }
3490                         udelay(50);
3491                 }
3492                 if (retry < 5)
3493                         break;
3494         }
3495         if (i == 4)
3496                 DRM_ERROR("FDI train 2 fail!\n");
3497
3498         DRM_DEBUG_KMS("FDI train done.\n");
3499 }
3500
3501 /* Manual link training for Ivy Bridge A0 parts */
3502 static void ivb_manual_fdi_link_train(struct drm_crtc *crtc)
3503 {
3504         struct drm_device *dev = crtc->dev;
3505         struct drm_i915_private *dev_priv = dev->dev_private;
3506         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
3507         int pipe = intel_crtc->pipe;
3508         i915_reg_t reg;
3509         u32 temp, i, j;
3510
3511         /* Train 1: umask FDI RX Interrupt symbol_lock and bit_lock bit
3512            for train result */
3513         reg = FDI_RX_IMR(pipe);
3514         temp = I915_READ(reg);
3515         temp &= ~FDI_RX_SYMBOL_LOCK;
3516         temp &= ~FDI_RX_BIT_LOCK;
3517         I915_WRITE(reg, temp);
3518
3519         POSTING_READ(reg);
3520         udelay(150);
3521
3522         DRM_DEBUG_KMS("FDI_RX_IIR before link train 0x%x\n",
3523                       I915_READ(FDI_RX_IIR(pipe)));
3524
3525         /* Try each vswing and preemphasis setting twice before moving on */
3526         for (j = 0; j < ARRAY_SIZE(snb_b_fdi_train_param) * 2; j++) {
3527                 /* disable first in case we need to retry */
3528                 reg = FDI_TX_CTL(pipe);
3529                 temp = I915_READ(reg);
3530                 temp &= ~(FDI_LINK_TRAIN_AUTO | FDI_LINK_TRAIN_NONE_IVB);
3531                 temp &= ~FDI_TX_ENABLE;
3532                 I915_WRITE(reg, temp);
3533
3534                 reg = FDI_RX_CTL(pipe);
3535                 temp = I915_READ(reg);
3536                 temp &= ~FDI_LINK_TRAIN_AUTO;
3537                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
3538                 temp &= ~FDI_RX_ENABLE;
3539                 I915_WRITE(reg, temp);
3540
3541                 /* enable CPU FDI TX and PCH FDI RX */
3542                 reg = FDI_TX_CTL(pipe);
3543                 temp = I915_READ(reg);
3544                 temp &= ~FDI_DP_PORT_WIDTH_MASK;
3545                 temp |= FDI_DP_PORT_WIDTH(intel_crtc->config->fdi_lanes);
3546                 temp |= FDI_LINK_TRAIN_PATTERN_1_IVB;
3547                 temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
3548                 temp |= snb_b_fdi_train_param[j/2];
3549                 temp |= FDI_COMPOSITE_SYNC;
3550                 I915_WRITE(reg, temp | FDI_TX_ENABLE);
3551
3552                 I915_WRITE(FDI_RX_MISC(pipe),
3553                            FDI_RX_TP1_TO_TP2_48 | FDI_RX_FDI_DELAY_90);
3554
3555                 reg = FDI_RX_CTL(pipe);
3556                 temp = I915_READ(reg);
3557                 temp |= FDI_LINK_TRAIN_PATTERN_1_CPT;
3558                 temp |= FDI_COMPOSITE_SYNC;
3559                 I915_WRITE(reg, temp | FDI_RX_ENABLE);
3560
3561                 POSTING_READ(reg);
3562                 udelay(1); /* should be 0.5us */
3563
3564                 for (i = 0; i < 4; i++) {
3565                         reg = FDI_RX_IIR(pipe);
3566                         temp = I915_READ(reg);
3567                         DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
3568
3569                         if (temp & FDI_RX_BIT_LOCK ||
3570                             (I915_READ(reg) & FDI_RX_BIT_LOCK)) {
3571                                 I915_WRITE(reg, temp | FDI_RX_BIT_LOCK);
3572                                 DRM_DEBUG_KMS("FDI train 1 done, level %i.\n",
3573                                               i);
3574                                 break;
3575                         }
3576                         udelay(1); /* should be 0.5us */
3577                 }
3578                 if (i == 4) {
3579                         DRM_DEBUG_KMS("FDI train 1 fail on vswing %d\n", j / 2);
3580                         continue;
3581                 }
3582
3583                 /* Train 2 */
3584                 reg = FDI_TX_CTL(pipe);
3585                 temp = I915_READ(reg);
3586                 temp &= ~FDI_LINK_TRAIN_NONE_IVB;
3587                 temp |= FDI_LINK_TRAIN_PATTERN_2_IVB;
3588                 I915_WRITE(reg, temp);
3589
3590                 reg = FDI_RX_CTL(pipe);
3591                 temp = I915_READ(reg);
3592                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
3593                 temp |= FDI_LINK_TRAIN_PATTERN_2_CPT;
3594                 I915_WRITE(reg, temp);
3595
3596                 POSTING_READ(reg);
3597                 udelay(2); /* should be 1.5us */
3598
3599                 for (i = 0; i < 4; i++) {
3600                         reg = FDI_RX_IIR(pipe);
3601                         temp = I915_READ(reg);
3602                         DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
3603
3604                         if (temp & FDI_RX_SYMBOL_LOCK ||
3605                             (I915_READ(reg) & FDI_RX_SYMBOL_LOCK)) {
3606                                 I915_WRITE(reg, temp | FDI_RX_SYMBOL_LOCK);
3607                                 DRM_DEBUG_KMS("FDI train 2 done, level %i.\n",
3608                                               i);
3609                                 goto train_done;
3610                         }
3611                         udelay(2); /* should be 1.5us */
3612                 }
3613                 if (i == 4)
3614                         DRM_DEBUG_KMS("FDI train 2 fail on vswing %d\n", j / 2);
3615         }
3616
3617 train_done:
3618         DRM_DEBUG_KMS("FDI train done.\n");
3619 }
3620
3621 static void ironlake_fdi_pll_enable(struct intel_crtc *intel_crtc)
3622 {
3623         struct drm_device *dev = intel_crtc->base.dev;
3624         struct drm_i915_private *dev_priv = dev->dev_private;
3625         int pipe = intel_crtc->pipe;
3626         i915_reg_t reg;
3627         u32 temp;
3628
3629         /* enable PCH FDI RX PLL, wait warmup plus DMI latency */
3630         reg = FDI_RX_CTL(pipe);
3631         temp = I915_READ(reg);
3632         temp &= ~(FDI_DP_PORT_WIDTH_MASK | (0x7 << 16));
3633         temp |= FDI_DP_PORT_WIDTH(intel_crtc->config->fdi_lanes);
3634         temp |= (I915_READ(PIPECONF(pipe)) & PIPECONF_BPC_MASK) << 11;
3635         I915_WRITE(reg, temp | FDI_RX_PLL_ENABLE);
3636
3637         POSTING_READ(reg);
3638         udelay(200);
3639
3640         /* Switch from Rawclk to PCDclk */
3641         temp = I915_READ(reg);
3642         I915_WRITE(reg, temp | FDI_PCDCLK);
3643
3644         POSTING_READ(reg);
3645         udelay(200);
3646
3647         /* Enable CPU FDI TX PLL, always on for Ironlake */
3648         reg = FDI_TX_CTL(pipe);
3649         temp = I915_READ(reg);
3650         if ((temp & FDI_TX_PLL_ENABLE) == 0) {
3651                 I915_WRITE(reg, temp | FDI_TX_PLL_ENABLE);
3652
3653                 POSTING_READ(reg);
3654                 udelay(100);
3655         }
3656 }
3657
3658 static void ironlake_fdi_pll_disable(struct intel_crtc *intel_crtc)
3659 {
3660         struct drm_device *dev = intel_crtc->base.dev;
3661         struct drm_i915_private *dev_priv = dev->dev_private;
3662         int pipe = intel_crtc->pipe;
3663         i915_reg_t reg;
3664         u32 temp;
3665
3666         /* Switch from PCDclk to Rawclk */
3667         reg = FDI_RX_CTL(pipe);
3668         temp = I915_READ(reg);
3669         I915_WRITE(reg, temp & ~FDI_PCDCLK);
3670
3671         /* Disable CPU FDI TX PLL */
3672         reg = FDI_TX_CTL(pipe);
3673         temp = I915_READ(reg);
3674         I915_WRITE(reg, temp & ~FDI_TX_PLL_ENABLE);
3675
3676         POSTING_READ(reg);
3677         udelay(100);
3678
3679         reg = FDI_RX_CTL(pipe);
3680         temp = I915_READ(reg);
3681         I915_WRITE(reg, temp & ~FDI_RX_PLL_ENABLE);
3682
3683         /* Wait for the clocks to turn off. */
3684         POSTING_READ(reg);
3685         udelay(100);
3686 }
3687
3688 static void ironlake_fdi_disable(struct drm_crtc *crtc)
3689 {
3690         struct drm_device *dev = crtc->dev;
3691         struct drm_i915_private *dev_priv = dev->dev_private;
3692         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
3693         int pipe = intel_crtc->pipe;
3694         i915_reg_t reg;
3695         u32 temp;
3696
3697         /* disable CPU FDI tx and PCH FDI rx */
3698         reg = FDI_TX_CTL(pipe);
3699         temp = I915_READ(reg);
3700         I915_WRITE(reg, temp & ~FDI_TX_ENABLE);
3701         POSTING_READ(reg);
3702
3703         reg = FDI_RX_CTL(pipe);
3704         temp = I915_READ(reg);
3705         temp &= ~(0x7 << 16);
3706         temp |= (I915_READ(PIPECONF(pipe)) & PIPECONF_BPC_MASK) << 11;
3707         I915_WRITE(reg, temp & ~FDI_RX_ENABLE);
3708
3709         POSTING_READ(reg);
3710         udelay(100);
3711
3712         /* Ironlake workaround, disable clock pointer after downing FDI */
3713         if (HAS_PCH_IBX(dev))
3714                 I915_WRITE(FDI_RX_CHICKEN(pipe), FDI_RX_PHASE_SYNC_POINTER_OVR);
3715
3716         /* still set train pattern 1 */
3717         reg = FDI_TX_CTL(pipe);
3718         temp = I915_READ(reg);
3719         temp &= ~FDI_LINK_TRAIN_NONE;
3720         temp |= FDI_LINK_TRAIN_PATTERN_1;
3721         I915_WRITE(reg, temp);
3722
3723         reg = FDI_RX_CTL(pipe);
3724         temp = I915_READ(reg);
3725         if (HAS_PCH_CPT(dev)) {
3726                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
3727                 temp |= FDI_LINK_TRAIN_PATTERN_1_CPT;
3728         } else {
3729                 temp &= ~FDI_LINK_TRAIN_NONE;
3730                 temp |= FDI_LINK_TRAIN_PATTERN_1;
3731         }
3732         /* BPC in FDI rx is consistent with that in PIPECONF */
3733         temp &= ~(0x07 << 16);
3734         temp |= (I915_READ(PIPECONF(pipe)) & PIPECONF_BPC_MASK) << 11;
3735         I915_WRITE(reg, temp);
3736
3737         POSTING_READ(reg);
3738         udelay(100);
3739 }
3740
3741 bool intel_has_pending_fb_unpin(struct drm_device *dev)
3742 {
3743         struct intel_crtc *crtc;
3744
3745         /* Note that we don't need to be called with mode_config.lock here
3746          * as our list of CRTC objects is static for the lifetime of the
3747          * device and so cannot disappear as we iterate. Similarly, we can
3748          * happily treat the predicates as racy, atomic checks as userspace
3749          * cannot claim and pin a new fb without at least acquring the
3750          * struct_mutex and so serialising with us.
3751          */
3752         for_each_intel_crtc(dev, crtc) {
3753                 if (atomic_read(&crtc->unpin_work_count) == 0)
3754                         continue;
3755
3756                 if (!list_empty_careful(&crtc->flip_work))
3757                         intel_wait_for_vblank(dev, crtc->pipe);
3758
3759                 return true;
3760         }
3761
3762         return false;
3763 }
3764
3765 static void page_flip_completed(struct intel_crtc *intel_crtc, struct intel_flip_work *work)
3766 {
3767         struct drm_i915_private *dev_priv = to_i915(intel_crtc->base.dev);
3768         struct drm_plane_state *new_plane_state;
3769         struct drm_plane *primary = intel_crtc->base.primary;
3770
3771         if (work->event)
3772                 drm_crtc_send_vblank_event(&intel_crtc->base, work->event);
3773
3774         drm_crtc_vblank_put(&intel_crtc->base);
3775
3776         new_plane_state = &work->old_plane_state[0]->base;
3777         if (work->num_planes >= 1 &&
3778             new_plane_state->plane == primary &&
3779             new_plane_state->fb)
3780                 trace_i915_flip_complete(intel_crtc->plane,
3781                                          intel_fb_obj(new_plane_state->fb));
3782
3783         if (work->can_async_unpin) {
3784                 list_del_init(&work->head);
3785                 wake_up_all(&dev_priv->pending_flip_queue);
3786         }
3787
3788         queue_work(dev_priv->wq, &work->unpin_work);
3789 }
3790
3791 static int intel_crtc_wait_for_pending_flips(struct drm_crtc *crtc)
3792 {
3793         struct drm_device *dev = crtc->dev;
3794         struct drm_i915_private *dev_priv = dev->dev_private;
3795         long ret;
3796
3797         WARN_ON(waitqueue_active(&dev_priv->pending_flip_queue));
3798
3799         ret = wait_event_interruptible_timeout(
3800                                         dev_priv->pending_flip_queue,
3801                                         !intel_crtc_has_pending_flip(crtc),
3802                                         60*HZ);
3803
3804         if (ret < 0)
3805                 return ret;
3806
3807         WARN(ret == 0, "Stuck page flip\n");
3808
3809         return 0;
3810 }
3811
3812 static void lpt_disable_iclkip(struct drm_i915_private *dev_priv)
3813 {
3814         u32 temp;
3815
3816         I915_WRITE(PIXCLK_GATE, PIXCLK_GATE_GATE);
3817
3818         mutex_lock(&dev_priv->sb_lock);
3819
3820         temp = intel_sbi_read(dev_priv, SBI_SSCCTL6, SBI_ICLK);
3821         temp |= SBI_SSCCTL_DISABLE;
3822         intel_sbi_write(dev_priv, SBI_SSCCTL6, temp, SBI_ICLK);
3823
3824         mutex_unlock(&dev_priv->sb_lock);
3825 }
3826
3827 /* Program iCLKIP clock to the desired frequency */
3828 static void lpt_program_iclkip(struct drm_crtc *crtc)
3829 {
3830         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
3831         int clock = to_intel_crtc(crtc)->config->base.adjusted_mode.crtc_clock;
3832         u32 divsel, phaseinc, auxdiv, phasedir = 0;
3833         u32 temp;
3834
3835         lpt_disable_iclkip(dev_priv);
3836
3837         /* The iCLK virtual clock root frequency is in MHz,
3838          * but the adjusted_mode->crtc_clock in in KHz. To get the
3839          * divisors, it is necessary to divide one by another, so we
3840          * convert the virtual clock precision to KHz here for higher
3841          * precision.
3842          */
3843         for (auxdiv = 0; auxdiv < 2; auxdiv++) {
3844                 u32 iclk_virtual_root_freq = 172800 * 1000;
3845                 u32 iclk_pi_range = 64;
3846                 u32 desired_divisor;
3847
3848                 desired_divisor = DIV_ROUND_CLOSEST(iclk_virtual_root_freq,
3849                                                     clock << auxdiv);
3850                 divsel = (desired_divisor / iclk_pi_range) - 2;
3851                 phaseinc = desired_divisor % iclk_pi_range;
3852
3853                 /*
3854                  * Near 20MHz is a corner case which is
3855                  * out of range for the 7-bit divisor
3856                  */
3857                 if (divsel <= 0x7f)
3858                         break;
3859         }
3860
3861         /* This should not happen with any sane values */
3862         WARN_ON(SBI_SSCDIVINTPHASE_DIVSEL(divsel) &
3863                 ~SBI_SSCDIVINTPHASE_DIVSEL_MASK);
3864         WARN_ON(SBI_SSCDIVINTPHASE_DIR(phasedir) &
3865                 ~SBI_SSCDIVINTPHASE_INCVAL_MASK);
3866
3867         DRM_DEBUG_KMS("iCLKIP clock: found settings for %dKHz refresh rate: auxdiv=%x, divsel=%x, phasedir=%x, phaseinc=%x\n",
3868                         clock,
3869                         auxdiv,
3870                         divsel,
3871                         phasedir,
3872                         phaseinc);
3873
3874         mutex_lock(&dev_priv->sb_lock);
3875
3876         /* Program SSCDIVINTPHASE6 */
3877         temp = intel_sbi_read(dev_priv, SBI_SSCDIVINTPHASE6, SBI_ICLK);
3878         temp &= ~SBI_SSCDIVINTPHASE_DIVSEL_MASK;
3879         temp |= SBI_SSCDIVINTPHASE_DIVSEL(divsel);
3880         temp &= ~SBI_SSCDIVINTPHASE_INCVAL_MASK;
3881         temp |= SBI_SSCDIVINTPHASE_INCVAL(phaseinc);
3882         temp |= SBI_SSCDIVINTPHASE_DIR(phasedir);
3883         temp |= SBI_SSCDIVINTPHASE_PROPAGATE;
3884         intel_sbi_write(dev_priv, SBI_SSCDIVINTPHASE6, temp, SBI_ICLK);
3885
3886         /* Program SSCAUXDIV */
3887         temp = intel_sbi_read(dev_priv, SBI_SSCAUXDIV6, SBI_ICLK);
3888         temp &= ~SBI_SSCAUXDIV_FINALDIV2SEL(1);
3889         temp |= SBI_SSCAUXDIV_FINALDIV2SEL(auxdiv);
3890         intel_sbi_write(dev_priv, SBI_SSCAUXDIV6, temp, SBI_ICLK);
3891
3892         /* Enable modulator and associated divider */
3893         temp = intel_sbi_read(dev_priv, SBI_SSCCTL6, SBI_ICLK);
3894         temp &= ~SBI_SSCCTL_DISABLE;
3895         intel_sbi_write(dev_priv, SBI_SSCCTL6, temp, SBI_ICLK);
3896
3897         mutex_unlock(&dev_priv->sb_lock);
3898
3899         /* Wait for initialization time */
3900         udelay(24);
3901
3902         I915_WRITE(PIXCLK_GATE, PIXCLK_GATE_UNGATE);
3903 }
3904
3905 int lpt_get_iclkip(struct drm_i915_private *dev_priv)
3906 {
3907         u32 divsel, phaseinc, auxdiv;
3908         u32 iclk_virtual_root_freq = 172800 * 1000;
3909         u32 iclk_pi_range = 64;
3910         u32 desired_divisor;
3911         u32 temp;
3912
3913         if ((I915_READ(PIXCLK_GATE) & PIXCLK_GATE_UNGATE) == 0)
3914                 return 0;
3915
3916         mutex_lock(&dev_priv->sb_lock);
3917
3918         temp = intel_sbi_read(dev_priv, SBI_SSCCTL6, SBI_ICLK);
3919         if (temp & SBI_SSCCTL_DISABLE) {
3920                 mutex_unlock(&dev_priv->sb_lock);
3921                 return 0;
3922         }
3923
3924         temp = intel_sbi_read(dev_priv, SBI_SSCDIVINTPHASE6, SBI_ICLK);
3925         divsel = (temp & SBI_SSCDIVINTPHASE_DIVSEL_MASK) >>
3926                 SBI_SSCDIVINTPHASE_DIVSEL_SHIFT;
3927         phaseinc = (temp & SBI_SSCDIVINTPHASE_INCVAL_MASK) >>
3928                 SBI_SSCDIVINTPHASE_INCVAL_SHIFT;
3929
3930         temp = intel_sbi_read(dev_priv, SBI_SSCAUXDIV6, SBI_ICLK);
3931         auxdiv = (temp & SBI_SSCAUXDIV_FINALDIV2SEL_MASK) >>
3932                 SBI_SSCAUXDIV_FINALDIV2SEL_SHIFT;
3933
3934         mutex_unlock(&dev_priv->sb_lock);
3935
3936         desired_divisor = (divsel + 2) * iclk_pi_range + phaseinc;
3937
3938         return DIV_ROUND_CLOSEST(iclk_virtual_root_freq,
3939                                  desired_divisor << auxdiv);
3940 }
3941
3942 static void ironlake_pch_transcoder_set_timings(struct intel_crtc *crtc,
3943                                                 enum pipe pch_transcoder)
3944 {
3945         struct drm_device *dev = crtc->base.dev;
3946         struct drm_i915_private *dev_priv = dev->dev_private;
3947         enum transcoder cpu_transcoder = crtc->config->cpu_transcoder;
3948
3949         I915_WRITE(PCH_TRANS_HTOTAL(pch_transcoder),
3950                    I915_READ(HTOTAL(cpu_transcoder)));
3951         I915_WRITE(PCH_TRANS_HBLANK(pch_transcoder),
3952                    I915_READ(HBLANK(cpu_transcoder)));
3953         I915_WRITE(PCH_TRANS_HSYNC(pch_transcoder),
3954                    I915_READ(HSYNC(cpu_transcoder)));
3955
3956         I915_WRITE(PCH_TRANS_VTOTAL(pch_transcoder),
3957                    I915_READ(VTOTAL(cpu_transcoder)));
3958         I915_WRITE(PCH_TRANS_VBLANK(pch_transcoder),
3959                    I915_READ(VBLANK(cpu_transcoder)));
3960         I915_WRITE(PCH_TRANS_VSYNC(pch_transcoder),
3961                    I915_READ(VSYNC(cpu_transcoder)));
3962         I915_WRITE(PCH_TRANS_VSYNCSHIFT(pch_transcoder),
3963                    I915_READ(VSYNCSHIFT(cpu_transcoder)));
3964 }
3965
3966 static void cpt_set_fdi_bc_bifurcation(struct drm_device *dev, bool enable)
3967 {
3968         struct drm_i915_private *dev_priv = dev->dev_private;
3969         uint32_t temp;
3970
3971         temp = I915_READ(SOUTH_CHICKEN1);
3972         if (!!(temp & FDI_BC_BIFURCATION_SELECT) == enable)
3973                 return;
3974
3975         WARN_ON(I915_READ(FDI_RX_CTL(PIPE_B)) & FDI_RX_ENABLE);
3976         WARN_ON(I915_READ(FDI_RX_CTL(PIPE_C)) & FDI_RX_ENABLE);
3977
3978         temp &= ~FDI_BC_BIFURCATION_SELECT;
3979         if (enable)
3980                 temp |= FDI_BC_BIFURCATION_SELECT;
3981
3982         DRM_DEBUG_KMS("%sabling fdi C rx\n", enable ? "en" : "dis");
3983         I915_WRITE(SOUTH_CHICKEN1, temp);
3984         POSTING_READ(SOUTH_CHICKEN1);
3985 }
3986
3987 static void ivybridge_update_fdi_bc_bifurcation(struct intel_crtc *intel_crtc)
3988 {
3989         struct drm_device *dev = intel_crtc->base.dev;
3990
3991         switch (intel_crtc->pipe) {
3992         case PIPE_A:
3993                 break;
3994         case PIPE_B:
3995                 if (intel_crtc->config->fdi_lanes > 2)
3996                         cpt_set_fdi_bc_bifurcation(dev, false);
3997                 else
3998                         cpt_set_fdi_bc_bifurcation(dev, true);
3999
4000                 break;
4001         case PIPE_C:
4002                 cpt_set_fdi_bc_bifurcation(dev, true);
4003
4004                 break;
4005         default:
4006                 BUG();
4007         }
4008 }
4009
4010 /* Return which DP Port should be selected for Transcoder DP control */
4011 static enum port
4012 intel_trans_dp_port_sel(struct drm_crtc *crtc)
4013 {
4014         struct drm_device *dev = crtc->dev;
4015         struct intel_encoder *encoder;
4016
4017         for_each_encoder_on_crtc(dev, crtc, encoder) {
4018                 if (encoder->type == INTEL_OUTPUT_DISPLAYPORT ||
4019                     encoder->type == INTEL_OUTPUT_EDP)
4020                         return enc_to_dig_port(&encoder->base)->port;
4021         }
4022
4023         return -1;
4024 }
4025
4026 /*
4027  * Enable PCH resources required for PCH ports:
4028  *   - PCH PLLs
4029  *   - FDI training & RX/TX
4030  *   - update transcoder timings
4031  *   - DP transcoding bits
4032  *   - transcoder
4033  */
4034 static void ironlake_pch_enable(struct drm_crtc *crtc)
4035 {
4036         struct drm_device *dev = crtc->dev;
4037         struct drm_i915_private *dev_priv = dev->dev_private;
4038         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4039         int pipe = intel_crtc->pipe;
4040         u32 temp;
4041
4042         assert_pch_transcoder_disabled(dev_priv, pipe);
4043
4044         if (IS_IVYBRIDGE(dev))
4045                 ivybridge_update_fdi_bc_bifurcation(intel_crtc);
4046
4047         /* Write the TU size bits before fdi link training, so that error
4048          * detection works. */
4049         I915_WRITE(FDI_RX_TUSIZE1(pipe),
4050                    I915_READ(PIPE_DATA_M1(pipe)) & TU_SIZE_MASK);
4051
4052         /* For PCH output, training FDI link */
4053         dev_priv->display.fdi_link_train(crtc);
4054
4055         /* We need to program the right clock selection before writing the pixel
4056          * mutliplier into the DPLL. */
4057         if (HAS_PCH_CPT(dev)) {
4058                 u32 sel;
4059
4060                 temp = I915_READ(PCH_DPLL_SEL);
4061                 temp |= TRANS_DPLL_ENABLE(pipe);
4062                 sel = TRANS_DPLLB_SEL(pipe);
4063                 if (intel_crtc->config->shared_dpll ==
4064                     intel_get_shared_dpll_by_id(dev_priv, DPLL_ID_PCH_PLL_B))
4065                         temp |= sel;
4066                 else
4067                         temp &= ~sel;
4068                 I915_WRITE(PCH_DPLL_SEL, temp);
4069         }
4070
4071         /* XXX: pch pll's can be enabled any time before we enable the PCH
4072          * transcoder, and we actually should do this to not upset any PCH
4073          * transcoder that already use the clock when we share it.
4074          *
4075          * Note that enable_shared_dpll tries to do the right thing, but
4076          * get_shared_dpll unconditionally resets the pll - we need that to have
4077          * the right LVDS enable sequence. */
4078         intel_enable_shared_dpll(intel_crtc);
4079
4080         /* set transcoder timing, panel must allow it */
4081         assert_panel_unlocked(dev_priv, pipe);
4082         ironlake_pch_transcoder_set_timings(intel_crtc, pipe);
4083
4084         intel_fdi_normal_train(crtc);
4085
4086         /* For PCH DP, enable TRANS_DP_CTL */
4087         if (HAS_PCH_CPT(dev) && intel_crtc->config->has_dp_encoder) {
4088                 const struct drm_display_mode *adjusted_mode =
4089                         &intel_crtc->config->base.adjusted_mode;
4090                 u32 bpc = (I915_READ(PIPECONF(pipe)) & PIPECONF_BPC_MASK) >> 5;
4091                 i915_reg_t reg = TRANS_DP_CTL(pipe);
4092                 temp = I915_READ(reg);
4093                 temp &= ~(TRANS_DP_PORT_SEL_MASK |
4094                           TRANS_DP_SYNC_MASK |
4095                           TRANS_DP_BPC_MASK);
4096                 temp |= TRANS_DP_OUTPUT_ENABLE;
4097                 temp |= bpc << 9; /* same format but at 11:9 */
4098
4099                 if (adjusted_mode->flags & DRM_MODE_FLAG_PHSYNC)
4100                         temp |= TRANS_DP_HSYNC_ACTIVE_HIGH;
4101                 if (adjusted_mode->flags & DRM_MODE_FLAG_PVSYNC)
4102                         temp |= TRANS_DP_VSYNC_ACTIVE_HIGH;
4103
4104                 switch (intel_trans_dp_port_sel(crtc)) {
4105                 case PORT_B:
4106                         temp |= TRANS_DP_PORT_SEL_B;
4107                         break;
4108                 case PORT_C:
4109                         temp |= TRANS_DP_PORT_SEL_C;
4110                         break;
4111                 case PORT_D:
4112                         temp |= TRANS_DP_PORT_SEL_D;
4113                         break;
4114                 default:
4115                         BUG();
4116                 }
4117
4118                 I915_WRITE(reg, temp);
4119         }
4120
4121         ironlake_enable_pch_transcoder(dev_priv, pipe);
4122 }
4123
4124 static void lpt_pch_enable(struct drm_crtc *crtc)
4125 {
4126         struct drm_device *dev = crtc->dev;
4127         struct drm_i915_private *dev_priv = dev->dev_private;
4128         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4129         enum transcoder cpu_transcoder = intel_crtc->config->cpu_transcoder;
4130
4131         assert_pch_transcoder_disabled(dev_priv, TRANSCODER_A);
4132
4133         lpt_program_iclkip(crtc);
4134
4135         /* Set transcoder timing. */
4136         ironlake_pch_transcoder_set_timings(intel_crtc, PIPE_A);
4137
4138         lpt_enable_pch_transcoder(dev_priv, cpu_transcoder);
4139 }
4140
4141 static void cpt_verify_modeset(struct drm_device *dev, int pipe)
4142 {
4143         struct drm_i915_private *dev_priv = dev->dev_private;
4144         i915_reg_t dslreg = PIPEDSL(pipe);
4145         u32 temp;
4146
4147         temp = I915_READ(dslreg);
4148         udelay(500);
4149         if (wait_for(I915_READ(dslreg) != temp, 5)) {
4150                 if (wait_for(I915_READ(dslreg) != temp, 5))
4151                         DRM_ERROR("mode set failed: pipe %c stuck\n", pipe_name(pipe));
4152         }
4153 }
4154
4155 static int
4156 skl_update_scaler(struct intel_crtc_state *crtc_state, bool force_detach,
4157                   unsigned scaler_user, int *scaler_id, unsigned int rotation,
4158                   int src_w, int src_h, int dst_w, int dst_h)
4159 {
4160         struct intel_crtc_scaler_state *scaler_state =
4161                 &crtc_state->scaler_state;
4162         struct intel_crtc *intel_crtc =
4163                 to_intel_crtc(crtc_state->base.crtc);
4164         int need_scaling;
4165
4166         need_scaling = intel_rotation_90_or_270(rotation) ?
4167                 (src_h != dst_w || src_w != dst_h):
4168                 (src_w != dst_w || src_h != dst_h);
4169
4170         /*
4171          * if plane is being disabled or scaler is no more required or force detach
4172          *  - free scaler binded to this plane/crtc
4173          *  - in order to do this, update crtc->scaler_usage
4174          *
4175          * Here scaler state in crtc_state is set free so that
4176          * scaler can be assigned to other user. Actual register
4177          * update to free the scaler is done in plane/panel-fit programming.
4178          * For this purpose crtc/plane_state->scaler_id isn't reset here.
4179          */
4180         if (force_detach || !need_scaling) {
4181                 if (*scaler_id >= 0) {
4182                         scaler_state->scaler_users &= ~(1 << scaler_user);
4183                         scaler_state->scalers[*scaler_id].in_use = 0;
4184
4185                         DRM_DEBUG_KMS("scaler_user index %u.%u: "
4186                                 "Staged freeing scaler id %d scaler_users = 0x%x\n",
4187                                 intel_crtc->pipe, scaler_user, *scaler_id,
4188                                 scaler_state->scaler_users);
4189                         *scaler_id = -1;
4190                 }
4191                 return 0;
4192         }
4193
4194         /* range checks */
4195         if (src_w < SKL_MIN_SRC_W || src_h < SKL_MIN_SRC_H ||
4196                 dst_w < SKL_MIN_DST_W || dst_h < SKL_MIN_DST_H ||
4197
4198                 src_w > SKL_MAX_SRC_W || src_h > SKL_MAX_SRC_H ||
4199                 dst_w > SKL_MAX_DST_W || dst_h > SKL_MAX_DST_H) {
4200                 DRM_DEBUG_KMS("scaler_user index %u.%u: src %ux%u dst %ux%u "
4201                         "size is out of scaler range\n",
4202                         intel_crtc->pipe, scaler_user, src_w, src_h, dst_w, dst_h);
4203                 return -EINVAL;
4204         }
4205
4206         /* mark this plane as a scaler user in crtc_state */
4207         scaler_state->scaler_users |= (1 << scaler_user);
4208         DRM_DEBUG_KMS("scaler_user index %u.%u: "
4209                 "staged scaling request for %ux%u->%ux%u scaler_users = 0x%x\n",
4210                 intel_crtc->pipe, scaler_user, src_w, src_h, dst_w, dst_h,
4211                 scaler_state->scaler_users);
4212
4213         return 0;
4214 }
4215
4216 /**
4217  * skl_update_scaler_crtc - Stages update to scaler state for a given crtc.
4218  *
4219  * @state: crtc's scaler state
4220  *
4221  * Return
4222  *     0 - scaler_usage updated successfully
4223  *    error - requested scaling cannot be supported or other error condition
4224  */
4225 int skl_update_scaler_crtc(struct intel_crtc_state *state)
4226 {
4227         struct intel_crtc *intel_crtc = to_intel_crtc(state->base.crtc);
4228         const struct drm_display_mode *adjusted_mode = &state->base.adjusted_mode;
4229
4230         DRM_DEBUG_KMS("Updating scaler for [CRTC:%i] scaler_user index %u.%u\n",
4231                       intel_crtc->base.base.id, intel_crtc->pipe, SKL_CRTC_INDEX);
4232
4233         return skl_update_scaler(state, !state->base.active, SKL_CRTC_INDEX,
4234                 &state->scaler_state.scaler_id, BIT(DRM_ROTATE_0),
4235                 state->pipe_src_w, state->pipe_src_h,
4236                 adjusted_mode->crtc_hdisplay, adjusted_mode->crtc_vdisplay);
4237 }
4238
4239 /**
4240  * skl_update_scaler_plane - Stages update to scaler state for a given plane.
4241  *
4242  * @state: crtc's scaler state
4243  * @plane_state: atomic plane state to update
4244  *
4245  * Return
4246  *     0 - scaler_usage updated successfully
4247  *    error - requested scaling cannot be supported or other error condition
4248  */
4249 static int skl_update_scaler_plane(struct intel_crtc_state *crtc_state,
4250                                    struct intel_plane_state *plane_state)
4251 {
4252
4253         struct intel_crtc *intel_crtc = to_intel_crtc(crtc_state->base.crtc);
4254         struct intel_plane *intel_plane =
4255                 to_intel_plane(plane_state->base.plane);
4256         struct drm_framebuffer *fb = plane_state->base.fb;
4257         int ret;
4258
4259         bool force_detach = !fb || !plane_state->visible;
4260
4261         DRM_DEBUG_KMS("Updating scaler for [PLANE:%d] scaler_user index %u.%u\n",
4262                       intel_plane->base.base.id, intel_crtc->pipe,
4263                       drm_plane_index(&intel_plane->base));
4264
4265         ret = skl_update_scaler(crtc_state, force_detach,
4266                                 drm_plane_index(&intel_plane->base),
4267                                 &plane_state->scaler_id,
4268                                 plane_state->base.rotation,
4269                                 drm_rect_width(&plane_state->src) >> 16,
4270                                 drm_rect_height(&plane_state->src) >> 16,
4271                                 drm_rect_width(&plane_state->dst),
4272                                 drm_rect_height(&plane_state->dst));
4273
4274         if (ret || plane_state->scaler_id < 0)
4275                 return ret;
4276
4277         /* check colorkey */
4278         if (plane_state->ckey.flags != I915_SET_COLORKEY_NONE) {
4279                 DRM_DEBUG_KMS("[PLANE:%d] scaling with color key not allowed",
4280                               intel_plane->base.base.id);
4281                 return -EINVAL;
4282         }
4283
4284         /* Check src format */
4285         switch (fb->pixel_format) {
4286         case DRM_FORMAT_RGB565:
4287         case DRM_FORMAT_XBGR8888:
4288         case DRM_FORMAT_XRGB8888:
4289         case DRM_FORMAT_ABGR8888:
4290         case DRM_FORMAT_ARGB8888:
4291         case DRM_FORMAT_XRGB2101010:
4292         case DRM_FORMAT_XBGR2101010:
4293         case DRM_FORMAT_YUYV:
4294         case DRM_FORMAT_YVYU:
4295         case DRM_FORMAT_UYVY:
4296         case DRM_FORMAT_VYUY:
4297                 break;
4298         default:
4299                 DRM_DEBUG_KMS("[PLANE:%d] FB:%d unsupported scaling format 0x%x\n",
4300                         intel_plane->base.base.id, fb->base.id, fb->pixel_format);
4301                 return -EINVAL;
4302         }
4303
4304         return 0;
4305 }
4306
4307 static void skylake_scaler_disable(struct intel_crtc *crtc)
4308 {
4309         int i;
4310
4311         for (i = 0; i < crtc->num_scalers; i++)
4312                 skl_detach_scaler(crtc, i);
4313 }
4314
4315 static void skylake_pfit_enable(struct intel_crtc *crtc)
4316 {
4317         struct drm_device *dev = crtc->base.dev;
4318         struct drm_i915_private *dev_priv = dev->dev_private;
4319         int pipe = crtc->pipe;
4320         struct intel_crtc_scaler_state *scaler_state =
4321                 &crtc->config->scaler_state;
4322
4323         DRM_DEBUG_KMS("for crtc_state = %p\n", crtc->config);
4324
4325         if (crtc->config->pch_pfit.enabled) {
4326                 int id;
4327
4328                 if (WARN_ON(crtc->config->scaler_state.scaler_id < 0)) {
4329                         DRM_ERROR("Requesting pfit without getting a scaler first\n");
4330                         return;
4331                 }
4332
4333                 id = scaler_state->scaler_id;
4334                 I915_WRITE(SKL_PS_CTRL(pipe, id), PS_SCALER_EN |
4335                         PS_FILTER_MEDIUM | scaler_state->scalers[id].mode);
4336                 I915_WRITE(SKL_PS_WIN_POS(pipe, id), crtc->config->pch_pfit.pos);
4337                 I915_WRITE(SKL_PS_WIN_SZ(pipe, id), crtc->config->pch_pfit.size);
4338
4339                 DRM_DEBUG_KMS("for crtc_state = %p scaler_id = %d\n", crtc->config, id);
4340         }
4341 }
4342
4343 static void ironlake_pfit_enable(struct intel_crtc *crtc)
4344 {
4345         struct drm_device *dev = crtc->base.dev;
4346         struct drm_i915_private *dev_priv = dev->dev_private;
4347         int pipe = crtc->pipe;
4348
4349         if (crtc->config->pch_pfit.enabled) {
4350                 /* Force use of hard-coded filter coefficients
4351                  * as some pre-programmed values are broken,
4352                  * e.g. x201.
4353                  */
4354                 if (IS_IVYBRIDGE(dev) || IS_HASWELL(dev))
4355                         I915_WRITE(PF_CTL(pipe), PF_ENABLE | PF_FILTER_MED_3x3 |
4356                                                  PF_PIPE_SEL_IVB(pipe));
4357                 else
4358                         I915_WRITE(PF_CTL(pipe), PF_ENABLE | PF_FILTER_MED_3x3);
4359                 I915_WRITE(PF_WIN_POS(pipe), crtc->config->pch_pfit.pos);
4360                 I915_WRITE(PF_WIN_SZ(pipe), crtc->config->pch_pfit.size);
4361         }
4362 }
4363
4364 void hsw_enable_ips(struct intel_crtc *crtc)
4365 {
4366         struct drm_device *dev = crtc->base.dev;
4367         struct drm_i915_private *dev_priv = dev->dev_private;
4368
4369         if (!crtc->config->ips_enabled)
4370                 return;
4371
4372         /*
4373          * We can only enable IPS after we enable a plane and wait for a vblank
4374          * This function is called from post_plane_update, which is run after
4375          * a vblank wait.
4376          */
4377
4378         assert_plane_enabled(dev_priv, crtc->plane);
4379         if (IS_BROADWELL(dev)) {
4380                 mutex_lock(&dev_priv->rps.hw_lock);
4381                 WARN_ON(sandybridge_pcode_write(dev_priv, DISPLAY_IPS_CONTROL, 0xc0000000));
4382                 mutex_unlock(&dev_priv->rps.hw_lock);
4383                 /* Quoting Art Runyan: "its not safe to expect any particular
4384                  * value in IPS_CTL bit 31 after enabling IPS through the
4385                  * mailbox." Moreover, the mailbox may return a bogus state,
4386                  * so we need to just enable it and continue on.
4387                  */
4388         } else {
4389                 I915_WRITE(IPS_CTL, IPS_ENABLE);
4390                 /* The bit only becomes 1 in the next vblank, so this wait here
4391                  * is essentially intel_wait_for_vblank. If we don't have this
4392                  * and don't wait for vblanks until the end of crtc_enable, then
4393                  * the HW state readout code will complain that the expected
4394                  * IPS_CTL value is not the one we read. */
4395                 if (wait_for(I915_READ_NOTRACE(IPS_CTL) & IPS_ENABLE, 50))
4396                         DRM_ERROR("Timed out waiting for IPS enable\n");
4397         }
4398 }
4399
4400 void hsw_disable_ips(struct intel_crtc *crtc)
4401 {
4402         struct drm_device *dev = crtc->base.dev;
4403         struct drm_i915_private *dev_priv = dev->dev_private;
4404
4405         if (!crtc->config->ips_enabled)
4406                 return;
4407
4408         assert_plane_enabled(dev_priv, crtc->plane);
4409         if (IS_BROADWELL(dev)) {
4410                 mutex_lock(&dev_priv->rps.hw_lock);
4411                 WARN_ON(sandybridge_pcode_write(dev_priv, DISPLAY_IPS_CONTROL, 0));
4412                 mutex_unlock(&dev_priv->rps.hw_lock);
4413                 /* wait for pcode to finish disabling IPS, which may take up to 42ms */
4414                 if (wait_for((I915_READ(IPS_CTL) & IPS_ENABLE) == 0, 42))
4415                         DRM_ERROR("Timed out waiting for IPS disable\n");
4416         } else {
4417                 I915_WRITE(IPS_CTL, 0);
4418                 POSTING_READ(IPS_CTL);
4419         }
4420
4421         /* We need to wait for a vblank before we can disable the plane. */
4422         intel_wait_for_vblank(dev, crtc->pipe);
4423 }
4424
4425 static void intel_crtc_dpms_overlay_disable(struct intel_crtc *intel_crtc)
4426 {
4427         if (intel_crtc->overlay) {
4428                 struct drm_device *dev = intel_crtc->base.dev;
4429                 struct drm_i915_private *dev_priv = dev->dev_private;
4430
4431                 mutex_lock(&dev->struct_mutex);
4432                 dev_priv->mm.interruptible = false;
4433                 (void) intel_overlay_switch_off(intel_crtc->overlay);
4434                 dev_priv->mm.interruptible = true;
4435                 mutex_unlock(&dev->struct_mutex);
4436         }
4437
4438         /* Let userspace switch the overlay on again. In most cases userspace
4439          * has to recompute where to put it anyway.
4440          */
4441 }
4442
4443 /**
4444  * intel_post_enable_primary - Perform operations after enabling primary plane
4445  * @crtc: the CRTC whose primary plane was just enabled
4446  *
4447  * Performs potentially sleeping operations that must be done after the primary
4448  * plane is enabled, such as updating FBC and IPS.  Note that this may be
4449  * called due to an explicit primary plane update, or due to an implicit
4450  * re-enable that is caused when a sprite plane is updated to no longer
4451  * completely hide the primary plane.
4452  */
4453 static void
4454 intel_post_enable_primary(struct drm_crtc *crtc)
4455 {
4456         struct drm_device *dev = crtc->dev;
4457         struct drm_i915_private *dev_priv = dev->dev_private;
4458         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4459         int pipe = intel_crtc->pipe;
4460
4461         /*
4462          * FIXME IPS should be fine as long as one plane is
4463          * enabled, but in practice it seems to have problems
4464          * when going from primary only to sprite only and vice
4465          * versa.
4466          */
4467         hsw_enable_ips(intel_crtc);
4468
4469         /*
4470          * Gen2 reports pipe underruns whenever all planes are disabled.
4471          * So don't enable underrun reporting before at least some planes
4472          * are enabled.
4473          * FIXME: Need to fix the logic to work when we turn off all planes
4474          * but leave the pipe running.
4475          */
4476         if (IS_GEN2(dev))
4477                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
4478
4479         /* Underruns don't always raise interrupts, so check manually. */
4480         intel_check_cpu_fifo_underruns(dev_priv);
4481         intel_check_pch_fifo_underruns(dev_priv);
4482 }
4483
4484 /* FIXME move all this to pre_plane_update() with proper state tracking */
4485 static void
4486 intel_pre_disable_primary(struct drm_crtc *crtc)
4487 {
4488         struct drm_device *dev = crtc->dev;
4489         struct drm_i915_private *dev_priv = dev->dev_private;
4490         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4491         int pipe = intel_crtc->pipe;
4492
4493         /*
4494          * Gen2 reports pipe underruns whenever all planes are disabled.
4495          * So diasble underrun reporting before all the planes get disabled.
4496          * FIXME: Need to fix the logic to work when we turn off all planes
4497          * but leave the pipe running.
4498          */
4499         if (IS_GEN2(dev))
4500                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, false);
4501
4502         /*
4503          * FIXME IPS should be fine as long as one plane is
4504          * enabled, but in practice it seems to have problems
4505          * when going from primary only to sprite only and vice
4506          * versa.
4507          */
4508         hsw_disable_ips(intel_crtc);
4509 }
4510
4511 /* FIXME get rid of this and use pre_plane_update */
4512 static void
4513 intel_pre_disable_primary_noatomic(struct drm_crtc *crtc)
4514 {
4515         struct drm_device *dev = crtc->dev;
4516         struct drm_i915_private *dev_priv = dev->dev_private;
4517         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4518         int pipe = intel_crtc->pipe;
4519
4520         intel_pre_disable_primary(crtc);
4521
4522         /*
4523          * Vblank time updates from the shadow to live plane control register
4524          * are blocked if the memory self-refresh mode is active at that
4525          * moment. So to make sure the plane gets truly disabled, disable
4526          * first the self-refresh mode. The self-refresh enable bit in turn
4527          * will be checked/applied by the HW only at the next frame start
4528          * event which is after the vblank start event, so we need to have a
4529          * wait-for-vblank between disabling the plane and the pipe.
4530          */
4531         if (HAS_GMCH_DISPLAY(dev)) {
4532                 intel_set_memory_cxsr(dev_priv, false);
4533                 dev_priv->wm.vlv.cxsr = false;
4534                 intel_wait_for_vblank(dev, pipe);
4535         }
4536 }
4537
4538 static void intel_pre_plane_update(struct intel_crtc_state *old_crtc_state)
4539 {
4540         struct intel_crtc *crtc = to_intel_crtc(old_crtc_state->base.crtc);
4541         struct drm_device *dev = crtc->base.dev;
4542         struct drm_i915_private *dev_priv = dev->dev_private;
4543         struct intel_crtc_state *pipe_config =
4544                 to_intel_crtc_state(crtc->base.state);
4545         struct drm_atomic_state *old_state = old_crtc_state->base.state;
4546         struct drm_plane *primary = crtc->base.primary;
4547         struct drm_plane_state *old_pri_state =
4548                 drm_atomic_get_existing_plane_state(old_state, primary);
4549         bool modeset = needs_modeset(&pipe_config->base);
4550
4551         if (old_pri_state) {
4552                 struct intel_plane_state *primary_state =
4553                         to_intel_plane_state(primary->state);
4554                 struct intel_plane_state *old_primary_state =
4555                         to_intel_plane_state(old_pri_state);
4556
4557                 intel_fbc_pre_update(crtc, pipe_config, primary_state);
4558
4559                 if (old_primary_state->visible &&
4560                     (modeset || !primary_state->visible))
4561                         intel_pre_disable_primary(&crtc->base);
4562         }
4563
4564         if (pipe_config->disable_cxsr) {
4565                 crtc->wm.cxsr_allowed = false;
4566
4567                 /*
4568                  * Vblank time updates from the shadow to live plane control register
4569                  * are blocked if the memory self-refresh mode is active at that
4570                  * moment. So to make sure the plane gets truly disabled, disable
4571                  * first the self-refresh mode. The self-refresh enable bit in turn
4572                  * will be checked/applied by the HW only at the next frame start
4573                  * event which is after the vblank start event, so we need to have a
4574                  * wait-for-vblank between disabling the plane and the pipe.
4575                  */
4576                 if (old_crtc_state->base.active) {
4577                         intel_set_memory_cxsr(dev_priv, false);
4578                         dev_priv->wm.vlv.cxsr = false;
4579                         intel_wait_for_vblank(dev, crtc->pipe);
4580                 }
4581         }
4582
4583         /*
4584          * IVB workaround: must disable low power watermarks for at least
4585          * one frame before enabling scaling.  LP watermarks can be re-enabled
4586          * when scaling is disabled.
4587          *
4588          * WaCxSRDisabledForSpriteScaling:ivb
4589          */
4590         if (pipe_config->disable_lp_wm) {
4591                 ilk_disable_lp_wm(dev);
4592                 intel_wait_for_vblank(dev, crtc->pipe);
4593         }
4594
4595         /*
4596          * If we're doing a modeset, we're done.  No need to do any pre-vblank
4597          * watermark programming here.
4598          */
4599         if (needs_modeset(&pipe_config->base))
4600                 return;
4601
4602         /*
4603          * For platforms that support atomic watermarks, program the
4604          * 'intermediate' watermarks immediately.  On pre-gen9 platforms, these
4605          * will be the intermediate values that are safe for both pre- and
4606          * post- vblank; when vblank happens, the 'active' values will be set
4607          * to the final 'target' values and we'll do this again to get the
4608          * optimal watermarks.  For gen9+ platforms, the values we program here
4609          * will be the final target values which will get automatically latched
4610          * at vblank time; no further programming will be necessary.
4611          *
4612          * If a platform hasn't been transitioned to atomic watermarks yet,
4613          * we'll continue to update watermarks the old way, if flags tell
4614          * us to.
4615          */
4616         if (dev_priv->display.initial_watermarks != NULL)
4617                 dev_priv->display.initial_watermarks(pipe_config);
4618         else if (pipe_config->update_wm_pre)
4619                 intel_update_watermarks(&crtc->base);
4620 }
4621
4622 static void intel_crtc_disable_planes(struct drm_crtc *crtc, unsigned plane_mask)
4623 {
4624         struct drm_device *dev = crtc->dev;
4625         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4626         struct drm_plane *p;
4627         int pipe = intel_crtc->pipe;
4628
4629         intel_crtc_dpms_overlay_disable(intel_crtc);
4630
4631         drm_for_each_plane_mask(p, dev, plane_mask)
4632                 to_intel_plane(p)->disable_plane(p, crtc);
4633
4634         /*
4635          * FIXME: Once we grow proper nuclear flip support out of this we need
4636          * to compute the mask of flip planes precisely. For the time being
4637          * consider this a flip to a NULL plane.
4638          */
4639         intel_frontbuffer_flip(dev, INTEL_FRONTBUFFER_ALL_MASK(pipe));
4640 }
4641
4642 static void ironlake_crtc_enable(struct drm_crtc *crtc)
4643 {
4644         struct drm_device *dev = crtc->dev;
4645         struct drm_i915_private *dev_priv = dev->dev_private;
4646         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4647         struct intel_encoder *encoder;
4648         int pipe = intel_crtc->pipe;
4649         struct intel_crtc_state *pipe_config =
4650                 to_intel_crtc_state(crtc->state);
4651
4652         if (WARN_ON(intel_crtc->active))
4653                 return;
4654
4655         /*
4656          * Sometimes spurious CPU pipe underruns happen during FDI
4657          * training, at least with VGA+HDMI cloning. Suppress them.
4658          *
4659          * On ILK we get an occasional spurious CPU pipe underruns
4660          * between eDP port A enable and vdd enable. Also PCH port
4661          * enable seems to result in the occasional CPU pipe underrun.
4662          *
4663          * Spurious PCH underruns also occur during PCH enabling.
4664          */
4665         if (intel_crtc->config->has_pch_encoder || IS_GEN5(dev_priv))
4666                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, false);
4667         if (intel_crtc->config->has_pch_encoder)
4668                 intel_set_pch_fifo_underrun_reporting(dev_priv, pipe, false);
4669
4670         if (intel_crtc->config->has_pch_encoder)
4671                 intel_prepare_shared_dpll(intel_crtc);
4672
4673         if (intel_crtc->config->has_dp_encoder)
4674                 intel_dp_set_m_n(intel_crtc, M1_N1);
4675
4676         intel_set_pipe_timings(intel_crtc);
4677         intel_set_pipe_src_size(intel_crtc);
4678
4679         if (intel_crtc->config->has_pch_encoder) {
4680                 intel_cpu_transcoder_set_m_n(intel_crtc,
4681                                      &intel_crtc->config->fdi_m_n, NULL);
4682         }
4683
4684         ironlake_set_pipeconf(crtc);
4685
4686         intel_crtc->active = true;
4687
4688         for_each_encoder_on_crtc(dev, crtc, encoder)
4689                 if (encoder->pre_enable)
4690                         encoder->pre_enable(encoder);
4691
4692         if (intel_crtc->config->has_pch_encoder) {
4693                 /* Note: FDI PLL enabling _must_ be done before we enable the
4694                  * cpu pipes, hence this is separate from all the other fdi/pch
4695                  * enabling. */
4696                 ironlake_fdi_pll_enable(intel_crtc);
4697         } else {
4698                 assert_fdi_tx_disabled(dev_priv, pipe);
4699                 assert_fdi_rx_disabled(dev_priv, pipe);
4700         }
4701
4702         ironlake_pfit_enable(intel_crtc);
4703
4704         /*
4705          * On ILK+ LUT must be loaded before the pipe is running but with
4706          * clocks enabled
4707          */
4708         intel_color_load_luts(&pipe_config->base);
4709
4710         if (dev_priv->display.initial_watermarks != NULL)
4711                 dev_priv->display.initial_watermarks(intel_crtc->config);
4712         intel_enable_pipe(intel_crtc);
4713
4714         if (intel_crtc->config->has_pch_encoder)
4715                 ironlake_pch_enable(crtc);
4716
4717         assert_vblank_disabled(crtc);
4718         drm_crtc_vblank_on(crtc);
4719
4720         for_each_encoder_on_crtc(dev, crtc, encoder)
4721                 encoder->enable(encoder);
4722
4723         if (HAS_PCH_CPT(dev))
4724                 cpt_verify_modeset(dev, intel_crtc->pipe);
4725
4726         /* Must wait for vblank to avoid spurious PCH FIFO underruns */
4727         if (intel_crtc->config->has_pch_encoder)
4728                 intel_wait_for_vblank(dev, pipe);
4729         intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
4730         intel_set_pch_fifo_underrun_reporting(dev_priv, pipe, true);
4731 }
4732
4733 /* IPS only exists on ULT machines and is tied to pipe A. */
4734 static bool hsw_crtc_supports_ips(struct intel_crtc *crtc)
4735 {
4736         return HAS_IPS(crtc->base.dev) && crtc->pipe == PIPE_A;
4737 }
4738
4739 static void haswell_crtc_enable(struct drm_crtc *crtc)
4740 {
4741         struct drm_device *dev = crtc->dev;
4742         struct drm_i915_private *dev_priv = dev->dev_private;
4743         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4744         struct intel_encoder *encoder;
4745         int pipe = intel_crtc->pipe, hsw_workaround_pipe;
4746         enum transcoder cpu_transcoder = intel_crtc->config->cpu_transcoder;
4747         struct intel_crtc_state *pipe_config =
4748                 to_intel_crtc_state(crtc->state);
4749
4750         if (WARN_ON(intel_crtc->active))
4751                 return;
4752
4753         if (intel_crtc->config->has_pch_encoder)
4754                 intel_set_pch_fifo_underrun_reporting(dev_priv, TRANSCODER_A,
4755                                                       false);
4756
4757         if (intel_crtc->config->shared_dpll)
4758                 intel_enable_shared_dpll(intel_crtc);
4759
4760         if (intel_crtc->config->has_dp_encoder)
4761                 intel_dp_set_m_n(intel_crtc, M1_N1);
4762
4763         if (!intel_crtc->config->has_dsi_encoder)
4764                 intel_set_pipe_timings(intel_crtc);
4765
4766         intel_set_pipe_src_size(intel_crtc);
4767
4768         if (cpu_transcoder != TRANSCODER_EDP &&
4769             !transcoder_is_dsi(cpu_transcoder)) {
4770                 I915_WRITE(PIPE_MULT(cpu_transcoder),
4771                            intel_crtc->config->pixel_multiplier - 1);
4772         }
4773
4774         if (intel_crtc->config->has_pch_encoder) {
4775                 intel_cpu_transcoder_set_m_n(intel_crtc,
4776                                      &intel_crtc->config->fdi_m_n, NULL);
4777         }
4778
4779         if (!intel_crtc->config->has_dsi_encoder)
4780                 haswell_set_pipeconf(crtc);
4781
4782         haswell_set_pipemisc(crtc);
4783
4784         intel_color_set_csc(&pipe_config->base);
4785
4786         intel_crtc->active = true;
4787
4788         if (intel_crtc->config->has_pch_encoder)
4789                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, false);
4790         else
4791                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
4792
4793         for_each_encoder_on_crtc(dev, crtc, encoder) {
4794                 if (encoder->pre_enable)
4795                         encoder->pre_enable(encoder);
4796         }
4797
4798         if (intel_crtc->config->has_pch_encoder)
4799                 dev_priv->display.fdi_link_train(crtc);
4800
4801         if (!intel_crtc->config->has_dsi_encoder)
4802                 intel_ddi_enable_pipe_clock(intel_crtc);
4803
4804         if (INTEL_INFO(dev)->gen >= 9)
4805                 skylake_pfit_enable(intel_crtc);
4806         else
4807                 ironlake_pfit_enable(intel_crtc);
4808
4809         /*
4810          * On ILK+ LUT must be loaded before the pipe is running but with
4811          * clocks enabled
4812          */
4813         intel_color_load_luts(&pipe_config->base);
4814
4815         intel_ddi_set_pipe_settings(crtc);
4816         if (!intel_crtc->config->has_dsi_encoder)
4817                 intel_ddi_enable_transcoder_func(crtc);
4818
4819         if (dev_priv->display.initial_watermarks != NULL)
4820                 dev_priv->display.initial_watermarks(pipe_config);
4821         else
4822                 intel_update_watermarks(crtc);
4823
4824         /* XXX: Do the pipe assertions at the right place for BXT DSI. */
4825         if (!intel_crtc->config->has_dsi_encoder)
4826                 intel_enable_pipe(intel_crtc);
4827
4828         if (intel_crtc->config->has_pch_encoder)
4829                 lpt_pch_enable(crtc);
4830
4831         if (intel_crtc->config->dp_encoder_is_mst)
4832                 intel_ddi_set_vc_payload_alloc(crtc, true);
4833
4834         assert_vblank_disabled(crtc);
4835         drm_crtc_vblank_on(crtc);
4836
4837         for_each_encoder_on_crtc(dev, crtc, encoder) {
4838                 encoder->enable(encoder);
4839                 intel_opregion_notify_encoder(encoder, true);
4840         }
4841
4842         if (intel_crtc->config->has_pch_encoder) {
4843                 intel_wait_for_vblank(dev, pipe);
4844                 intel_wait_for_vblank(dev, pipe);
4845                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
4846                 intel_set_pch_fifo_underrun_reporting(dev_priv, TRANSCODER_A,
4847                                                       true);
4848         }
4849
4850         /* If we change the relative order between pipe/planes enabling, we need
4851          * to change the workaround. */
4852         hsw_workaround_pipe = pipe_config->hsw_workaround_pipe;
4853         if (IS_HASWELL(dev) && hsw_workaround_pipe != INVALID_PIPE) {
4854                 intel_wait_for_vblank(dev, hsw_workaround_pipe);
4855                 intel_wait_for_vblank(dev, hsw_workaround_pipe);
4856         }
4857 }
4858
4859 static void ironlake_pfit_disable(struct intel_crtc *crtc, bool force)
4860 {
4861         struct drm_device *dev = crtc->base.dev;
4862         struct drm_i915_private *dev_priv = dev->dev_private;
4863         int pipe = crtc->pipe;
4864
4865         /* To avoid upsetting the power well on haswell only disable the pfit if
4866          * it's in use. The hw state code will make sure we get this right. */
4867         if (force || crtc->config->pch_pfit.enabled) {
4868                 I915_WRITE(PF_CTL(pipe), 0);
4869                 I915_WRITE(PF_WIN_POS(pipe), 0);
4870                 I915_WRITE(PF_WIN_SZ(pipe), 0);
4871         }
4872 }
4873
4874 static void ironlake_crtc_disable(struct drm_crtc *crtc)
4875 {
4876         struct drm_device *dev = crtc->dev;
4877         struct drm_i915_private *dev_priv = dev->dev_private;
4878         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4879         struct intel_encoder *encoder;
4880         int pipe = intel_crtc->pipe;
4881
4882         /*
4883          * Sometimes spurious CPU pipe underruns happen when the
4884          * pipe is already disabled, but FDI RX/TX is still enabled.
4885          * Happens at least with VGA+HDMI cloning. Suppress them.
4886          */
4887         if (intel_crtc->config->has_pch_encoder) {
4888                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, false);
4889                 intel_set_pch_fifo_underrun_reporting(dev_priv, pipe, false);
4890         }
4891
4892         for_each_encoder_on_crtc(dev, crtc, encoder)
4893                 encoder->disable(encoder);
4894
4895         drm_crtc_vblank_off(crtc);
4896         assert_vblank_disabled(crtc);
4897
4898         intel_disable_pipe(intel_crtc);
4899
4900         ironlake_pfit_disable(intel_crtc, false);
4901
4902         if (intel_crtc->config->has_pch_encoder)
4903                 ironlake_fdi_disable(crtc);
4904
4905         for_each_encoder_on_crtc(dev, crtc, encoder)
4906                 if (encoder->post_disable)
4907                         encoder->post_disable(encoder);
4908
4909         if (intel_crtc->config->has_pch_encoder) {
4910                 ironlake_disable_pch_transcoder(dev_priv, pipe);
4911
4912                 if (HAS_PCH_CPT(dev)) {
4913                         i915_reg_t reg;
4914                         u32 temp;
4915
4916                         /* disable TRANS_DP_CTL */
4917                         reg = TRANS_DP_CTL(pipe);
4918                         temp = I915_READ(reg);
4919                         temp &= ~(TRANS_DP_OUTPUT_ENABLE |
4920                                   TRANS_DP_PORT_SEL_MASK);
4921                         temp |= TRANS_DP_PORT_SEL_NONE;
4922                         I915_WRITE(reg, temp);
4923
4924                         /* disable DPLL_SEL */
4925                         temp = I915_READ(PCH_DPLL_SEL);
4926                         temp &= ~(TRANS_DPLL_ENABLE(pipe) | TRANS_DPLLB_SEL(pipe));
4927                         I915_WRITE(PCH_DPLL_SEL, temp);
4928                 }
4929
4930                 ironlake_fdi_pll_disable(intel_crtc);
4931         }
4932
4933         intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
4934         intel_set_pch_fifo_underrun_reporting(dev_priv, pipe, true);
4935 }
4936
4937 static void haswell_crtc_disable(struct drm_crtc *crtc)
4938 {
4939         struct drm_device *dev = crtc->dev;
4940         struct drm_i915_private *dev_priv = dev->dev_private;
4941         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4942         struct intel_encoder *encoder;
4943         enum transcoder cpu_transcoder = intel_crtc->config->cpu_transcoder;
4944
4945         if (intel_crtc->config->has_pch_encoder)
4946                 intel_set_pch_fifo_underrun_reporting(dev_priv, TRANSCODER_A,
4947                                                       false);
4948
4949         for_each_encoder_on_crtc(dev, crtc, encoder) {
4950                 intel_opregion_notify_encoder(encoder, false);
4951                 encoder->disable(encoder);
4952         }
4953
4954         drm_crtc_vblank_off(crtc);
4955         assert_vblank_disabled(crtc);
4956
4957         /* XXX: Do the pipe assertions at the right place for BXT DSI. */
4958         if (!intel_crtc->config->has_dsi_encoder)
4959                 intel_disable_pipe(intel_crtc);
4960
4961         if (intel_crtc->config->dp_encoder_is_mst)
4962                 intel_ddi_set_vc_payload_alloc(crtc, false);
4963
4964         if (!intel_crtc->config->has_dsi_encoder)
4965                 intel_ddi_disable_transcoder_func(dev_priv, cpu_transcoder);
4966
4967         if (INTEL_INFO(dev)->gen >= 9)
4968                 skylake_scaler_disable(intel_crtc);
4969         else
4970                 ironlake_pfit_disable(intel_crtc, false);
4971
4972         if (!intel_crtc->config->has_dsi_encoder)
4973                 intel_ddi_disable_pipe_clock(intel_crtc);
4974
4975         for_each_encoder_on_crtc(dev, crtc, encoder)
4976                 if (encoder->post_disable)
4977                         encoder->post_disable(encoder);
4978
4979         if (intel_crtc->config->has_pch_encoder) {
4980                 lpt_disable_pch_transcoder(dev_priv);
4981                 lpt_disable_iclkip(dev_priv);
4982                 intel_ddi_fdi_disable(crtc);
4983
4984                 intel_set_pch_fifo_underrun_reporting(dev_priv, TRANSCODER_A,
4985                                                       true);
4986         }
4987 }
4988
4989 static void i9xx_pfit_enable(struct intel_crtc *crtc)
4990 {
4991         struct drm_device *dev = crtc->base.dev;
4992         struct drm_i915_private *dev_priv = dev->dev_private;
4993         struct intel_crtc_state *pipe_config = crtc->config;
4994
4995         if (!pipe_config->gmch_pfit.control)
4996                 return;
4997
4998         /*
4999          * The panel fitter should only be adjusted whilst the pipe is disabled,
5000          * according to register description and PRM.
5001          */
5002         WARN_ON(I915_READ(PFIT_CONTROL) & PFIT_ENABLE);
5003         assert_pipe_disabled(dev_priv, crtc->pipe);
5004
5005         I915_WRITE(PFIT_PGM_RATIOS, pipe_config->gmch_pfit.pgm_ratios);
5006         I915_WRITE(PFIT_CONTROL, pipe_config->gmch_pfit.control);
5007
5008         /* Border color in case we don't scale up to the full screen. Black by
5009          * default, change to something else for debugging. */
5010         I915_WRITE(BCLRPAT(crtc->pipe), 0);
5011 }
5012
5013 static enum intel_display_power_domain port_to_power_domain(enum port port)
5014 {
5015         switch (port) {
5016         case PORT_A:
5017                 return POWER_DOMAIN_PORT_DDI_A_LANES;
5018         case PORT_B:
5019                 return POWER_DOMAIN_PORT_DDI_B_LANES;
5020         case PORT_C:
5021                 return POWER_DOMAIN_PORT_DDI_C_LANES;
5022         case PORT_D:
5023                 return POWER_DOMAIN_PORT_DDI_D_LANES;
5024         case PORT_E:
5025                 return POWER_DOMAIN_PORT_DDI_E_LANES;
5026         default:
5027                 MISSING_CASE(port);
5028                 return POWER_DOMAIN_PORT_OTHER;
5029         }
5030 }
5031
5032 static enum intel_display_power_domain port_to_aux_power_domain(enum port port)
5033 {
5034         switch (port) {
5035         case PORT_A:
5036                 return POWER_DOMAIN_AUX_A;
5037         case PORT_B:
5038                 return POWER_DOMAIN_AUX_B;
5039         case PORT_C:
5040                 return POWER_DOMAIN_AUX_C;
5041         case PORT_D:
5042                 return POWER_DOMAIN_AUX_D;
5043         case PORT_E:
5044                 /* FIXME: Check VBT for actual wiring of PORT E */
5045                 return POWER_DOMAIN_AUX_D;
5046         default:
5047                 MISSING_CASE(port);
5048                 return POWER_DOMAIN_AUX_A;
5049         }
5050 }
5051
5052 enum intel_display_power_domain
5053 intel_display_port_power_domain(struct intel_encoder *intel_encoder)
5054 {
5055         struct drm_device *dev = intel_encoder->base.dev;
5056         struct intel_digital_port *intel_dig_port;
5057
5058         switch (intel_encoder->type) {
5059         case INTEL_OUTPUT_UNKNOWN:
5060                 /* Only DDI platforms should ever use this output type */
5061                 WARN_ON_ONCE(!HAS_DDI(dev));
5062         case INTEL_OUTPUT_DISPLAYPORT:
5063         case INTEL_OUTPUT_HDMI:
5064         case INTEL_OUTPUT_EDP:
5065                 intel_dig_port = enc_to_dig_port(&intel_encoder->base);
5066                 return port_to_power_domain(intel_dig_port->port);
5067         case INTEL_OUTPUT_DP_MST:
5068                 intel_dig_port = enc_to_mst(&intel_encoder->base)->primary;
5069                 return port_to_power_domain(intel_dig_port->port);
5070         case INTEL_OUTPUT_ANALOG:
5071                 return POWER_DOMAIN_PORT_CRT;
5072         case INTEL_OUTPUT_DSI:
5073                 return POWER_DOMAIN_PORT_DSI;
5074         default:
5075                 return POWER_DOMAIN_PORT_OTHER;
5076         }
5077 }
5078
5079 enum intel_display_power_domain
5080 intel_display_port_aux_power_domain(struct intel_encoder *intel_encoder)
5081 {
5082         struct drm_device *dev = intel_encoder->base.dev;
5083         struct intel_digital_port *intel_dig_port;
5084
5085         switch (intel_encoder->type) {
5086         case INTEL_OUTPUT_UNKNOWN:
5087         case INTEL_OUTPUT_HDMI:
5088                 /*
5089                  * Only DDI platforms should ever use these output types.
5090                  * We can get here after the HDMI detect code has already set
5091                  * the type of the shared encoder. Since we can't be sure
5092                  * what's the status of the given connectors, play safe and
5093                  * run the DP detection too.
5094                  */
5095                 WARN_ON_ONCE(!HAS_DDI(dev));
5096         case INTEL_OUTPUT_DISPLAYPORT:
5097         case INTEL_OUTPUT_EDP:
5098                 intel_dig_port = enc_to_dig_port(&intel_encoder->base);
5099                 return port_to_aux_power_domain(intel_dig_port->port);
5100         case INTEL_OUTPUT_DP_MST:
5101                 intel_dig_port = enc_to_mst(&intel_encoder->base)->primary;
5102                 return port_to_aux_power_domain(intel_dig_port->port);
5103         default:
5104                 MISSING_CASE(intel_encoder->type);
5105                 return POWER_DOMAIN_AUX_A;
5106         }
5107 }
5108
5109 static unsigned long get_crtc_power_domains(struct drm_crtc *crtc,
5110                                             struct intel_crtc_state *crtc_state)
5111 {
5112         struct drm_device *dev = crtc->dev;
5113         struct drm_encoder *encoder;
5114         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5115         enum pipe pipe = intel_crtc->pipe;
5116         unsigned long mask;
5117         enum transcoder transcoder = crtc_state->cpu_transcoder;
5118
5119         if (!crtc_state->base.active)
5120                 return 0;
5121
5122         mask = BIT(POWER_DOMAIN_PIPE(pipe));
5123         mask |= BIT(POWER_DOMAIN_TRANSCODER(transcoder));
5124         if (crtc_state->pch_pfit.enabled ||
5125             crtc_state->pch_pfit.force_thru)
5126                 mask |= BIT(POWER_DOMAIN_PIPE_PANEL_FITTER(pipe));
5127
5128         drm_for_each_encoder_mask(encoder, dev, crtc_state->base.encoder_mask) {
5129                 struct intel_encoder *intel_encoder = to_intel_encoder(encoder);
5130
5131                 mask |= BIT(intel_display_port_power_domain(intel_encoder));
5132         }
5133
5134         if (crtc_state->shared_dpll)
5135                 mask |= BIT(POWER_DOMAIN_PLLS);
5136
5137         return mask;
5138 }
5139
5140 static unsigned long
5141 modeset_get_crtc_power_domains(struct drm_crtc *crtc,
5142                                struct intel_crtc_state *crtc_state)
5143 {
5144         struct drm_i915_private *dev_priv = crtc->dev->dev_private;
5145         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5146         enum intel_display_power_domain domain;
5147         unsigned long domains, new_domains, old_domains, ms_domain = 0;
5148
5149         old_domains = intel_crtc->enabled_power_domains;
5150         intel_crtc->enabled_power_domains = new_domains =
5151                 get_crtc_power_domains(crtc, crtc_state);
5152
5153         if (needs_modeset(&crtc_state->base))
5154                 ms_domain = BIT(POWER_DOMAIN_MODESET);
5155
5156         domains = (new_domains & ~old_domains) | ms_domain;
5157
5158         for_each_power_domain(domain, domains)
5159                 intel_display_power_get(dev_priv, domain);
5160
5161         return (old_domains & ~new_domains) | ms_domain;
5162 }
5163
5164 static void modeset_put_power_domains(struct drm_i915_private *dev_priv,
5165                                       unsigned long domains)
5166 {
5167         enum intel_display_power_domain domain;
5168
5169         for_each_power_domain(domain, domains)
5170                 intel_display_power_put(dev_priv, domain);
5171 }
5172
5173 static int intel_compute_max_dotclk(struct drm_i915_private *dev_priv)
5174 {
5175         int max_cdclk_freq = dev_priv->max_cdclk_freq;
5176
5177         if (INTEL_INFO(dev_priv)->gen >= 9 ||
5178             IS_HASWELL(dev_priv) || IS_BROADWELL(dev_priv))
5179                 return max_cdclk_freq;
5180         else if (IS_CHERRYVIEW(dev_priv))
5181                 return max_cdclk_freq*95/100;
5182         else if (INTEL_INFO(dev_priv)->gen < 4)
5183                 return 2*max_cdclk_freq*90/100;
5184         else
5185                 return max_cdclk_freq*90/100;
5186 }
5187
5188 static void intel_update_max_cdclk(struct drm_device *dev)
5189 {
5190         struct drm_i915_private *dev_priv = dev->dev_private;
5191
5192         if (IS_SKYLAKE(dev) || IS_KABYLAKE(dev)) {
5193                 u32 limit = I915_READ(SKL_DFSM) & SKL_DFSM_CDCLK_LIMIT_MASK;
5194
5195                 if (limit == SKL_DFSM_CDCLK_LIMIT_675)
5196                         dev_priv->max_cdclk_freq = 675000;
5197                 else if (limit == SKL_DFSM_CDCLK_LIMIT_540)
5198                         dev_priv->max_cdclk_freq = 540000;
5199                 else if (limit == SKL_DFSM_CDCLK_LIMIT_450)
5200                         dev_priv->max_cdclk_freq = 450000;
5201                 else
5202                         dev_priv->max_cdclk_freq = 337500;
5203         } else if (IS_BROXTON(dev)) {
5204                 dev_priv->max_cdclk_freq = 624000;
5205         } else if (IS_BROADWELL(dev))  {
5206                 /*
5207                  * FIXME with extra cooling we can allow
5208                  * 540 MHz for ULX and 675 Mhz for ULT.
5209                  * How can we know if extra cooling is
5210                  * available? PCI ID, VTB, something else?
5211                  */
5212                 if (I915_READ(FUSE_STRAP) & HSW_CDCLK_LIMIT)
5213                         dev_priv->max_cdclk_freq = 450000;
5214                 else if (IS_BDW_ULX(dev))
5215                         dev_priv->max_cdclk_freq = 450000;
5216                 else if (IS_BDW_ULT(dev))
5217                         dev_priv->max_cdclk_freq = 540000;
5218                 else
5219                         dev_priv->max_cdclk_freq = 675000;
5220         } else if (IS_CHERRYVIEW(dev)) {
5221                 dev_priv->max_cdclk_freq = 320000;
5222         } else if (IS_VALLEYVIEW(dev)) {
5223                 dev_priv->max_cdclk_freq = 400000;
5224         } else {
5225                 /* otherwise assume cdclk is fixed */
5226                 dev_priv->max_cdclk_freq = dev_priv->cdclk_freq;
5227         }
5228
5229         dev_priv->max_dotclk_freq = intel_compute_max_dotclk(dev_priv);
5230
5231         DRM_DEBUG_DRIVER("Max CD clock rate: %d kHz\n",
5232                          dev_priv->max_cdclk_freq);
5233
5234         DRM_DEBUG_DRIVER("Max dotclock rate: %d kHz\n",
5235                          dev_priv->max_dotclk_freq);
5236 }
5237
5238 static void intel_update_cdclk(struct drm_device *dev)
5239 {
5240         struct drm_i915_private *dev_priv = dev->dev_private;
5241
5242         dev_priv->cdclk_freq = dev_priv->display.get_display_clock_speed(dev);
5243         DRM_DEBUG_DRIVER("Current CD clock rate: %d kHz\n",
5244                          dev_priv->cdclk_freq);
5245
5246         /*
5247          * 9:0 CMBUS [sic] CDCLK frequency (cdfreq):
5248          * Programmng [sic] note: bit[9:2] should be programmed to the number
5249          * of cdclk that generates 4MHz reference clock freq which is used to
5250          * generate GMBus clock. This will vary with the cdclk freq.
5251          */
5252         if (IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv))
5253                 I915_WRITE(GMBUSFREQ_VLV, DIV_ROUND_UP(dev_priv->cdclk_freq, 1000));
5254
5255         if (dev_priv->max_cdclk_freq == 0)
5256                 intel_update_max_cdclk(dev);
5257 }
5258
5259 /* convert from kHz to .1 fixpoint MHz with -1MHz offset */
5260 static int skl_cdclk_decimal(int cdclk)
5261 {
5262         return DIV_ROUND_CLOSEST(cdclk - 1000, 500);
5263 }
5264
5265 static void broxton_set_cdclk(struct drm_i915_private *dev_priv, int cdclk)
5266 {
5267         uint32_t divider;
5268         uint32_t ratio;
5269         uint32_t current_cdclk;
5270         int ret;
5271
5272         /* frequency = 19.2MHz * ratio / 2 / div{1,1.5,2,4} */
5273         switch (cdclk) {
5274         case 144000:
5275                 divider = BXT_CDCLK_CD2X_DIV_SEL_4;
5276                 ratio = BXT_DE_PLL_RATIO(60);
5277                 break;
5278         case 288000:
5279                 divider = BXT_CDCLK_CD2X_DIV_SEL_2;
5280                 ratio = BXT_DE_PLL_RATIO(60);
5281                 break;
5282         case 384000:
5283                 divider = BXT_CDCLK_CD2X_DIV_SEL_1_5;
5284                 ratio = BXT_DE_PLL_RATIO(60);
5285                 break;
5286         case 576000:
5287                 divider = BXT_CDCLK_CD2X_DIV_SEL_1;
5288                 ratio = BXT_DE_PLL_RATIO(60);
5289                 break;
5290         case 624000:
5291                 divider = BXT_CDCLK_CD2X_DIV_SEL_1;
5292                 ratio = BXT_DE_PLL_RATIO(65);
5293                 break;
5294         case 19200:
5295                 /*
5296                  * Bypass frequency with DE PLL disabled. Init ratio, divider
5297                  * to suppress GCC warning.
5298                  */
5299                 ratio = 0;
5300                 divider = 0;
5301                 break;
5302         default:
5303                 DRM_ERROR("unsupported CDCLK freq %d", cdclk);
5304
5305                 return;
5306         }
5307
5308         mutex_lock(&dev_priv->rps.hw_lock);
5309         /* Inform power controller of upcoming frequency change */
5310         ret = sandybridge_pcode_write(dev_priv, HSW_PCODE_DE_WRITE_FREQ_REQ,
5311                                       0x80000000);
5312         mutex_unlock(&dev_priv->rps.hw_lock);
5313
5314         if (ret) {
5315                 DRM_ERROR("PCode CDCLK freq change notify failed (err %d, freq %d)\n",
5316                           ret, cdclk);
5317                 return;
5318         }
5319
5320         current_cdclk = I915_READ(CDCLK_CTL) & CDCLK_FREQ_DECIMAL_MASK;
5321         /* convert from .1 fixpoint MHz with -1MHz offset to kHz */
5322         current_cdclk = current_cdclk * 500 + 1000;
5323
5324         /*
5325          * DE PLL has to be disabled when
5326          * - setting to 19.2MHz (bypass, PLL isn't used)
5327          * - before setting to 624MHz (PLL needs toggling)
5328          * - before setting to any frequency from 624MHz (PLL needs toggling)
5329          */
5330         if (cdclk == 19200 || cdclk == 624000 ||
5331             current_cdclk == 624000) {
5332                 I915_WRITE(BXT_DE_PLL_ENABLE, ~BXT_DE_PLL_PLL_ENABLE);
5333                 /* Timeout 200us */
5334                 if (wait_for(!(I915_READ(BXT_DE_PLL_ENABLE) & BXT_DE_PLL_LOCK),
5335                              1))
5336                         DRM_ERROR("timout waiting for DE PLL unlock\n");
5337         }
5338
5339         if (cdclk != 19200) {
5340                 uint32_t val;
5341
5342                 val = I915_READ(BXT_DE_PLL_CTL);
5343                 val &= ~BXT_DE_PLL_RATIO_MASK;
5344                 val |= ratio;
5345                 I915_WRITE(BXT_DE_PLL_CTL, val);
5346
5347                 I915_WRITE(BXT_DE_PLL_ENABLE, BXT_DE_PLL_PLL_ENABLE);
5348                 /* Timeout 200us */
5349                 if (wait_for(I915_READ(BXT_DE_PLL_ENABLE) & BXT_DE_PLL_LOCK, 1))
5350                         DRM_ERROR("timeout waiting for DE PLL lock\n");
5351
5352                 val = divider | skl_cdclk_decimal(cdclk);
5353                 /*
5354                  * FIXME if only the cd2x divider needs changing, it could be done
5355                  * without shutting off the pipe (if only one pipe is active).
5356                  */
5357                 val |= BXT_CDCLK_CD2X_PIPE_NONE;
5358                 /*
5359                  * Disable SSA Precharge when CD clock frequency < 500 MHz,
5360                  * enable otherwise.
5361                  */
5362                 if (cdclk >= 500000)
5363                         val |= BXT_CDCLK_SSA_PRECHARGE_ENABLE;
5364                 I915_WRITE(CDCLK_CTL, val);
5365         }
5366
5367         mutex_lock(&dev_priv->rps.hw_lock);
5368         ret = sandybridge_pcode_write(dev_priv, HSW_PCODE_DE_WRITE_FREQ_REQ,
5369                                       DIV_ROUND_UP(cdclk, 25000));
5370         mutex_unlock(&dev_priv->rps.hw_lock);
5371
5372         if (ret) {
5373                 DRM_ERROR("PCode CDCLK freq set failed, (err %d, freq %d)\n",
5374                           ret, cdclk);
5375                 return;
5376         }
5377
5378         intel_update_cdclk(dev_priv->dev);
5379 }
5380
5381 static bool broxton_cdclk_is_enabled(struct drm_i915_private *dev_priv)
5382 {
5383         if (!(I915_READ(BXT_DE_PLL_ENABLE) & BXT_DE_PLL_PLL_ENABLE))
5384                 return false;
5385
5386         /* TODO: Check for a valid CDCLK rate */
5387
5388         if (!(I915_READ(DBUF_CTL) & DBUF_POWER_REQUEST)) {
5389                 DRM_DEBUG_DRIVER("CDCLK enabled, but DBUF power not requested\n");
5390
5391                 return false;
5392         }
5393
5394         if (!(I915_READ(DBUF_CTL) & DBUF_POWER_STATE)) {
5395                 DRM_DEBUG_DRIVER("CDCLK enabled, but DBUF power hasn't settled\n");
5396
5397                 return false;
5398         }
5399
5400         return true;
5401 }
5402
5403 bool broxton_cdclk_verify_state(struct drm_i915_private *dev_priv)
5404 {
5405         return broxton_cdclk_is_enabled(dev_priv);
5406 }
5407
5408 void broxton_init_cdclk(struct drm_i915_private *dev_priv)
5409 {
5410         /* check if cd clock is enabled */
5411         if (broxton_cdclk_is_enabled(dev_priv)) {
5412                 DRM_DEBUG_KMS("CDCLK already enabled, won't reprogram it\n");
5413                 return;
5414         }
5415
5416         DRM_DEBUG_KMS("CDCLK not enabled, enabling it\n");
5417
5418         /*
5419          * FIXME:
5420          * - The initial CDCLK needs to be read from VBT.
5421          *   Need to make this change after VBT has changes for BXT.
5422          * - check if setting the max (or any) cdclk freq is really necessary
5423          *   here, it belongs to modeset time
5424          */
5425         broxton_set_cdclk(dev_priv, 624000);
5426
5427         I915_WRITE(DBUF_CTL, I915_READ(DBUF_CTL) | DBUF_POWER_REQUEST);
5428         POSTING_READ(DBUF_CTL);
5429
5430         udelay(10);
5431
5432         if (!(I915_READ(DBUF_CTL) & DBUF_POWER_STATE))
5433                 DRM_ERROR("DBuf power enable timeout!\n");
5434 }
5435
5436 void broxton_uninit_cdclk(struct drm_i915_private *dev_priv)
5437 {
5438         I915_WRITE(DBUF_CTL, I915_READ(DBUF_CTL) & ~DBUF_POWER_REQUEST);
5439         POSTING_READ(DBUF_CTL);
5440
5441         udelay(10);
5442
5443         if (I915_READ(DBUF_CTL) & DBUF_POWER_STATE)
5444                 DRM_ERROR("DBuf power disable timeout!\n");
5445
5446         /* Set minimum (bypass) frequency, in effect turning off the DE PLL */
5447         broxton_set_cdclk(dev_priv, 19200);
5448 }
5449
5450 static int skl_calc_cdclk(int max_pixclk, int vco)
5451 {
5452         if (vco == 8640) {
5453                 if (max_pixclk > 540000)
5454                         return 617140;
5455                 else if (max_pixclk > 432000)
5456                         return 540000;
5457                 else if (max_pixclk > 308570)
5458                         return 432000;
5459                 else
5460                         return 308570;
5461         } else {
5462                 /* VCO 8100 */
5463                 if (max_pixclk > 540000)
5464                         return 675000;
5465                 else if (max_pixclk > 450000)
5466                         return 540000;
5467                 else if (max_pixclk > 337500)
5468                         return 450000;
5469                 else
5470                         return 337500;
5471         }
5472 }
5473
5474 static void
5475 skl_dpll0_update(struct drm_i915_private *dev_priv)
5476 {
5477         u32 val;
5478
5479         val = I915_READ(LCPLL1_CTL);
5480         if ((val & LCPLL_PLL_ENABLE) == 0) {
5481                 dev_priv->skl_vco_freq = 0;
5482                 return;
5483         }
5484
5485         val = I915_READ(DPLL_CTRL1);
5486
5487         switch (val & DPLL_CTRL1_LINK_RATE_MASK(SKL_DPLL0)) {
5488         case DPLL_CTRL1_LINK_RATE(DPLL_CTRL1_LINK_RATE_810, SKL_DPLL0):
5489         case DPLL_CTRL1_LINK_RATE(DPLL_CTRL1_LINK_RATE_1350, SKL_DPLL0):
5490         case DPLL_CTRL1_LINK_RATE(DPLL_CTRL1_LINK_RATE_1620, SKL_DPLL0):
5491         case DPLL_CTRL1_LINK_RATE(DPLL_CTRL1_LINK_RATE_2700, SKL_DPLL0):
5492                 dev_priv->skl_vco_freq = 8100;
5493                 break;
5494         case DPLL_CTRL1_LINK_RATE(DPLL_CTRL1_LINK_RATE_1080, SKL_DPLL0):
5495         case DPLL_CTRL1_LINK_RATE(DPLL_CTRL1_LINK_RATE_2160, SKL_DPLL0):
5496                 dev_priv->skl_vco_freq = 8640;
5497                 break;
5498         default:
5499                 MISSING_CASE(val & DPLL_CTRL1_LINK_RATE_MASK(SKL_DPLL0));
5500                 dev_priv->skl_vco_freq = 0;
5501                 break;
5502         }
5503 }
5504
5505 static void
5506 skl_dpll0_enable(struct drm_i915_private *dev_priv, int vco)
5507 {
5508         int min_cdclk = skl_calc_cdclk(0, vco);
5509         u32 val;
5510
5511         /* select the minimum CDCLK before enabling DPLL 0 */
5512         val = CDCLK_FREQ_337_308 | skl_cdclk_decimal(min_cdclk);
5513         I915_WRITE(CDCLK_CTL, val);
5514         POSTING_READ(CDCLK_CTL);
5515
5516         /*
5517          * We always enable DPLL0 with the lowest link rate possible, but still
5518          * taking into account the VCO required to operate the eDP panel at the
5519          * desired frequency. The usual DP link rates operate with a VCO of
5520          * 8100 while the eDP 1.4 alternate link rates need a VCO of 8640.
5521          * The modeset code is responsible for the selection of the exact link
5522          * rate later on, with the constraint of choosing a frequency that
5523          * works with vco.
5524          */
5525         val = I915_READ(DPLL_CTRL1);
5526
5527         val &= ~(DPLL_CTRL1_HDMI_MODE(SKL_DPLL0) | DPLL_CTRL1_SSC(SKL_DPLL0) |
5528                  DPLL_CTRL1_LINK_RATE_MASK(SKL_DPLL0));
5529         val |= DPLL_CTRL1_OVERRIDE(SKL_DPLL0);
5530         if (vco == 8640)
5531                 val |= DPLL_CTRL1_LINK_RATE(DPLL_CTRL1_LINK_RATE_1080,
5532                                             SKL_DPLL0);
5533         else
5534                 val |= DPLL_CTRL1_LINK_RATE(DPLL_CTRL1_LINK_RATE_810,
5535                                             SKL_DPLL0);
5536
5537         I915_WRITE(DPLL_CTRL1, val);
5538         POSTING_READ(DPLL_CTRL1);
5539
5540         I915_WRITE(LCPLL1_CTL, I915_READ(LCPLL1_CTL) | LCPLL_PLL_ENABLE);
5541
5542         if (wait_for(I915_READ(LCPLL1_CTL) & LCPLL_PLL_LOCK, 5))
5543                 DRM_ERROR("DPLL0 not locked\n");
5544 }
5545
5546 static void
5547 skl_dpll0_disable(struct drm_i915_private *dev_priv)
5548 {
5549         I915_WRITE(LCPLL1_CTL, I915_READ(LCPLL1_CTL) & ~LCPLL_PLL_ENABLE);
5550         if (wait_for(!(I915_READ(LCPLL1_CTL) & LCPLL_PLL_LOCK), 1))
5551                 DRM_ERROR("Couldn't disable DPLL0\n");
5552 }
5553
5554 static bool skl_cdclk_pcu_ready(struct drm_i915_private *dev_priv)
5555 {
5556         int ret;
5557         u32 val;
5558
5559         /* inform PCU we want to change CDCLK */
5560         val = SKL_CDCLK_PREPARE_FOR_CHANGE;
5561         mutex_lock(&dev_priv->rps.hw_lock);
5562         ret = sandybridge_pcode_read(dev_priv, SKL_PCODE_CDCLK_CONTROL, &val);
5563         mutex_unlock(&dev_priv->rps.hw_lock);
5564
5565         return ret == 0 && (val & SKL_CDCLK_READY_FOR_CHANGE);
5566 }
5567
5568 static bool skl_cdclk_wait_for_pcu_ready(struct drm_i915_private *dev_priv)
5569 {
5570         unsigned int i;
5571
5572         for (i = 0; i < 15; i++) {
5573                 if (skl_cdclk_pcu_ready(dev_priv))
5574                         return true;
5575                 udelay(10);
5576         }
5577
5578         return false;
5579 }
5580
5581 static void skl_set_cdclk(struct drm_i915_private *dev_priv, int cdclk)
5582 {
5583         struct drm_device *dev = dev_priv->dev;
5584         u32 freq_select, pcu_ack;
5585
5586         DRM_DEBUG_DRIVER("Changing CDCLK to %dKHz\n", cdclk);
5587
5588         if (!skl_cdclk_wait_for_pcu_ready(dev_priv)) {
5589                 DRM_ERROR("failed to inform PCU about cdclk change\n");
5590                 return;
5591         }
5592
5593         /* set CDCLK_CTL */
5594         switch (cdclk) {
5595         case 450000:
5596         case 432000:
5597                 freq_select = CDCLK_FREQ_450_432;
5598                 pcu_ack = 1;
5599                 break;
5600         case 540000:
5601                 freq_select = CDCLK_FREQ_540;
5602                 pcu_ack = 2;
5603                 break;
5604         case 308570:
5605         case 337500:
5606         default:
5607                 freq_select = CDCLK_FREQ_337_308;
5608                 pcu_ack = 0;
5609                 break;
5610         case 617140:
5611         case 675000:
5612                 freq_select = CDCLK_FREQ_675_617;
5613                 pcu_ack = 3;
5614                 break;
5615         }
5616
5617         I915_WRITE(CDCLK_CTL, freq_select | skl_cdclk_decimal(cdclk));
5618         POSTING_READ(CDCLK_CTL);
5619
5620         /* inform PCU of the change */
5621         mutex_lock(&dev_priv->rps.hw_lock);
5622         sandybridge_pcode_write(dev_priv, SKL_PCODE_CDCLK_CONTROL, pcu_ack);
5623         mutex_unlock(&dev_priv->rps.hw_lock);
5624
5625         intel_update_cdclk(dev);
5626 }
5627
5628 void skl_uninit_cdclk(struct drm_i915_private *dev_priv)
5629 {
5630         /* disable DBUF power */
5631         I915_WRITE(DBUF_CTL, I915_READ(DBUF_CTL) & ~DBUF_POWER_REQUEST);
5632         POSTING_READ(DBUF_CTL);
5633
5634         udelay(10);
5635
5636         if (I915_READ(DBUF_CTL) & DBUF_POWER_STATE)
5637                 DRM_ERROR("DBuf power disable timeout\n");
5638
5639         skl_dpll0_disable(dev_priv);
5640 }
5641
5642 void skl_init_cdclk(struct drm_i915_private *dev_priv)
5643 {
5644         unsigned int cdclk;
5645
5646         /* DPLL0 not enabled (happens on early BIOS versions) */
5647         if (!(I915_READ(LCPLL1_CTL) & LCPLL_PLL_ENABLE)) {
5648                 /* enable DPLL0 */
5649                 if (dev_priv->skl_vco_freq != 8640)
5650                         dev_priv->skl_vco_freq = 8100;
5651                 skl_dpll0_enable(dev_priv, dev_priv->skl_vco_freq);
5652                 cdclk = skl_calc_cdclk(0, dev_priv->skl_vco_freq);
5653         } else {
5654                 cdclk = dev_priv->cdclk_freq;
5655         }
5656
5657         /* set CDCLK to the lowest frequency, Modeset follows */
5658         skl_set_cdclk(dev_priv, cdclk);
5659
5660         /* enable DBUF power */
5661         I915_WRITE(DBUF_CTL, I915_READ(DBUF_CTL) | DBUF_POWER_REQUEST);
5662         POSTING_READ(DBUF_CTL);
5663
5664         udelay(10);
5665
5666         if (!(I915_READ(DBUF_CTL) & DBUF_POWER_STATE))
5667                 DRM_ERROR("DBuf power enable timeout\n");
5668 }
5669
5670 int skl_sanitize_cdclk(struct drm_i915_private *dev_priv)
5671 {
5672         uint32_t lcpll1 = I915_READ(LCPLL1_CTL);
5673         uint32_t cdctl = I915_READ(CDCLK_CTL);
5674         int freq = dev_priv->cdclk_freq;
5675
5676         /*
5677          * check if the pre-os intialized the display
5678          * There is SWF18 scratchpad register defined which is set by the
5679          * pre-os which can be used by the OS drivers to check the status
5680          */
5681         if ((I915_READ(SWF_ILK(0x18)) & 0x00FFFFFF) == 0)
5682                 goto sanitize;
5683
5684         /* Is PLL enabled and locked ? */
5685         if (!((lcpll1 & LCPLL_PLL_ENABLE) && (lcpll1 & LCPLL_PLL_LOCK)))
5686                 goto sanitize;
5687
5688         /* DPLL okay; verify the cdclock
5689          *
5690          * Noticed in some instances that the freq selection is correct but
5691          * decimal part is programmed wrong from BIOS where pre-os does not
5692          * enable display. Verify the same as well.
5693          */
5694         if (cdctl == ((cdctl & CDCLK_FREQ_SEL_MASK) | skl_cdclk_decimal(freq)))
5695                 /* All well; nothing to sanitize */
5696                 return false;
5697 sanitize:
5698
5699         skl_init_cdclk(dev_priv);
5700
5701         /* we did have to sanitize */
5702         return true;
5703 }
5704
5705 /* Adjust CDclk dividers to allow high res or save power if possible */
5706 static void valleyview_set_cdclk(struct drm_device *dev, int cdclk)
5707 {
5708         struct drm_i915_private *dev_priv = dev->dev_private;
5709         u32 val, cmd;
5710
5711         WARN_ON(dev_priv->display.get_display_clock_speed(dev)
5712                                         != dev_priv->cdclk_freq);
5713
5714         if (cdclk >= 320000) /* jump to highest voltage for 400MHz too */
5715                 cmd = 2;
5716         else if (cdclk == 266667)
5717                 cmd = 1;
5718         else
5719                 cmd = 0;
5720
5721         mutex_lock(&dev_priv->rps.hw_lock);
5722         val = vlv_punit_read(dev_priv, PUNIT_REG_DSPFREQ);
5723         val &= ~DSPFREQGUAR_MASK;
5724         val |= (cmd << DSPFREQGUAR_SHIFT);
5725         vlv_punit_write(dev_priv, PUNIT_REG_DSPFREQ, val);
5726         if (wait_for((vlv_punit_read(dev_priv, PUNIT_REG_DSPFREQ) &
5727                       DSPFREQSTAT_MASK) == (cmd << DSPFREQSTAT_SHIFT),
5728                      50)) {
5729                 DRM_ERROR("timed out waiting for CDclk change\n");
5730         }
5731         mutex_unlock(&dev_priv->rps.hw_lock);
5732
5733         mutex_lock(&dev_priv->sb_lock);
5734
5735         if (cdclk == 400000) {
5736                 u32 divider;
5737
5738                 divider = DIV_ROUND_CLOSEST(dev_priv->hpll_freq << 1, cdclk) - 1;
5739
5740                 /* adjust cdclk divider */
5741                 val = vlv_cck_read(dev_priv, CCK_DISPLAY_CLOCK_CONTROL);
5742                 val &= ~CCK_FREQUENCY_VALUES;
5743                 val |= divider;
5744                 vlv_cck_write(dev_priv, CCK_DISPLAY_CLOCK_CONTROL, val);
5745
5746                 if (wait_for((vlv_cck_read(dev_priv, CCK_DISPLAY_CLOCK_CONTROL) &
5747                               CCK_FREQUENCY_STATUS) == (divider << CCK_FREQUENCY_STATUS_SHIFT),
5748                              50))
5749                         DRM_ERROR("timed out waiting for CDclk change\n");
5750         }
5751
5752         /* adjust self-refresh exit latency value */
5753         val = vlv_bunit_read(dev_priv, BUNIT_REG_BISOC);
5754         val &= ~0x7f;
5755
5756         /*
5757          * For high bandwidth configs, we set a higher latency in the bunit
5758          * so that the core display fetch happens in time to avoid underruns.
5759          */
5760         if (cdclk == 400000)
5761                 val |= 4500 / 250; /* 4.5 usec */
5762         else
5763                 val |= 3000 / 250; /* 3.0 usec */
5764         vlv_bunit_write(dev_priv, BUNIT_REG_BISOC, val);
5765
5766         mutex_unlock(&dev_priv->sb_lock);
5767
5768         intel_update_cdclk(dev);
5769 }
5770
5771 static void cherryview_set_cdclk(struct drm_device *dev, int cdclk)
5772 {
5773         struct drm_i915_private *dev_priv = dev->dev_private;
5774         u32 val, cmd;
5775
5776         WARN_ON(dev_priv->display.get_display_clock_speed(dev)
5777                                                 != dev_priv->cdclk_freq);
5778
5779         switch (cdclk) {
5780         case 333333:
5781         case 320000:
5782         case 266667:
5783         case 200000:
5784                 break;
5785         default:
5786                 MISSING_CASE(cdclk);
5787                 return;
5788         }
5789
5790         /*
5791          * Specs are full of misinformation, but testing on actual
5792          * hardware has shown that we just need to write the desired
5793          * CCK divider into the Punit register.
5794          */
5795         cmd = DIV_ROUND_CLOSEST(dev_priv->hpll_freq << 1, cdclk) - 1;
5796
5797         mutex_lock(&dev_priv->rps.hw_lock);
5798         val = vlv_punit_read(dev_priv, PUNIT_REG_DSPFREQ);
5799         val &= ~DSPFREQGUAR_MASK_CHV;
5800         val |= (cmd << DSPFREQGUAR_SHIFT_CHV);
5801         vlv_punit_write(dev_priv, PUNIT_REG_DSPFREQ, val);
5802         if (wait_for((vlv_punit_read(dev_priv, PUNIT_REG_DSPFREQ) &
5803                       DSPFREQSTAT_MASK_CHV) == (cmd << DSPFREQSTAT_SHIFT_CHV),
5804                      50)) {
5805                 DRM_ERROR("timed out waiting for CDclk change\n");
5806         }
5807         mutex_unlock(&dev_priv->rps.hw_lock);
5808
5809         intel_update_cdclk(dev);
5810 }
5811
5812 static int valleyview_calc_cdclk(struct drm_i915_private *dev_priv,
5813                                  int max_pixclk)
5814 {
5815         int freq_320 = (dev_priv->hpll_freq <<  1) % 320000 != 0 ? 333333 : 320000;
5816         int limit = IS_CHERRYVIEW(dev_priv) ? 95 : 90;
5817
5818         /*
5819          * Really only a few cases to deal with, as only 4 CDclks are supported:
5820          *   200MHz
5821          *   267MHz
5822          *   320/333MHz (depends on HPLL freq)
5823          *   400MHz (VLV only)
5824          * So we check to see whether we're above 90% (VLV) or 95% (CHV)
5825          * of the lower bin and adjust if needed.
5826          *
5827          * We seem to get an unstable or solid color picture at 200MHz.
5828          * Not sure what's wrong. For now use 200MHz only when all pipes
5829          * are off.
5830          */
5831         if (!IS_CHERRYVIEW(dev_priv) &&
5832             max_pixclk > freq_320*limit/100)
5833                 return 400000;
5834         else if (max_pixclk > 266667*limit/100)
5835                 return freq_320;
5836         else if (max_pixclk > 0)
5837                 return 266667;
5838         else
5839                 return 200000;
5840 }
5841
5842 static int broxton_calc_cdclk(int max_pixclk)
5843 {
5844         /*
5845          * FIXME:
5846          * - set 19.2MHz bypass frequency if there are no active pipes
5847          */
5848         if (max_pixclk > 576000)
5849                 return 624000;
5850         else if (max_pixclk > 384000)
5851                 return 576000;
5852         else if (max_pixclk > 288000)
5853                 return 384000;
5854         else if (max_pixclk > 144000)
5855                 return 288000;
5856         else
5857                 return 144000;
5858 }
5859
5860 /* Compute the max pixel clock for new configuration. */
5861 static int intel_mode_max_pixclk(struct drm_device *dev,
5862                                  struct drm_atomic_state *state)
5863 {
5864         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
5865         struct drm_i915_private *dev_priv = dev->dev_private;
5866         struct drm_crtc *crtc;
5867         struct drm_crtc_state *crtc_state;
5868         unsigned max_pixclk = 0, i;
5869         enum pipe pipe;
5870
5871         memcpy(intel_state->min_pixclk, dev_priv->min_pixclk,
5872                sizeof(intel_state->min_pixclk));
5873
5874         for_each_crtc_in_state(state, crtc, crtc_state, i) {
5875                 int pixclk = 0;
5876
5877                 if (crtc_state->enable)
5878                         pixclk = crtc_state->adjusted_mode.crtc_clock;
5879
5880                 intel_state->min_pixclk[i] = pixclk;
5881         }
5882
5883         for_each_pipe(dev_priv, pipe)
5884                 max_pixclk = max(intel_state->min_pixclk[pipe], max_pixclk);
5885
5886         return max_pixclk;
5887 }
5888
5889 static int valleyview_modeset_calc_cdclk(struct drm_atomic_state *state)
5890 {
5891         struct drm_device *dev = state->dev;
5892         struct drm_i915_private *dev_priv = dev->dev_private;
5893         int max_pixclk = intel_mode_max_pixclk(dev, state);
5894         struct intel_atomic_state *intel_state =
5895                 to_intel_atomic_state(state);
5896
5897         intel_state->cdclk = intel_state->dev_cdclk =
5898                 valleyview_calc_cdclk(dev_priv, max_pixclk);
5899
5900         if (!intel_state->active_crtcs)
5901                 intel_state->dev_cdclk = valleyview_calc_cdclk(dev_priv, 0);
5902
5903         return 0;
5904 }
5905
5906 static int broxton_modeset_calc_cdclk(struct drm_atomic_state *state)
5907 {
5908         int max_pixclk = ilk_max_pixel_rate(state);
5909         struct intel_atomic_state *intel_state =
5910                 to_intel_atomic_state(state);
5911
5912         intel_state->cdclk = intel_state->dev_cdclk =
5913                 broxton_calc_cdclk(max_pixclk);
5914
5915         if (!intel_state->active_crtcs)
5916                 intel_state->dev_cdclk = broxton_calc_cdclk(0);
5917
5918         return 0;
5919 }
5920
5921 static void vlv_program_pfi_credits(struct drm_i915_private *dev_priv)
5922 {
5923         unsigned int credits, default_credits;
5924
5925         if (IS_CHERRYVIEW(dev_priv))
5926                 default_credits = PFI_CREDIT(12);
5927         else
5928                 default_credits = PFI_CREDIT(8);
5929
5930         if (dev_priv->cdclk_freq >= dev_priv->czclk_freq) {
5931                 /* CHV suggested value is 31 or 63 */
5932                 if (IS_CHERRYVIEW(dev_priv))
5933                         credits = PFI_CREDIT_63;
5934                 else
5935                         credits = PFI_CREDIT(15);
5936         } else {
5937                 credits = default_credits;
5938         }
5939
5940         /*
5941          * WA - write default credits before re-programming
5942          * FIXME: should we also set the resend bit here?
5943          */
5944         I915_WRITE(GCI_CONTROL, VGA_FAST_MODE_DISABLE |
5945                    default_credits);
5946
5947         I915_WRITE(GCI_CONTROL, VGA_FAST_MODE_DISABLE |
5948                    credits | PFI_CREDIT_RESEND);
5949
5950         /*
5951          * FIXME is this guaranteed to clear
5952          * immediately or should we poll for it?
5953          */
5954         WARN_ON(I915_READ(GCI_CONTROL) & PFI_CREDIT_RESEND);
5955 }
5956
5957 static void valleyview_modeset_commit_cdclk(struct drm_atomic_state *old_state)
5958 {
5959         struct drm_device *dev = old_state->dev;
5960         struct drm_i915_private *dev_priv = dev->dev_private;
5961         struct intel_atomic_state *old_intel_state =
5962                 to_intel_atomic_state(old_state);
5963         unsigned req_cdclk = old_intel_state->dev_cdclk;
5964
5965         /*
5966          * FIXME: We can end up here with all power domains off, yet
5967          * with a CDCLK frequency other than the minimum. To account
5968          * for this take the PIPE-A power domain, which covers the HW
5969          * blocks needed for the following programming. This can be
5970          * removed once it's guaranteed that we get here either with
5971          * the minimum CDCLK set, or the required power domains
5972          * enabled.
5973          */
5974         intel_display_power_get(dev_priv, POWER_DOMAIN_PIPE_A);
5975
5976         if (IS_CHERRYVIEW(dev))
5977                 cherryview_set_cdclk(dev, req_cdclk);
5978         else
5979                 valleyview_set_cdclk(dev, req_cdclk);
5980
5981         vlv_program_pfi_credits(dev_priv);
5982
5983         intel_display_power_put(dev_priv, POWER_DOMAIN_PIPE_A);
5984 }
5985
5986 static void valleyview_crtc_enable(struct drm_crtc *crtc)
5987 {
5988         struct drm_device *dev = crtc->dev;
5989         struct drm_i915_private *dev_priv = to_i915(dev);
5990         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5991         struct intel_encoder *encoder;
5992         struct intel_crtc_state *pipe_config =
5993                 to_intel_crtc_state(crtc->state);
5994         int pipe = intel_crtc->pipe;
5995
5996         if (WARN_ON(intel_crtc->active))
5997                 return;
5998
5999         if (intel_crtc->config->has_dp_encoder)
6000                 intel_dp_set_m_n(intel_crtc, M1_N1);
6001
6002         intel_set_pipe_timings(intel_crtc);
6003         intel_set_pipe_src_size(intel_crtc);
6004
6005         if (IS_CHERRYVIEW(dev) && pipe == PIPE_B) {
6006                 struct drm_i915_private *dev_priv = dev->dev_private;
6007
6008                 I915_WRITE(CHV_BLEND(pipe), CHV_BLEND_LEGACY);
6009                 I915_WRITE(CHV_CANVAS(pipe), 0);
6010         }
6011
6012         i9xx_set_pipeconf(intel_crtc);
6013
6014         intel_crtc->active = true;
6015
6016         intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
6017
6018         for_each_encoder_on_crtc(dev, crtc, encoder)
6019                 if (encoder->pre_pll_enable)
6020                         encoder->pre_pll_enable(encoder);
6021
6022         if (IS_CHERRYVIEW(dev)) {
6023                 chv_prepare_pll(intel_crtc, intel_crtc->config);
6024                 chv_enable_pll(intel_crtc, intel_crtc->config);
6025         } else {
6026                 vlv_prepare_pll(intel_crtc, intel_crtc->config);
6027                 vlv_enable_pll(intel_crtc, intel_crtc->config);
6028         }
6029
6030         for_each_encoder_on_crtc(dev, crtc, encoder)
6031                 if (encoder->pre_enable)
6032                         encoder->pre_enable(encoder);
6033
6034         i9xx_pfit_enable(intel_crtc);
6035
6036         intel_color_load_luts(&pipe_config->base);
6037
6038         intel_update_watermarks(crtc);
6039         intel_enable_pipe(intel_crtc);
6040
6041         assert_vblank_disabled(crtc);
6042         drm_crtc_vblank_on(crtc);
6043
6044         for_each_encoder_on_crtc(dev, crtc, encoder)
6045                 encoder->enable(encoder);
6046 }
6047
6048 static void i9xx_set_pll_dividers(struct intel_crtc *crtc)
6049 {
6050         struct drm_device *dev = crtc->base.dev;
6051         struct drm_i915_private *dev_priv = dev->dev_private;
6052
6053         I915_WRITE(FP0(crtc->pipe), crtc->config->dpll_hw_state.fp0);
6054         I915_WRITE(FP1(crtc->pipe), crtc->config->dpll_hw_state.fp1);
6055 }
6056
6057 static void i9xx_crtc_enable(struct drm_crtc *crtc)
6058 {
6059         struct drm_device *dev = crtc->dev;
6060         struct drm_i915_private *dev_priv = to_i915(dev);
6061         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
6062         struct intel_encoder *encoder;
6063         struct intel_crtc_state *pipe_config =
6064                 to_intel_crtc_state(crtc->state);
6065         enum pipe pipe = intel_crtc->pipe;
6066
6067         if (WARN_ON(intel_crtc->active))
6068                 return;
6069
6070         i9xx_set_pll_dividers(intel_crtc);
6071
6072         if (intel_crtc->config->has_dp_encoder)
6073                 intel_dp_set_m_n(intel_crtc, M1_N1);
6074
6075         intel_set_pipe_timings(intel_crtc);
6076         intel_set_pipe_src_size(intel_crtc);
6077
6078         i9xx_set_pipeconf(intel_crtc);
6079
6080         intel_crtc->active = true;
6081
6082         if (!IS_GEN2(dev))
6083                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
6084
6085         for_each_encoder_on_crtc(dev, crtc, encoder)
6086                 if (encoder->pre_enable)
6087                         encoder->pre_enable(encoder);
6088
6089         i9xx_enable_pll(intel_crtc);
6090
6091         i9xx_pfit_enable(intel_crtc);
6092
6093         intel_color_load_luts(&pipe_config->base);
6094
6095         intel_update_watermarks(crtc);
6096         intel_enable_pipe(intel_crtc);
6097
6098         assert_vblank_disabled(crtc);
6099         drm_crtc_vblank_on(crtc);
6100
6101         for_each_encoder_on_crtc(dev, crtc, encoder)
6102                 encoder->enable(encoder);
6103 }
6104
6105 static void i9xx_pfit_disable(struct intel_crtc *crtc)
6106 {
6107         struct drm_device *dev = crtc->base.dev;
6108         struct drm_i915_private *dev_priv = dev->dev_private;
6109
6110         if (!crtc->config->gmch_pfit.control)
6111                 return;
6112
6113         assert_pipe_disabled(dev_priv, crtc->pipe);
6114
6115         DRM_DEBUG_DRIVER("disabling pfit, current: 0x%08x\n",
6116                          I915_READ(PFIT_CONTROL));
6117         I915_WRITE(PFIT_CONTROL, 0);
6118 }
6119
6120 static void i9xx_crtc_disable(struct drm_crtc *crtc)
6121 {
6122         struct drm_device *dev = crtc->dev;
6123         struct drm_i915_private *dev_priv = dev->dev_private;
6124         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
6125         struct intel_encoder *encoder;
6126         int pipe = intel_crtc->pipe;
6127
6128         /*
6129          * On gen2 planes are double buffered but the pipe isn't, so we must
6130          * wait for planes to fully turn off before disabling the pipe.
6131          */
6132         if (IS_GEN2(dev))
6133                 intel_wait_for_vblank(dev, pipe);
6134
6135         for_each_encoder_on_crtc(dev, crtc, encoder)
6136                 encoder->disable(encoder);
6137
6138         drm_crtc_vblank_off(crtc);
6139         assert_vblank_disabled(crtc);
6140
6141         intel_disable_pipe(intel_crtc);
6142
6143         i9xx_pfit_disable(intel_crtc);
6144
6145         for_each_encoder_on_crtc(dev, crtc, encoder)
6146                 if (encoder->post_disable)
6147                         encoder->post_disable(encoder);
6148
6149         if (!intel_crtc->config->has_dsi_encoder) {
6150                 if (IS_CHERRYVIEW(dev))
6151                         chv_disable_pll(dev_priv, pipe);
6152                 else if (IS_VALLEYVIEW(dev))
6153                         vlv_disable_pll(dev_priv, pipe);
6154                 else
6155                         i9xx_disable_pll(intel_crtc);
6156         }
6157
6158         for_each_encoder_on_crtc(dev, crtc, encoder)
6159                 if (encoder->post_pll_disable)
6160                         encoder->post_pll_disable(encoder);
6161
6162         if (!IS_GEN2(dev))
6163                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, false);
6164 }
6165
6166 static void intel_crtc_disable_noatomic(struct drm_crtc *crtc)
6167 {
6168         struct intel_encoder *encoder;
6169         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
6170         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
6171         enum intel_display_power_domain domain;
6172         unsigned long domains;
6173
6174         if (!intel_crtc->active)
6175                 return;
6176
6177         if (to_intel_plane_state(crtc->primary->state)->visible) {
6178                 WARN_ON(list_empty(&intel_crtc->flip_work));
6179
6180                 intel_pre_disable_primary_noatomic(crtc);
6181
6182                 intel_crtc_disable_planes(crtc, 1 << drm_plane_index(crtc->primary));
6183                 to_intel_plane_state(crtc->primary->state)->visible = false;
6184         }
6185
6186         dev_priv->display.crtc_disable(crtc);
6187
6188         DRM_DEBUG_KMS("[CRTC:%d] hw state adjusted, was enabled, now disabled\n",
6189                       crtc->base.id);
6190
6191         WARN_ON(drm_atomic_set_mode_for_crtc(crtc->state, NULL) < 0);
6192         crtc->state->active = false;
6193         intel_crtc->active = false;
6194         crtc->enabled = false;
6195         crtc->state->connector_mask = 0;
6196         crtc->state->encoder_mask = 0;
6197
6198         for_each_encoder_on_crtc(crtc->dev, crtc, encoder)
6199                 encoder->base.crtc = NULL;
6200
6201         intel_fbc_disable(intel_crtc);
6202         intel_update_watermarks(crtc);
6203         intel_disable_shared_dpll(intel_crtc);
6204
6205         domains = intel_crtc->enabled_power_domains;
6206         for_each_power_domain(domain, domains)
6207                 intel_display_power_put(dev_priv, domain);
6208         intel_crtc->enabled_power_domains = 0;
6209
6210         dev_priv->active_crtcs &= ~(1 << intel_crtc->pipe);
6211         dev_priv->min_pixclk[intel_crtc->pipe] = 0;
6212 }
6213
6214 /*
6215  * turn all crtc's off, but do not adjust state
6216  * This has to be paired with a call to intel_modeset_setup_hw_state.
6217  */
6218 int intel_display_suspend(struct drm_device *dev)
6219 {
6220         struct drm_i915_private *dev_priv = to_i915(dev);
6221         struct drm_atomic_state *state;
6222         int ret;
6223
6224         state = drm_atomic_helper_suspend(dev);
6225         ret = PTR_ERR_OR_ZERO(state);
6226         if (ret)
6227                 DRM_ERROR("Suspending crtc's failed with %i\n", ret);
6228         else
6229                 dev_priv->modeset_restore_state = state;
6230
6231         /*
6232          * Make sure all unpin_work completes before returning.
6233          */
6234         flush_workqueue(dev_priv->wq);
6235
6236         return ret;
6237 }
6238
6239 void intel_encoder_destroy(struct drm_encoder *encoder)
6240 {
6241         struct intel_encoder *intel_encoder = to_intel_encoder(encoder);
6242
6243         drm_encoder_cleanup(encoder);
6244         kfree(intel_encoder);
6245 }
6246
6247 /* Cross check the actual hw state with our own modeset state tracking (and it's
6248  * internal consistency). */
6249 static void intel_connector_verify_state(struct intel_connector *connector,
6250                                          struct drm_connector_state *conn_state)
6251 {
6252         struct drm_crtc *crtc = conn_state->crtc;
6253
6254         DRM_DEBUG_KMS("[CONNECTOR:%d:%s]\n",
6255                       connector->base.base.id,
6256                       connector->base.name);
6257
6258         if (connector->get_hw_state(connector)) {
6259                 struct intel_encoder *encoder = connector->encoder;
6260
6261                 I915_STATE_WARN(!crtc,
6262                          "connector enabled without attached crtc\n");
6263
6264                 if (!crtc)
6265                         return;
6266
6267                 I915_STATE_WARN(!crtc->state->active,
6268                       "connector is active, but attached crtc isn't\n");
6269
6270                 if (!encoder || encoder->type == INTEL_OUTPUT_DP_MST)
6271                         return;
6272
6273                 I915_STATE_WARN(conn_state->best_encoder != &encoder->base,
6274                         "atomic encoder doesn't match attached encoder\n");
6275
6276                 I915_STATE_WARN(conn_state->crtc != encoder->base.crtc,
6277                         "attached encoder crtc differs from connector crtc\n");
6278         } else {
6279                 I915_STATE_WARN(crtc && crtc->state->active,
6280                         "attached crtc is active, but connector isn't\n");
6281                 I915_STATE_WARN(!crtc && conn_state->best_encoder,
6282                         "best encoder set without crtc!\n");
6283         }
6284 }
6285
6286 int intel_connector_init(struct intel_connector *connector)
6287 {
6288         drm_atomic_helper_connector_reset(&connector->base);
6289
6290         if (!connector->base.state)
6291                 return -ENOMEM;
6292
6293         return 0;
6294 }
6295
6296 struct intel_connector *intel_connector_alloc(void)
6297 {
6298         struct intel_connector *connector;
6299
6300         connector = kzalloc(sizeof *connector, GFP_KERNEL);
6301         if (!connector)
6302                 return NULL;
6303
6304         if (intel_connector_init(connector) < 0) {
6305                 kfree(connector);
6306                 return NULL;
6307         }
6308
6309         return connector;
6310 }
6311
6312 /* Simple connector->get_hw_state implementation for encoders that support only
6313  * one connector and no cloning and hence the encoder state determines the state
6314  * of the connector. */
6315 bool intel_connector_get_hw_state(struct intel_connector *connector)
6316 {
6317         enum pipe pipe = 0;
6318         struct intel_encoder *encoder = connector->encoder;
6319
6320         return encoder->get_hw_state(encoder, &pipe);
6321 }
6322
6323 static int pipe_required_fdi_lanes(struct intel_crtc_state *crtc_state)
6324 {
6325         if (crtc_state->base.enable && crtc_state->has_pch_encoder)
6326                 return crtc_state->fdi_lanes;
6327
6328         return 0;
6329 }
6330
6331 static int ironlake_check_fdi_lanes(struct drm_device *dev, enum pipe pipe,
6332                                      struct intel_crtc_state *pipe_config)
6333 {
6334         struct drm_atomic_state *state = pipe_config->base.state;
6335         struct intel_crtc *other_crtc;
6336         struct intel_crtc_state *other_crtc_state;
6337
6338         DRM_DEBUG_KMS("checking fdi config on pipe %c, lanes %i\n",
6339                       pipe_name(pipe), pipe_config->fdi_lanes);
6340         if (pipe_config->fdi_lanes > 4) {
6341                 DRM_DEBUG_KMS("invalid fdi lane config on pipe %c: %i lanes\n",
6342                               pipe_name(pipe), pipe_config->fdi_lanes);
6343                 return -EINVAL;
6344         }
6345
6346         if (IS_HASWELL(dev) || IS_BROADWELL(dev)) {
6347                 if (pipe_config->fdi_lanes > 2) {
6348                         DRM_DEBUG_KMS("only 2 lanes on haswell, required: %i lanes\n",
6349                                       pipe_config->fdi_lanes);
6350                         return -EINVAL;
6351                 } else {
6352                         return 0;
6353                 }
6354         }
6355
6356         if (INTEL_INFO(dev)->num_pipes == 2)
6357                 return 0;
6358
6359         /* Ivybridge 3 pipe is really complicated */
6360         switch (pipe) {
6361         case PIPE_A:
6362                 return 0;
6363         case PIPE_B:
6364                 if (pipe_config->fdi_lanes <= 2)
6365                         return 0;
6366
6367                 other_crtc = to_intel_crtc(intel_get_crtc_for_pipe(dev, PIPE_C));
6368                 other_crtc_state =
6369                         intel_atomic_get_crtc_state(state, other_crtc);
6370                 if (IS_ERR(other_crtc_state))
6371                         return PTR_ERR(other_crtc_state);
6372
6373                 if (pipe_required_fdi_lanes(other_crtc_state) > 0) {
6374                         DRM_DEBUG_KMS("invalid shared fdi lane config on pipe %c: %i lanes\n",
6375                                       pipe_name(pipe), pipe_config->fdi_lanes);
6376                         return -EINVAL;
6377                 }
6378                 return 0;
6379         case PIPE_C:
6380                 if (pipe_config->fdi_lanes > 2) {
6381                         DRM_DEBUG_KMS("only 2 lanes on pipe %c: required %i lanes\n",
6382                                       pipe_name(pipe), pipe_config->fdi_lanes);
6383                         return -EINVAL;
6384                 }
6385
6386                 other_crtc = to_intel_crtc(intel_get_crtc_for_pipe(dev, PIPE_B));
6387                 other_crtc_state =
6388                         intel_atomic_get_crtc_state(state, other_crtc);
6389                 if (IS_ERR(other_crtc_state))
6390                         return PTR_ERR(other_crtc_state);
6391
6392                 if (pipe_required_fdi_lanes(other_crtc_state) > 2) {
6393                         DRM_DEBUG_KMS("fdi link B uses too many lanes to enable link C\n");
6394                         return -EINVAL;
6395                 }
6396                 return 0;
6397         default:
6398                 BUG();
6399         }
6400 }
6401
6402 #define RETRY 1
6403 static int ironlake_fdi_compute_config(struct intel_crtc *intel_crtc,
6404                                        struct intel_crtc_state *pipe_config)
6405 {
6406         struct drm_device *dev = intel_crtc->base.dev;
6407         const struct drm_display_mode *adjusted_mode = &pipe_config->base.adjusted_mode;
6408         int lane, link_bw, fdi_dotclock, ret;
6409         bool needs_recompute = false;
6410
6411 retry:
6412         /* FDI is a binary signal running at ~2.7GHz, encoding
6413          * each output octet as 10 bits. The actual frequency
6414          * is stored as a divider into a 100MHz clock, and the
6415          * mode pixel clock is stored in units of 1KHz.
6416          * Hence the bw of each lane in terms of the mode signal
6417          * is:
6418          */
6419         link_bw = intel_fdi_link_freq(to_i915(dev), pipe_config);
6420
6421         fdi_dotclock = adjusted_mode->crtc_clock;
6422
6423         lane = ironlake_get_lanes_required(fdi_dotclock, link_bw,
6424                                            pipe_config->pipe_bpp);
6425
6426         pipe_config->fdi_lanes = lane;
6427
6428         intel_link_compute_m_n(pipe_config->pipe_bpp, lane, fdi_dotclock,
6429                                link_bw, &pipe_config->fdi_m_n);
6430
6431         ret = ironlake_check_fdi_lanes(dev, intel_crtc->pipe, pipe_config);
6432         if (ret == -EINVAL && pipe_config->pipe_bpp > 6*3) {
6433                 pipe_config->pipe_bpp -= 2*3;
6434                 DRM_DEBUG_KMS("fdi link bw constraint, reducing pipe bpp to %i\n",
6435                               pipe_config->pipe_bpp);
6436                 needs_recompute = true;
6437                 pipe_config->bw_constrained = true;
6438
6439                 goto retry;
6440         }
6441
6442         if (needs_recompute)
6443                 return RETRY;
6444
6445         return ret;
6446 }
6447
6448 static bool pipe_config_supports_ips(struct drm_i915_private *dev_priv,
6449                                      struct intel_crtc_state *pipe_config)
6450 {
6451         if (pipe_config->pipe_bpp > 24)
6452                 return false;
6453
6454         /* HSW can handle pixel rate up to cdclk? */
6455         if (IS_HASWELL(dev_priv))
6456                 return true;
6457
6458         /*
6459          * We compare against max which means we must take
6460          * the increased cdclk requirement into account when
6461          * calculating the new cdclk.
6462          *
6463          * Should measure whether using a lower cdclk w/o IPS
6464          */
6465         return ilk_pipe_pixel_rate(pipe_config) <=
6466                 dev_priv->max_cdclk_freq * 95 / 100;
6467 }
6468
6469 static void hsw_compute_ips_config(struct intel_crtc *crtc,
6470                                    struct intel_crtc_state *pipe_config)
6471 {
6472         struct drm_device *dev = crtc->base.dev;
6473         struct drm_i915_private *dev_priv = dev->dev_private;
6474
6475         pipe_config->ips_enabled = i915.enable_ips &&
6476                 hsw_crtc_supports_ips(crtc) &&
6477                 pipe_config_supports_ips(dev_priv, pipe_config);
6478 }
6479
6480 static bool intel_crtc_supports_double_wide(const struct intel_crtc *crtc)
6481 {
6482         const struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
6483
6484         /* GDG double wide on either pipe, otherwise pipe A only */
6485         return INTEL_INFO(dev_priv)->gen < 4 &&
6486                 (crtc->pipe == PIPE_A || IS_I915G(dev_priv));
6487 }
6488
6489 static int intel_crtc_compute_config(struct intel_crtc *crtc,
6490                                      struct intel_crtc_state *pipe_config)
6491 {
6492         struct drm_device *dev = crtc->base.dev;
6493         struct drm_i915_private *dev_priv = dev->dev_private;
6494         const struct drm_display_mode *adjusted_mode = &pipe_config->base.adjusted_mode;
6495
6496         /* FIXME should check pixel clock limits on all platforms */
6497         if (INTEL_INFO(dev)->gen < 4) {
6498                 int clock_limit = dev_priv->max_cdclk_freq * 9 / 10;
6499
6500                 /*
6501                  * Enable double wide mode when the dot clock
6502                  * is > 90% of the (display) core speed.
6503                  */
6504                 if (intel_crtc_supports_double_wide(crtc) &&
6505                     adjusted_mode->crtc_clock > clock_limit) {
6506                         clock_limit *= 2;
6507                         pipe_config->double_wide = true;
6508                 }
6509
6510                 if (adjusted_mode->crtc_clock > clock_limit) {
6511                         DRM_DEBUG_KMS("requested pixel clock (%d kHz) too high (max: %d kHz, double wide: %s)\n",
6512                                       adjusted_mode->crtc_clock, clock_limit,
6513                                       yesno(pipe_config->double_wide));
6514                         return -EINVAL;
6515                 }
6516         }
6517
6518         /*
6519          * Pipe horizontal size must be even in:
6520          * - DVO ganged mode
6521          * - LVDS dual channel mode
6522          * - Double wide pipe
6523          */
6524         if ((intel_pipe_will_have_type(pipe_config, INTEL_OUTPUT_LVDS) &&
6525              intel_is_dual_link_lvds(dev)) || pipe_config->double_wide)
6526                 pipe_config->pipe_src_w &= ~1;
6527
6528         /* Cantiga+ cannot handle modes with a hsync front porch of 0.
6529          * WaPruneModeWithIncorrectHsyncOffset:ctg,elk,ilk,snb,ivb,vlv,hsw.
6530          */
6531         if ((INTEL_INFO(dev)->gen > 4 || IS_G4X(dev)) &&
6532                 adjusted_mode->crtc_hsync_start == adjusted_mode->crtc_hdisplay)
6533                 return -EINVAL;
6534
6535         if (HAS_IPS(dev))
6536                 hsw_compute_ips_config(crtc, pipe_config);
6537
6538         if (pipe_config->has_pch_encoder)
6539                 return ironlake_fdi_compute_config(crtc, pipe_config);
6540
6541         return 0;
6542 }
6543
6544 static int skylake_get_display_clock_speed(struct drm_device *dev)
6545 {
6546         struct drm_i915_private *dev_priv = to_i915(dev);
6547         uint32_t cdctl;
6548
6549         skl_dpll0_update(dev_priv);
6550
6551         if (dev_priv->skl_vco_freq == 0)
6552                 return 24000; /* 24MHz is the cd freq with NSSC ref */
6553
6554         cdctl = I915_READ(CDCLK_CTL);
6555
6556         if (dev_priv->skl_vco_freq == 8640) {
6557                 switch (cdctl & CDCLK_FREQ_SEL_MASK) {
6558                 case CDCLK_FREQ_450_432:
6559                         return 432000;
6560                 case CDCLK_FREQ_337_308:
6561                         return 308570;
6562                 case CDCLK_FREQ_540:
6563                         return 540000;
6564                 case CDCLK_FREQ_675_617:
6565                         return 617140;
6566                 default:
6567                         MISSING_CASE(cdctl & CDCLK_FREQ_SEL_MASK);
6568                 }
6569         } else {
6570                 switch (cdctl & CDCLK_FREQ_SEL_MASK) {
6571                 case CDCLK_FREQ_450_432:
6572                         return 450000;
6573                 case CDCLK_FREQ_337_308:
6574                         return 337500;
6575                 case CDCLK_FREQ_540:
6576                         return 540000;
6577                 case CDCLK_FREQ_675_617:
6578                         return 675000;
6579                 default:
6580                         MISSING_CASE(cdctl & CDCLK_FREQ_SEL_MASK);
6581                 }
6582         }
6583
6584         /* error case, do as if DPLL0 isn't enabled */
6585         return 24000;
6586 }
6587
6588 static int broxton_get_display_clock_speed(struct drm_device *dev)
6589 {
6590         struct drm_i915_private *dev_priv = to_i915(dev);
6591         uint32_t cdctl = I915_READ(CDCLK_CTL);
6592         uint32_t pll_ratio = I915_READ(BXT_DE_PLL_CTL) & BXT_DE_PLL_RATIO_MASK;
6593         uint32_t pll_enab = I915_READ(BXT_DE_PLL_ENABLE);
6594         int cdclk;
6595
6596         if (!(pll_enab & BXT_DE_PLL_PLL_ENABLE))
6597                 return 19200;
6598
6599         cdclk = 19200 * pll_ratio / 2;
6600
6601         switch (cdctl & BXT_CDCLK_CD2X_DIV_SEL_MASK) {
6602         case BXT_CDCLK_CD2X_DIV_SEL_1:
6603                 return cdclk;  /* 576MHz or 624MHz */
6604         case BXT_CDCLK_CD2X_DIV_SEL_1_5:
6605                 return cdclk * 2 / 3; /* 384MHz */
6606         case BXT_CDCLK_CD2X_DIV_SEL_2:
6607                 return cdclk / 2; /* 288MHz */
6608         case BXT_CDCLK_CD2X_DIV_SEL_4:
6609                 return cdclk / 4; /* 144MHz */
6610         }
6611
6612         /* error case, do as if DE PLL isn't enabled */
6613         return 19200;
6614 }
6615
6616 static int broadwell_get_display_clock_speed(struct drm_device *dev)
6617 {
6618         struct drm_i915_private *dev_priv = dev->dev_private;
6619         uint32_t lcpll = I915_READ(LCPLL_CTL);
6620         uint32_t freq = lcpll & LCPLL_CLK_FREQ_MASK;
6621
6622         if (lcpll & LCPLL_CD_SOURCE_FCLK)
6623                 return 800000;
6624         else if (I915_READ(FUSE_STRAP) & HSW_CDCLK_LIMIT)
6625                 return 450000;
6626         else if (freq == LCPLL_CLK_FREQ_450)
6627                 return 450000;
6628         else if (freq == LCPLL_CLK_FREQ_54O_BDW)
6629                 return 540000;
6630         else if (freq == LCPLL_CLK_FREQ_337_5_BDW)
6631                 return 337500;
6632         else
6633                 return 675000;
6634 }
6635
6636 static int haswell_get_display_clock_speed(struct drm_device *dev)
6637 {
6638         struct drm_i915_private *dev_priv = dev->dev_private;
6639         uint32_t lcpll = I915_READ(LCPLL_CTL);
6640         uint32_t freq = lcpll & LCPLL_CLK_FREQ_MASK;
6641
6642         if (lcpll & LCPLL_CD_SOURCE_FCLK)
6643                 return 800000;
6644         else if (I915_READ(FUSE_STRAP) & HSW_CDCLK_LIMIT)
6645                 return 450000;
6646         else if (freq == LCPLL_CLK_FREQ_450)
6647                 return 450000;
6648         else if (IS_HSW_ULT(dev))
6649                 return 337500;
6650         else
6651                 return 540000;
6652 }
6653
6654 static int valleyview_get_display_clock_speed(struct drm_device *dev)
6655 {
6656         return vlv_get_cck_clock_hpll(to_i915(dev), "cdclk",
6657                                       CCK_DISPLAY_CLOCK_CONTROL);
6658 }
6659
6660 static int ilk_get_display_clock_speed(struct drm_device *dev)
6661 {
6662         return 450000;
6663 }
6664
6665 static int i945_get_display_clock_speed(struct drm_device *dev)
6666 {
6667         return 400000;
6668 }
6669
6670 static int i915_get_display_clock_speed(struct drm_device *dev)
6671 {
6672         return 333333;
6673 }
6674
6675 static int i9xx_misc_get_display_clock_speed(struct drm_device *dev)
6676 {
6677         return 200000;
6678 }
6679
6680 static int pnv_get_display_clock_speed(struct drm_device *dev)
6681 {
6682         u16 gcfgc = 0;
6683
6684         pci_read_config_word(dev->pdev, GCFGC, &gcfgc);
6685
6686         switch (gcfgc & GC_DISPLAY_CLOCK_MASK) {
6687         case GC_DISPLAY_CLOCK_267_MHZ_PNV:
6688                 return 266667;
6689         case GC_DISPLAY_CLOCK_333_MHZ_PNV:
6690                 return 333333;
6691         case GC_DISPLAY_CLOCK_444_MHZ_PNV:
6692                 return 444444;
6693         case GC_DISPLAY_CLOCK_200_MHZ_PNV:
6694                 return 200000;
6695         default:
6696                 DRM_ERROR("Unknown pnv display core clock 0x%04x\n", gcfgc);
6697         case GC_DISPLAY_CLOCK_133_MHZ_PNV:
6698                 return 133333;
6699         case GC_DISPLAY_CLOCK_167_MHZ_PNV:
6700                 return 166667;
6701         }
6702 }
6703
6704 static int i915gm_get_display_clock_speed(struct drm_device *dev)
6705 {
6706         u16 gcfgc = 0;
6707
6708         pci_read_config_word(dev->pdev, GCFGC, &gcfgc);
6709
6710         if (gcfgc & GC_LOW_FREQUENCY_ENABLE)
6711                 return 133333;
6712         else {
6713                 switch (gcfgc & GC_DISPLAY_CLOCK_MASK) {
6714                 case GC_DISPLAY_CLOCK_333_MHZ:
6715                         return 333333;
6716                 default:
6717                 case GC_DISPLAY_CLOCK_190_200_MHZ:
6718                         return 190000;
6719                 }
6720         }
6721 }
6722
6723 static int i865_get_display_clock_speed(struct drm_device *dev)
6724 {
6725         return 266667;
6726 }
6727
6728 static int i85x_get_display_clock_speed(struct drm_device *dev)
6729 {
6730         u16 hpllcc = 0;
6731
6732         /*
6733          * 852GM/852GMV only supports 133 MHz and the HPLLCC
6734          * encoding is different :(
6735          * FIXME is this the right way to detect 852GM/852GMV?
6736          */
6737         if (dev->pdev->revision == 0x1)
6738                 return 133333;
6739
6740         pci_bus_read_config_word(dev->pdev->bus,
6741                                  PCI_DEVFN(0, 3), HPLLCC, &hpllcc);
6742
6743         /* Assume that the hardware is in the high speed state.  This
6744          * should be the default.
6745          */
6746         switch (hpllcc & GC_CLOCK_CONTROL_MASK) {
6747         case GC_CLOCK_133_200:
6748         case GC_CLOCK_133_200_2:
6749         case GC_CLOCK_100_200:
6750                 return 200000;
6751         case GC_CLOCK_166_250:
6752                 return 250000;
6753         case GC_CLOCK_100_133:
6754                 return 133333;
6755         case GC_CLOCK_133_266:
6756         case GC_CLOCK_133_266_2:
6757         case GC_CLOCK_166_266:
6758                 return 266667;
6759         }
6760
6761         /* Shouldn't happen */
6762         return 0;
6763 }
6764
6765 static int i830_get_display_clock_speed(struct drm_device *dev)
6766 {
6767         return 133333;
6768 }
6769
6770 static unsigned int intel_hpll_vco(struct drm_device *dev)
6771 {
6772         struct drm_i915_private *dev_priv = dev->dev_private;
6773         static const unsigned int blb_vco[8] = {
6774                 [0] = 3200000,
6775                 [1] = 4000000,
6776                 [2] = 5333333,
6777                 [3] = 4800000,
6778                 [4] = 6400000,
6779         };
6780         static const unsigned int pnv_vco[8] = {
6781                 [0] = 3200000,
6782                 [1] = 4000000,
6783                 [2] = 5333333,
6784                 [3] = 4800000,
6785                 [4] = 2666667,
6786         };
6787         static const unsigned int cl_vco[8] = {
6788                 [0] = 3200000,
6789                 [1] = 4000000,
6790                 [2] = 5333333,
6791                 [3] = 6400000,
6792                 [4] = 3333333,
6793                 [5] = 3566667,
6794                 [6] = 4266667,
6795         };
6796         static const unsigned int elk_vco[8] = {
6797                 [0] = 3200000,
6798                 [1] = 4000000,
6799                 [2] = 5333333,
6800                 [3] = 4800000,
6801         };
6802         static const unsigned int ctg_vco[8] = {
6803                 [0] = 3200000,
6804                 [1] = 4000000,
6805                 [2] = 5333333,
6806                 [3] = 6400000,
6807                 [4] = 2666667,
6808                 [5] = 4266667,
6809         };
6810         const unsigned int *vco_table;
6811         unsigned int vco;
6812         uint8_t tmp = 0;
6813
6814         /* FIXME other chipsets? */
6815         if (IS_GM45(dev))
6816                 vco_table = ctg_vco;
6817         else if (IS_G4X(dev))
6818                 vco_table = elk_vco;
6819         else if (IS_CRESTLINE(dev))
6820                 vco_table = cl_vco;
6821         else if (IS_PINEVIEW(dev))
6822                 vco_table = pnv_vco;
6823         else if (IS_G33(dev))
6824                 vco_table = blb_vco;
6825         else
6826                 return 0;
6827
6828         tmp = I915_READ(IS_MOBILE(dev) ? HPLLVCO_MOBILE : HPLLVCO);
6829
6830         vco = vco_table[tmp & 0x7];
6831         if (vco == 0)
6832                 DRM_ERROR("Bad HPLL VCO (HPLLVCO=0x%02x)\n", tmp);
6833         else
6834                 DRM_DEBUG_KMS("HPLL VCO %u kHz\n", vco);
6835
6836         return vco;
6837 }
6838
6839 static int gm45_get_display_clock_speed(struct drm_device *dev)
6840 {
6841         unsigned int cdclk_sel, vco = intel_hpll_vco(dev);
6842         uint16_t tmp = 0;
6843
6844         pci_read_config_word(dev->pdev, GCFGC, &tmp);
6845
6846         cdclk_sel = (tmp >> 12) & 0x1;
6847
6848         switch (vco) {
6849         case 2666667:
6850         case 4000000:
6851         case 5333333:
6852                 return cdclk_sel ? 333333 : 222222;
6853         case 3200000:
6854                 return cdclk_sel ? 320000 : 228571;
6855         default:
6856                 DRM_ERROR("Unable to determine CDCLK. HPLL VCO=%u, CFGC=0x%04x\n", vco, tmp);
6857                 return 222222;
6858         }
6859 }
6860
6861 static int i965gm_get_display_clock_speed(struct drm_device *dev)
6862 {
6863         static const uint8_t div_3200[] = { 16, 10,  8 };
6864         static const uint8_t div_4000[] = { 20, 12, 10 };
6865         static const uint8_t div_5333[] = { 24, 16, 14 };
6866         const uint8_t *div_table;
6867         unsigned int cdclk_sel, vco = intel_hpll_vco(dev);
6868         uint16_t tmp = 0;
6869
6870         pci_read_config_word(dev->pdev, GCFGC, &tmp);
6871
6872         cdclk_sel = ((tmp >> 8) & 0x1f) - 1;
6873
6874         if (cdclk_sel >= ARRAY_SIZE(div_3200))
6875                 goto fail;
6876
6877         switch (vco) {
6878         case 3200000:
6879                 div_table = div_3200;
6880                 break;
6881         case 4000000:
6882                 div_table = div_4000;
6883                 break;
6884         case 5333333:
6885                 div_table = div_5333;
6886                 break;
6887         default:
6888                 goto fail;
6889         }
6890
6891         return DIV_ROUND_CLOSEST(vco, div_table[cdclk_sel]);
6892
6893 fail:
6894         DRM_ERROR("Unable to determine CDCLK. HPLL VCO=%u kHz, CFGC=0x%04x\n", vco, tmp);
6895         return 200000;
6896 }
6897
6898 static int g33_get_display_clock_speed(struct drm_device *dev)
6899 {
6900         static const uint8_t div_3200[] = { 12, 10,  8,  7, 5, 16 };
6901         static const uint8_t div_4000[] = { 14, 12, 10,  8, 6, 20 };
6902         static const uint8_t div_4800[] = { 20, 14, 12, 10, 8, 24 };
6903         static const uint8_t div_5333[] = { 20, 16, 12, 12, 8, 28 };
6904         const uint8_t *div_table;
6905         unsigned int cdclk_sel, vco = intel_hpll_vco(dev);
6906         uint16_t tmp = 0;
6907
6908         pci_read_config_word(dev->pdev, GCFGC, &tmp);
6909
6910         cdclk_sel = (tmp >> 4) & 0x7;
6911
6912         if (cdclk_sel >= ARRAY_SIZE(div_3200))
6913                 goto fail;
6914
6915         switch (vco) {
6916         case 3200000:
6917                 div_table = div_3200;
6918                 break;
6919         case 4000000:
6920                 div_table = div_4000;
6921                 break;
6922         case 4800000:
6923                 div_table = div_4800;
6924                 break;
6925         case 5333333:
6926                 div_table = div_5333;
6927                 break;
6928         default:
6929                 goto fail;
6930         }
6931
6932         return DIV_ROUND_CLOSEST(vco, div_table[cdclk_sel]);
6933
6934 fail:
6935         DRM_ERROR("Unable to determine CDCLK. HPLL VCO=%u kHz, CFGC=0x%08x\n", vco, tmp);
6936         return 190476;
6937 }
6938
6939 static void
6940 intel_reduce_m_n_ratio(uint32_t *num, uint32_t *den)
6941 {
6942         while (*num > DATA_LINK_M_N_MASK ||
6943                *den > DATA_LINK_M_N_MASK) {
6944                 *num >>= 1;
6945                 *den >>= 1;
6946         }
6947 }
6948
6949 static void compute_m_n(unsigned int m, unsigned int n,
6950                         uint32_t *ret_m, uint32_t *ret_n)
6951 {
6952         *ret_n = min_t(unsigned int, roundup_pow_of_two(n), DATA_LINK_N_MAX);
6953         *ret_m = div_u64((uint64_t) m * *ret_n, n);
6954         intel_reduce_m_n_ratio(ret_m, ret_n);
6955 }
6956
6957 void
6958 intel_link_compute_m_n(int bits_per_pixel, int nlanes,
6959                        int pixel_clock, int link_clock,
6960                        struct intel_link_m_n *m_n)
6961 {
6962         m_n->tu = 64;
6963
6964         compute_m_n(bits_per_pixel * pixel_clock,
6965                     link_clock * nlanes * 8,
6966                     &m_n->gmch_m, &m_n->gmch_n);
6967
6968         compute_m_n(pixel_clock, link_clock,
6969                     &m_n->link_m, &m_n->link_n);
6970 }
6971
6972 static inline bool intel_panel_use_ssc(struct drm_i915_private *dev_priv)
6973 {
6974         if (i915.panel_use_ssc >= 0)
6975                 return i915.panel_use_ssc != 0;
6976         return dev_priv->vbt.lvds_use_ssc
6977                 && !(dev_priv->quirks & QUIRK_LVDS_SSC_DISABLE);
6978 }
6979
6980 static uint32_t pnv_dpll_compute_fp(struct dpll *dpll)
6981 {
6982         return (1 << dpll->n) << 16 | dpll->m2;
6983 }
6984
6985 static uint32_t i9xx_dpll_compute_fp(struct dpll *dpll)
6986 {
6987         return dpll->n << 16 | dpll->m1 << 8 | dpll->m2;
6988 }
6989
6990 static void i9xx_update_pll_dividers(struct intel_crtc *crtc,
6991                                      struct intel_crtc_state *crtc_state,
6992                                      struct dpll *reduced_clock)
6993 {
6994         struct drm_device *dev = crtc->base.dev;
6995         u32 fp, fp2 = 0;
6996
6997         if (IS_PINEVIEW(dev)) {
6998                 fp = pnv_dpll_compute_fp(&crtc_state->dpll);
6999                 if (reduced_clock)
7000                         fp2 = pnv_dpll_compute_fp(reduced_clock);
7001         } else {
7002                 fp = i9xx_dpll_compute_fp(&crtc_state->dpll);
7003                 if (reduced_clock)
7004                         fp2 = i9xx_dpll_compute_fp(reduced_clock);
7005         }
7006
7007         crtc_state->dpll_hw_state.fp0 = fp;
7008
7009         crtc->lowfreq_avail = false;
7010         if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_LVDS) &&
7011             reduced_clock) {
7012                 crtc_state->dpll_hw_state.fp1 = fp2;
7013                 crtc->lowfreq_avail = true;
7014         } else {
7015                 crtc_state->dpll_hw_state.fp1 = fp;
7016         }
7017 }
7018
7019 static void vlv_pllb_recal_opamp(struct drm_i915_private *dev_priv, enum pipe
7020                 pipe)
7021 {
7022         u32 reg_val;
7023
7024         /*
7025          * PLLB opamp always calibrates to max value of 0x3f, force enable it
7026          * and set it to a reasonable value instead.
7027          */
7028         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW9(1));
7029         reg_val &= 0xffffff00;
7030         reg_val |= 0x00000030;
7031         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW9(1), reg_val);
7032
7033         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_REF_DW13);
7034         reg_val &= 0x8cffffff;
7035         reg_val = 0x8c000000;
7036         vlv_dpio_write(dev_priv, pipe, VLV_REF_DW13, reg_val);
7037
7038         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW9(1));
7039         reg_val &= 0xffffff00;
7040         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW9(1), reg_val);
7041
7042         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_REF_DW13);
7043         reg_val &= 0x00ffffff;
7044         reg_val |= 0xb0000000;
7045         vlv_dpio_write(dev_priv, pipe, VLV_REF_DW13, reg_val);
7046 }
7047
7048 static void intel_pch_transcoder_set_m_n(struct intel_crtc *crtc,
7049                                          struct intel_link_m_n *m_n)
7050 {
7051         struct drm_device *dev = crtc->base.dev;
7052         struct drm_i915_private *dev_priv = dev->dev_private;
7053         int pipe = crtc->pipe;
7054
7055         I915_WRITE(PCH_TRANS_DATA_M1(pipe), TU_SIZE(m_n->tu) | m_n->gmch_m);
7056         I915_WRITE(PCH_TRANS_DATA_N1(pipe), m_n->gmch_n);
7057         I915_WRITE(PCH_TRANS_LINK_M1(pipe), m_n->link_m);
7058         I915_WRITE(PCH_TRANS_LINK_N1(pipe), m_n->link_n);
7059 }
7060
7061 static void intel_cpu_transcoder_set_m_n(struct intel_crtc *crtc,
7062                                          struct intel_link_m_n *m_n,
7063                                          struct intel_link_m_n *m2_n2)
7064 {
7065         struct drm_device *dev = crtc->base.dev;
7066         struct drm_i915_private *dev_priv = dev->dev_private;
7067         int pipe = crtc->pipe;
7068         enum transcoder transcoder = crtc->config->cpu_transcoder;
7069
7070         if (INTEL_INFO(dev)->gen >= 5) {
7071                 I915_WRITE(PIPE_DATA_M1(transcoder), TU_SIZE(m_n->tu) | m_n->gmch_m);
7072                 I915_WRITE(PIPE_DATA_N1(transcoder), m_n->gmch_n);
7073                 I915_WRITE(PIPE_LINK_M1(transcoder), m_n->link_m);
7074                 I915_WRITE(PIPE_LINK_N1(transcoder), m_n->link_n);
7075                 /* M2_N2 registers to be set only for gen < 8 (M2_N2 available
7076                  * for gen < 8) and if DRRS is supported (to make sure the
7077                  * registers are not unnecessarily accessed).
7078                  */
7079                 if (m2_n2 && (IS_CHERRYVIEW(dev) || INTEL_INFO(dev)->gen < 8) &&
7080                         crtc->config->has_drrs) {
7081                         I915_WRITE(PIPE_DATA_M2(transcoder),
7082                                         TU_SIZE(m2_n2->tu) | m2_n2->gmch_m);
7083                         I915_WRITE(PIPE_DATA_N2(transcoder), m2_n2->gmch_n);
7084                         I915_WRITE(PIPE_LINK_M2(transcoder), m2_n2->link_m);
7085                         I915_WRITE(PIPE_LINK_N2(transcoder), m2_n2->link_n);
7086                 }
7087         } else {
7088                 I915_WRITE(PIPE_DATA_M_G4X(pipe), TU_SIZE(m_n->tu) | m_n->gmch_m);
7089                 I915_WRITE(PIPE_DATA_N_G4X(pipe), m_n->gmch_n);
7090                 I915_WRITE(PIPE_LINK_M_G4X(pipe), m_n->link_m);
7091                 I915_WRITE(PIPE_LINK_N_G4X(pipe), m_n->link_n);
7092         }
7093 }
7094
7095 void intel_dp_set_m_n(struct intel_crtc *crtc, enum link_m_n_set m_n)
7096 {
7097         struct intel_link_m_n *dp_m_n, *dp_m2_n2 = NULL;
7098
7099         if (m_n == M1_N1) {
7100                 dp_m_n = &crtc->config->dp_m_n;
7101                 dp_m2_n2 = &crtc->config->dp_m2_n2;
7102         } else if (m_n == M2_N2) {
7103
7104                 /*
7105                  * M2_N2 registers are not supported. Hence m2_n2 divider value
7106                  * needs to be programmed into M1_N1.
7107                  */
7108                 dp_m_n = &crtc->config->dp_m2_n2;
7109         } else {
7110                 DRM_ERROR("Unsupported divider value\n");
7111                 return;
7112         }
7113
7114         if (crtc->config->has_pch_encoder)
7115                 intel_pch_transcoder_set_m_n(crtc, &crtc->config->dp_m_n);
7116         else
7117                 intel_cpu_transcoder_set_m_n(crtc, dp_m_n, dp_m2_n2);
7118 }
7119
7120 static void vlv_compute_dpll(struct intel_crtc *crtc,
7121                              struct intel_crtc_state *pipe_config)
7122 {
7123         pipe_config->dpll_hw_state.dpll = DPLL_INTEGRATED_REF_CLK_VLV |
7124                 DPLL_REF_CLK_ENABLE_VLV | DPLL_VGA_MODE_DIS;
7125         if (crtc->pipe != PIPE_A)
7126                 pipe_config->dpll_hw_state.dpll |= DPLL_INTEGRATED_CRI_CLK_VLV;
7127
7128         /* DPLL not used with DSI, but still need the rest set up */
7129         if (!pipe_config->has_dsi_encoder)
7130                 pipe_config->dpll_hw_state.dpll |= DPLL_VCO_ENABLE |
7131                         DPLL_EXT_BUFFER_ENABLE_VLV;
7132
7133         pipe_config->dpll_hw_state.dpll_md =
7134                 (pipe_config->pixel_multiplier - 1) << DPLL_MD_UDI_MULTIPLIER_SHIFT;
7135 }
7136
7137 static void chv_compute_dpll(struct intel_crtc *crtc,
7138                              struct intel_crtc_state *pipe_config)
7139 {
7140         pipe_config->dpll_hw_state.dpll = DPLL_SSC_REF_CLK_CHV |
7141                 DPLL_REF_CLK_ENABLE_VLV | DPLL_VGA_MODE_DIS;
7142         if (crtc->pipe != PIPE_A)
7143                 pipe_config->dpll_hw_state.dpll |= DPLL_INTEGRATED_CRI_CLK_VLV;
7144
7145         /* DPLL not used with DSI, but still need the rest set up */
7146         if (!pipe_config->has_dsi_encoder)
7147                 pipe_config->dpll_hw_state.dpll |= DPLL_VCO_ENABLE;
7148
7149         pipe_config->dpll_hw_state.dpll_md =
7150                 (pipe_config->pixel_multiplier - 1) << DPLL_MD_UDI_MULTIPLIER_SHIFT;
7151 }
7152
7153 static void vlv_prepare_pll(struct intel_crtc *crtc,
7154                             const struct intel_crtc_state *pipe_config)
7155 {
7156         struct drm_device *dev = crtc->base.dev;
7157         struct drm_i915_private *dev_priv = dev->dev_private;
7158         enum pipe pipe = crtc->pipe;
7159         u32 mdiv;
7160         u32 bestn, bestm1, bestm2, bestp1, bestp2;
7161         u32 coreclk, reg_val;
7162
7163         /* Enable Refclk */
7164         I915_WRITE(DPLL(pipe),
7165                    pipe_config->dpll_hw_state.dpll &
7166                    ~(DPLL_VCO_ENABLE | DPLL_EXT_BUFFER_ENABLE_VLV));
7167
7168         /* No need to actually set up the DPLL with DSI */
7169         if ((pipe_config->dpll_hw_state.dpll & DPLL_VCO_ENABLE) == 0)
7170                 return;
7171
7172         mutex_lock(&dev_priv->sb_lock);
7173
7174         bestn = pipe_config->dpll.n;
7175         bestm1 = pipe_config->dpll.m1;
7176         bestm2 = pipe_config->dpll.m2;
7177         bestp1 = pipe_config->dpll.p1;
7178         bestp2 = pipe_config->dpll.p2;
7179
7180         /* See eDP HDMI DPIO driver vbios notes doc */
7181
7182         /* PLL B needs special handling */
7183         if (pipe == PIPE_B)
7184                 vlv_pllb_recal_opamp(dev_priv, pipe);
7185
7186         /* Set up Tx target for periodic Rcomp update */
7187         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW9_BCAST, 0x0100000f);
7188
7189         /* Disable target IRef on PLL */
7190         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW8(pipe));
7191         reg_val &= 0x00ffffff;
7192         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW8(pipe), reg_val);
7193
7194         /* Disable fast lock */
7195         vlv_dpio_write(dev_priv, pipe, VLV_CMN_DW0, 0x610);
7196
7197         /* Set idtafcrecal before PLL is enabled */
7198         mdiv = ((bestm1 << DPIO_M1DIV_SHIFT) | (bestm2 & DPIO_M2DIV_MASK));
7199         mdiv |= ((bestp1 << DPIO_P1_SHIFT) | (bestp2 << DPIO_P2_SHIFT));
7200         mdiv |= ((bestn << DPIO_N_SHIFT));
7201         mdiv |= (1 << DPIO_K_SHIFT);
7202
7203         /*
7204          * Post divider depends on pixel clock rate, DAC vs digital (and LVDS,
7205          * but we don't support that).
7206          * Note: don't use the DAC post divider as it seems unstable.
7207          */
7208         mdiv |= (DPIO_POST_DIV_HDMIDP << DPIO_POST_DIV_SHIFT);
7209         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW3(pipe), mdiv);
7210
7211         mdiv |= DPIO_ENABLE_CALIBRATION;
7212         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW3(pipe), mdiv);
7213
7214         /* Set HBR and RBR LPF coefficients */
7215         if (pipe_config->port_clock == 162000 ||
7216             intel_pipe_has_type(crtc, INTEL_OUTPUT_ANALOG) ||
7217             intel_pipe_has_type(crtc, INTEL_OUTPUT_HDMI))
7218                 vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW10(pipe),
7219                                  0x009f0003);
7220         else
7221                 vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW10(pipe),
7222                                  0x00d0000f);
7223
7224         if (pipe_config->has_dp_encoder) {
7225                 /* Use SSC source */
7226                 if (pipe == PIPE_A)
7227                         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW5(pipe),
7228                                          0x0df40000);
7229                 else
7230                         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW5(pipe),
7231                                          0x0df70000);
7232         } else { /* HDMI or VGA */
7233                 /* Use bend source */
7234                 if (pipe == PIPE_A)
7235                         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW5(pipe),
7236                                          0x0df70000);
7237                 else
7238                         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW5(pipe),
7239                                          0x0df40000);
7240         }
7241
7242         coreclk = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW7(pipe));
7243         coreclk = (coreclk & 0x0000ff00) | 0x01c00000;
7244         if (intel_pipe_has_type(crtc, INTEL_OUTPUT_DISPLAYPORT) ||
7245             intel_pipe_has_type(crtc, INTEL_OUTPUT_EDP))
7246                 coreclk |= 0x01000000;
7247         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW7(pipe), coreclk);
7248
7249         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW11(pipe), 0x87871000);
7250         mutex_unlock(&dev_priv->sb_lock);
7251 }
7252
7253 static void chv_prepare_pll(struct intel_crtc *crtc,
7254                             const struct intel_crtc_state *pipe_config)
7255 {
7256         struct drm_device *dev = crtc->base.dev;
7257         struct drm_i915_private *dev_priv = dev->dev_private;
7258         enum pipe pipe = crtc->pipe;
7259         enum dpio_channel port = vlv_pipe_to_channel(pipe);
7260         u32 loopfilter, tribuf_calcntr;
7261         u32 bestn, bestm1, bestm2, bestp1, bestp2, bestm2_frac;
7262         u32 dpio_val;
7263         int vco;
7264
7265         /* Enable Refclk and SSC */
7266         I915_WRITE(DPLL(pipe),
7267                    pipe_config->dpll_hw_state.dpll & ~DPLL_VCO_ENABLE);
7268
7269         /* No need to actually set up the DPLL with DSI */
7270         if ((pipe_config->dpll_hw_state.dpll & DPLL_VCO_ENABLE) == 0)
7271                 return;
7272
7273         bestn = pipe_config->dpll.n;
7274         bestm2_frac = pipe_config->dpll.m2 & 0x3fffff;
7275         bestm1 = pipe_config->dpll.m1;
7276         bestm2 = pipe_config->dpll.m2 >> 22;
7277         bestp1 = pipe_config->dpll.p1;
7278         bestp2 = pipe_config->dpll.p2;
7279         vco = pipe_config->dpll.vco;
7280         dpio_val = 0;
7281         loopfilter = 0;
7282
7283         mutex_lock(&dev_priv->sb_lock);
7284
7285         /* p1 and p2 divider */
7286         vlv_dpio_write(dev_priv, pipe, CHV_CMN_DW13(port),
7287                         5 << DPIO_CHV_S1_DIV_SHIFT |
7288                         bestp1 << DPIO_CHV_P1_DIV_SHIFT |
7289                         bestp2 << DPIO_CHV_P2_DIV_SHIFT |
7290                         1 << DPIO_CHV_K_DIV_SHIFT);
7291
7292         /* Feedback post-divider - m2 */
7293         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW0(port), bestm2);
7294
7295         /* Feedback refclk divider - n and m1 */
7296         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW1(port),
7297                         DPIO_CHV_M1_DIV_BY_2 |
7298                         1 << DPIO_CHV_N_DIV_SHIFT);
7299
7300         /* M2 fraction division */
7301         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW2(port), bestm2_frac);
7302
7303         /* M2 fraction division enable */
7304         dpio_val = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW3(port));
7305         dpio_val &= ~(DPIO_CHV_FEEDFWD_GAIN_MASK | DPIO_CHV_FRAC_DIV_EN);
7306         dpio_val |= (2 << DPIO_CHV_FEEDFWD_GAIN_SHIFT);
7307         if (bestm2_frac)
7308                 dpio_val |= DPIO_CHV_FRAC_DIV_EN;
7309         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW3(port), dpio_val);
7310
7311         /* Program digital lock detect threshold */
7312         dpio_val = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW9(port));
7313         dpio_val &= ~(DPIO_CHV_INT_LOCK_THRESHOLD_MASK |
7314                                         DPIO_CHV_INT_LOCK_THRESHOLD_SEL_COARSE);
7315         dpio_val |= (0x5 << DPIO_CHV_INT_LOCK_THRESHOLD_SHIFT);
7316         if (!bestm2_frac)
7317                 dpio_val |= DPIO_CHV_INT_LOCK_THRESHOLD_SEL_COARSE;
7318         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW9(port), dpio_val);
7319
7320         /* Loop filter */
7321         if (vco == 5400000) {
7322                 loopfilter |= (0x3 << DPIO_CHV_PROP_COEFF_SHIFT);
7323                 loopfilter |= (0x8 << DPIO_CHV_INT_COEFF_SHIFT);
7324                 loopfilter |= (0x1 << DPIO_CHV_GAIN_CTRL_SHIFT);
7325                 tribuf_calcntr = 0x9;
7326         } else if (vco <= 6200000) {
7327                 loopfilter |= (0x5 << DPIO_CHV_PROP_COEFF_SHIFT);
7328                 loopfilter |= (0xB << DPIO_CHV_INT_COEFF_SHIFT);
7329                 loopfilter |= (0x3 << DPIO_CHV_GAIN_CTRL_SHIFT);
7330                 tribuf_calcntr = 0x9;
7331         } else if (vco <= 6480000) {
7332                 loopfilter |= (0x4 << DPIO_CHV_PROP_COEFF_SHIFT);
7333                 loopfilter |= (0x9 << DPIO_CHV_INT_COEFF_SHIFT);
7334                 loopfilter |= (0x3 << DPIO_CHV_GAIN_CTRL_SHIFT);
7335                 tribuf_calcntr = 0x8;
7336         } else {
7337                 /* Not supported. Apply the same limits as in the max case */
7338                 loopfilter |= (0x4 << DPIO_CHV_PROP_COEFF_SHIFT);
7339                 loopfilter |= (0x9 << DPIO_CHV_INT_COEFF_SHIFT);
7340                 loopfilter |= (0x3 << DPIO_CHV_GAIN_CTRL_SHIFT);
7341                 tribuf_calcntr = 0;
7342         }
7343         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW6(port), loopfilter);
7344
7345         dpio_val = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW8(port));
7346         dpio_val &= ~DPIO_CHV_TDC_TARGET_CNT_MASK;
7347         dpio_val |= (tribuf_calcntr << DPIO_CHV_TDC_TARGET_CNT_SHIFT);
7348         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW8(port), dpio_val);
7349
7350         /* AFC Recal */
7351         vlv_dpio_write(dev_priv, pipe, CHV_CMN_DW14(port),
7352                         vlv_dpio_read(dev_priv, pipe, CHV_CMN_DW14(port)) |
7353                         DPIO_AFC_RECAL);
7354
7355         mutex_unlock(&dev_priv->sb_lock);
7356 }
7357
7358 /**
7359  * vlv_force_pll_on - forcibly enable just the PLL
7360  * @dev_priv: i915 private structure
7361  * @pipe: pipe PLL to enable
7362  * @dpll: PLL configuration
7363  *
7364  * Enable the PLL for @pipe using the supplied @dpll config. To be used
7365  * in cases where we need the PLL enabled even when @pipe is not going to
7366  * be enabled.
7367  */
7368 int vlv_force_pll_on(struct drm_device *dev, enum pipe pipe,
7369                      const struct dpll *dpll)
7370 {
7371         struct intel_crtc *crtc =
7372                 to_intel_crtc(intel_get_crtc_for_pipe(dev, pipe));
7373         struct intel_crtc_state *pipe_config;
7374
7375         pipe_config = kzalloc(sizeof(*pipe_config), GFP_KERNEL);
7376         if (!pipe_config)
7377                 return -ENOMEM;
7378
7379         pipe_config->base.crtc = &crtc->base;
7380         pipe_config->pixel_multiplier = 1;
7381         pipe_config->dpll = *dpll;
7382
7383         if (IS_CHERRYVIEW(dev)) {
7384                 chv_compute_dpll(crtc, pipe_config);
7385                 chv_prepare_pll(crtc, pipe_config);
7386                 chv_enable_pll(crtc, pipe_config);
7387         } else {
7388                 vlv_compute_dpll(crtc, pipe_config);
7389                 vlv_prepare_pll(crtc, pipe_config);
7390                 vlv_enable_pll(crtc, pipe_config);
7391         }
7392
7393         kfree(pipe_config);
7394
7395         return 0;
7396 }
7397
7398 /**
7399  * vlv_force_pll_off - forcibly disable just the PLL
7400  * @dev_priv: i915 private structure
7401  * @pipe: pipe PLL to disable
7402  *
7403  * Disable the PLL for @pipe. To be used in cases where we need
7404  * the PLL enabled even when @pipe is not going to be enabled.
7405  */
7406 void vlv_force_pll_off(struct drm_device *dev, enum pipe pipe)
7407 {
7408         if (IS_CHERRYVIEW(dev))
7409                 chv_disable_pll(to_i915(dev), pipe);
7410         else
7411                 vlv_disable_pll(to_i915(dev), pipe);
7412 }
7413
7414 static void i9xx_compute_dpll(struct intel_crtc *crtc,
7415                               struct intel_crtc_state *crtc_state,
7416                               struct dpll *reduced_clock)
7417 {
7418         struct drm_device *dev = crtc->base.dev;
7419         struct drm_i915_private *dev_priv = dev->dev_private;
7420         u32 dpll;
7421         bool is_sdvo;
7422         struct dpll *clock = &crtc_state->dpll;
7423
7424         i9xx_update_pll_dividers(crtc, crtc_state, reduced_clock);
7425
7426         is_sdvo = intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_SDVO) ||
7427                 intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_HDMI);
7428
7429         dpll = DPLL_VGA_MODE_DIS;
7430
7431         if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_LVDS))
7432                 dpll |= DPLLB_MODE_LVDS;
7433         else
7434                 dpll |= DPLLB_MODE_DAC_SERIAL;
7435
7436         if (IS_I945G(dev) || IS_I945GM(dev) || IS_G33(dev)) {
7437                 dpll |= (crtc_state->pixel_multiplier - 1)
7438                         << SDVO_MULTIPLIER_SHIFT_HIRES;
7439         }
7440
7441         if (is_sdvo)
7442                 dpll |= DPLL_SDVO_HIGH_SPEED;
7443
7444         if (crtc_state->has_dp_encoder)
7445                 dpll |= DPLL_SDVO_HIGH_SPEED;
7446
7447         /* compute bitmask from p1 value */
7448         if (IS_PINEVIEW(dev))
7449                 dpll |= (1 << (clock->p1 - 1)) << DPLL_FPA01_P1_POST_DIV_SHIFT_PINEVIEW;
7450         else {
7451                 dpll |= (1 << (clock->p1 - 1)) << DPLL_FPA01_P1_POST_DIV_SHIFT;
7452                 if (IS_G4X(dev) && reduced_clock)
7453                         dpll |= (1 << (reduced_clock->p1 - 1)) << DPLL_FPA1_P1_POST_DIV_SHIFT;
7454         }
7455         switch (clock->p2) {
7456         case 5:
7457                 dpll |= DPLL_DAC_SERIAL_P2_CLOCK_DIV_5;
7458                 break;
7459         case 7:
7460                 dpll |= DPLLB_LVDS_P2_CLOCK_DIV_7;
7461                 break;
7462         case 10:
7463                 dpll |= DPLL_DAC_SERIAL_P2_CLOCK_DIV_10;
7464                 break;
7465         case 14:
7466                 dpll |= DPLLB_LVDS_P2_CLOCK_DIV_14;
7467                 break;
7468         }
7469         if (INTEL_INFO(dev)->gen >= 4)
7470                 dpll |= (6 << PLL_LOAD_PULSE_PHASE_SHIFT);
7471
7472         if (crtc_state->sdvo_tv_clock)
7473                 dpll |= PLL_REF_INPUT_TVCLKINBC;
7474         else if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_LVDS) &&
7475                  intel_panel_use_ssc(dev_priv))
7476                 dpll |= PLLB_REF_INPUT_SPREADSPECTRUMIN;
7477         else
7478                 dpll |= PLL_REF_INPUT_DREFCLK;
7479
7480         dpll |= DPLL_VCO_ENABLE;
7481         crtc_state->dpll_hw_state.dpll = dpll;
7482
7483         if (INTEL_INFO(dev)->gen >= 4) {
7484                 u32 dpll_md = (crtc_state->pixel_multiplier - 1)
7485                         << DPLL_MD_UDI_MULTIPLIER_SHIFT;
7486                 crtc_state->dpll_hw_state.dpll_md = dpll_md;
7487         }
7488 }
7489
7490 static void i8xx_compute_dpll(struct intel_crtc *crtc,
7491                               struct intel_crtc_state *crtc_state,
7492                               struct dpll *reduced_clock)
7493 {
7494         struct drm_device *dev = crtc->base.dev;
7495         struct drm_i915_private *dev_priv = dev->dev_private;
7496         u32 dpll;
7497         struct dpll *clock = &crtc_state->dpll;
7498
7499         i9xx_update_pll_dividers(crtc, crtc_state, reduced_clock);
7500
7501         dpll = DPLL_VGA_MODE_DIS;
7502
7503         if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_LVDS)) {
7504                 dpll |= (1 << (clock->p1 - 1)) << DPLL_FPA01_P1_POST_DIV_SHIFT;
7505         } else {
7506                 if (clock->p1 == 2)
7507                         dpll |= PLL_P1_DIVIDE_BY_TWO;
7508                 else
7509                         dpll |= (clock->p1 - 2) << DPLL_FPA01_P1_POST_DIV_SHIFT;
7510                 if (clock->p2 == 4)
7511                         dpll |= PLL_P2_DIVIDE_BY_4;
7512         }
7513
7514         if (!IS_I830(dev) && intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_DVO))
7515                 dpll |= DPLL_DVO_2X_MODE;
7516
7517         if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_LVDS) &&
7518             intel_panel_use_ssc(dev_priv))
7519                 dpll |= PLLB_REF_INPUT_SPREADSPECTRUMIN;
7520         else
7521                 dpll |= PLL_REF_INPUT_DREFCLK;
7522
7523         dpll |= DPLL_VCO_ENABLE;
7524         crtc_state->dpll_hw_state.dpll = dpll;
7525 }
7526
7527 static void intel_set_pipe_timings(struct intel_crtc *intel_crtc)
7528 {
7529         struct drm_device *dev = intel_crtc->base.dev;
7530         struct drm_i915_private *dev_priv = dev->dev_private;
7531         enum pipe pipe = intel_crtc->pipe;
7532         enum transcoder cpu_transcoder = intel_crtc->config->cpu_transcoder;
7533         const struct drm_display_mode *adjusted_mode = &intel_crtc->config->base.adjusted_mode;
7534         uint32_t crtc_vtotal, crtc_vblank_end;
7535         int vsyncshift = 0;
7536
7537         /* We need to be careful not to changed the adjusted mode, for otherwise
7538          * the hw state checker will get angry at the mismatch. */
7539         crtc_vtotal = adjusted_mode->crtc_vtotal;
7540         crtc_vblank_end = adjusted_mode->crtc_vblank_end;
7541
7542         if (adjusted_mode->flags & DRM_MODE_FLAG_INTERLACE) {
7543                 /* the chip adds 2 halflines automatically */
7544                 crtc_vtotal -= 1;
7545                 crtc_vblank_end -= 1;
7546
7547                 if (intel_pipe_has_type(intel_crtc, INTEL_OUTPUT_SDVO))
7548                         vsyncshift = (adjusted_mode->crtc_htotal - 1) / 2;
7549                 else
7550                         vsyncshift = adjusted_mode->crtc_hsync_start -
7551                                 adjusted_mode->crtc_htotal / 2;
7552                 if (vsyncshift < 0)
7553                         vsyncshift += adjusted_mode->crtc_htotal;
7554         }
7555
7556         if (INTEL_INFO(dev)->gen > 3)
7557                 I915_WRITE(VSYNCSHIFT(cpu_transcoder), vsyncshift);
7558
7559         I915_WRITE(HTOTAL(cpu_transcoder),
7560                    (adjusted_mode->crtc_hdisplay - 1) |
7561                    ((adjusted_mode->crtc_htotal - 1) << 16));
7562         I915_WRITE(HBLANK(cpu_transcoder),
7563                    (adjusted_mode->crtc_hblank_start - 1) |
7564                    ((adjusted_mode->crtc_hblank_end - 1) << 16));
7565         I915_WRITE(HSYNC(cpu_transcoder),
7566                    (adjusted_mode->crtc_hsync_start - 1) |
7567                    ((adjusted_mode->crtc_hsync_end - 1) << 16));
7568
7569         I915_WRITE(VTOTAL(cpu_transcoder),
7570                    (adjusted_mode->crtc_vdisplay - 1) |
7571                    ((crtc_vtotal - 1) << 16));
7572         I915_WRITE(VBLANK(cpu_transcoder),
7573                    (adjusted_mode->crtc_vblank_start - 1) |
7574                    ((crtc_vblank_end - 1) << 16));
7575         I915_WRITE(VSYNC(cpu_transcoder),
7576                    (adjusted_mode->crtc_vsync_start - 1) |
7577                    ((adjusted_mode->crtc_vsync_end - 1) << 16));
7578
7579         /* Workaround: when the EDP input selection is B, the VTOTAL_B must be
7580          * programmed with the VTOTAL_EDP value. Same for VTOTAL_C. This is
7581          * documented on the DDI_FUNC_CTL register description, EDP Input Select
7582          * bits. */
7583         if (IS_HASWELL(dev) && cpu_transcoder == TRANSCODER_EDP &&
7584             (pipe == PIPE_B || pipe == PIPE_C))
7585                 I915_WRITE(VTOTAL(pipe), I915_READ(VTOTAL(cpu_transcoder)));
7586
7587 }
7588
7589 static void intel_set_pipe_src_size(struct intel_crtc *intel_crtc)
7590 {
7591         struct drm_device *dev = intel_crtc->base.dev;
7592         struct drm_i915_private *dev_priv = dev->dev_private;
7593         enum pipe pipe = intel_crtc->pipe;
7594
7595         /* pipesrc controls the size that is scaled from, which should
7596          * always be the user's requested size.
7597          */
7598         I915_WRITE(PIPESRC(pipe),
7599                    ((intel_crtc->config->pipe_src_w - 1) << 16) |
7600                    (intel_crtc->config->pipe_src_h - 1));
7601 }
7602
7603 static void intel_get_pipe_timings(struct intel_crtc *crtc,
7604                                    struct intel_crtc_state *pipe_config)
7605 {
7606         struct drm_device *dev = crtc->base.dev;
7607         struct drm_i915_private *dev_priv = dev->dev_private;
7608         enum transcoder cpu_transcoder = pipe_config->cpu_transcoder;
7609         uint32_t tmp;
7610
7611         tmp = I915_READ(HTOTAL(cpu_transcoder));
7612         pipe_config->base.adjusted_mode.crtc_hdisplay = (tmp & 0xffff) + 1;
7613         pipe_config->base.adjusted_mode.crtc_htotal = ((tmp >> 16) & 0xffff) + 1;
7614         tmp = I915_READ(HBLANK(cpu_transcoder));
7615         pipe_config->base.adjusted_mode.crtc_hblank_start = (tmp & 0xffff) + 1;
7616         pipe_config->base.adjusted_mode.crtc_hblank_end = ((tmp >> 16) & 0xffff) + 1;
7617         tmp = I915_READ(HSYNC(cpu_transcoder));
7618         pipe_config->base.adjusted_mode.crtc_hsync_start = (tmp & 0xffff) + 1;
7619         pipe_config->base.adjusted_mode.crtc_hsync_end = ((tmp >> 16) & 0xffff) + 1;
7620
7621         tmp = I915_READ(VTOTAL(cpu_transcoder));
7622         pipe_config->base.adjusted_mode.crtc_vdisplay = (tmp & 0xffff) + 1;
7623         pipe_config->base.adjusted_mode.crtc_vtotal = ((tmp >> 16) & 0xffff) + 1;
7624         tmp = I915_READ(VBLANK(cpu_transcoder));
7625         pipe_config->base.adjusted_mode.crtc_vblank_start = (tmp & 0xffff) + 1;
7626         pipe_config->base.adjusted_mode.crtc_vblank_end = ((tmp >> 16) & 0xffff) + 1;
7627         tmp = I915_READ(VSYNC(cpu_transcoder));
7628         pipe_config->base.adjusted_mode.crtc_vsync_start = (tmp & 0xffff) + 1;
7629         pipe_config->base.adjusted_mode.crtc_vsync_end = ((tmp >> 16) & 0xffff) + 1;
7630
7631         if (I915_READ(PIPECONF(cpu_transcoder)) & PIPECONF_INTERLACE_MASK) {
7632                 pipe_config->base.adjusted_mode.flags |= DRM_MODE_FLAG_INTERLACE;
7633                 pipe_config->base.adjusted_mode.crtc_vtotal += 1;
7634                 pipe_config->base.adjusted_mode.crtc_vblank_end += 1;
7635         }
7636 }
7637
7638 static void intel_get_pipe_src_size(struct intel_crtc *crtc,
7639                                     struct intel_crtc_state *pipe_config)
7640 {
7641         struct drm_device *dev = crtc->base.dev;
7642         struct drm_i915_private *dev_priv = dev->dev_private;
7643         u32 tmp;
7644
7645         tmp = I915_READ(PIPESRC(crtc->pipe));
7646         pipe_config->pipe_src_h = (tmp & 0xffff) + 1;
7647         pipe_config->pipe_src_w = ((tmp >> 16) & 0xffff) + 1;
7648
7649         pipe_config->base.mode.vdisplay = pipe_config->pipe_src_h;
7650         pipe_config->base.mode.hdisplay = pipe_config->pipe_src_w;
7651 }
7652
7653 void intel_mode_from_pipe_config(struct drm_display_mode *mode,
7654                                  struct intel_crtc_state *pipe_config)
7655 {
7656         mode->hdisplay = pipe_config->base.adjusted_mode.crtc_hdisplay;
7657         mode->htotal = pipe_config->base.adjusted_mode.crtc_htotal;
7658         mode->hsync_start = pipe_config->base.adjusted_mode.crtc_hsync_start;
7659         mode->hsync_end = pipe_config->base.adjusted_mode.crtc_hsync_end;
7660
7661         mode->vdisplay = pipe_config->base.adjusted_mode.crtc_vdisplay;
7662         mode->vtotal = pipe_config->base.adjusted_mode.crtc_vtotal;
7663         mode->vsync_start = pipe_config->base.adjusted_mode.crtc_vsync_start;
7664         mode->vsync_end = pipe_config->base.adjusted_mode.crtc_vsync_end;
7665
7666         mode->flags = pipe_config->base.adjusted_mode.flags;
7667         mode->type = DRM_MODE_TYPE_DRIVER;
7668
7669         mode->clock = pipe_config->base.adjusted_mode.crtc_clock;
7670         mode->flags |= pipe_config->base.adjusted_mode.flags;
7671
7672         mode->hsync = drm_mode_hsync(mode);
7673         mode->vrefresh = drm_mode_vrefresh(mode);
7674         drm_mode_set_name(mode);
7675 }
7676
7677 static void i9xx_set_pipeconf(struct intel_crtc *intel_crtc)
7678 {
7679         struct drm_device *dev = intel_crtc->base.dev;
7680         struct drm_i915_private *dev_priv = dev->dev_private;
7681         uint32_t pipeconf;
7682
7683         pipeconf = 0;
7684
7685         if ((intel_crtc->pipe == PIPE_A && dev_priv->quirks & QUIRK_PIPEA_FORCE) ||
7686             (intel_crtc->pipe == PIPE_B && dev_priv->quirks & QUIRK_PIPEB_FORCE))
7687                 pipeconf |= I915_READ(PIPECONF(intel_crtc->pipe)) & PIPECONF_ENABLE;
7688
7689         if (intel_crtc->config->double_wide)
7690                 pipeconf |= PIPECONF_DOUBLE_WIDE;
7691
7692         /* only g4x and later have fancy bpc/dither controls */
7693         if (IS_G4X(dev) || IS_VALLEYVIEW(dev) || IS_CHERRYVIEW(dev)) {
7694                 /* Bspec claims that we can't use dithering for 30bpp pipes. */
7695                 if (intel_crtc->config->dither && intel_crtc->config->pipe_bpp != 30)
7696                         pipeconf |= PIPECONF_DITHER_EN |
7697                                     PIPECONF_DITHER_TYPE_SP;
7698
7699                 switch (intel_crtc->config->pipe_bpp) {
7700                 case 18:
7701                         pipeconf |= PIPECONF_6BPC;
7702                         break;
7703                 case 24:
7704                         pipeconf |= PIPECONF_8BPC;
7705                         break;
7706                 case 30:
7707                         pipeconf |= PIPECONF_10BPC;
7708                         break;
7709                 default:
7710                         /* Case prevented by intel_choose_pipe_bpp_dither. */
7711                         BUG();
7712                 }
7713         }
7714
7715         if (HAS_PIPE_CXSR(dev)) {
7716                 if (intel_crtc->lowfreq_avail) {
7717                         DRM_DEBUG_KMS("enabling CxSR downclocking\n");
7718                         pipeconf |= PIPECONF_CXSR_DOWNCLOCK;
7719                 } else {
7720                         DRM_DEBUG_KMS("disabling CxSR downclocking\n");
7721                 }
7722         }
7723
7724         if (intel_crtc->config->base.adjusted_mode.flags & DRM_MODE_FLAG_INTERLACE) {
7725                 if (INTEL_INFO(dev)->gen < 4 ||
7726                     intel_pipe_has_type(intel_crtc, INTEL_OUTPUT_SDVO))
7727                         pipeconf |= PIPECONF_INTERLACE_W_FIELD_INDICATION;
7728                 else
7729                         pipeconf |= PIPECONF_INTERLACE_W_SYNC_SHIFT;
7730         } else
7731                 pipeconf |= PIPECONF_PROGRESSIVE;
7732
7733         if ((IS_VALLEYVIEW(dev) || IS_CHERRYVIEW(dev)) &&
7734              intel_crtc->config->limited_color_range)
7735                 pipeconf |= PIPECONF_COLOR_RANGE_SELECT;
7736
7737         I915_WRITE(PIPECONF(intel_crtc->pipe), pipeconf);
7738         POSTING_READ(PIPECONF(intel_crtc->pipe));
7739 }
7740
7741 static int i8xx_crtc_compute_clock(struct intel_crtc *crtc,
7742                                    struct intel_crtc_state *crtc_state)
7743 {
7744         struct drm_device *dev = crtc->base.dev;
7745         struct drm_i915_private *dev_priv = dev->dev_private;
7746         const struct intel_limit *limit;
7747         int refclk = 48000;
7748
7749         memset(&crtc_state->dpll_hw_state, 0,
7750                sizeof(crtc_state->dpll_hw_state));
7751
7752         if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_LVDS)) {
7753                 if (intel_panel_use_ssc(dev_priv)) {
7754                         refclk = dev_priv->vbt.lvds_ssc_freq;
7755                         DRM_DEBUG_KMS("using SSC reference clock of %d kHz\n", refclk);
7756                 }
7757
7758                 limit = &intel_limits_i8xx_lvds;
7759         } else if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_DVO)) {
7760                 limit = &intel_limits_i8xx_dvo;
7761         } else {
7762                 limit = &intel_limits_i8xx_dac;
7763         }
7764
7765         if (!crtc_state->clock_set &&
7766             !i9xx_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
7767                                  refclk, NULL, &crtc_state->dpll)) {
7768                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
7769                 return -EINVAL;
7770         }
7771
7772         i8xx_compute_dpll(crtc, crtc_state, NULL);
7773
7774         return 0;
7775 }
7776
7777 static int g4x_crtc_compute_clock(struct intel_crtc *crtc,
7778                                   struct intel_crtc_state *crtc_state)
7779 {
7780         struct drm_device *dev = crtc->base.dev;
7781         struct drm_i915_private *dev_priv = dev->dev_private;
7782         const struct intel_limit *limit;
7783         int refclk = 96000;
7784
7785         memset(&crtc_state->dpll_hw_state, 0,
7786                sizeof(crtc_state->dpll_hw_state));
7787
7788         if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_LVDS)) {
7789                 if (intel_panel_use_ssc(dev_priv)) {
7790                         refclk = dev_priv->vbt.lvds_ssc_freq;
7791                         DRM_DEBUG_KMS("using SSC reference clock of %d kHz\n", refclk);
7792                 }
7793
7794                 if (intel_is_dual_link_lvds(dev))
7795                         limit = &intel_limits_g4x_dual_channel_lvds;
7796                 else
7797                         limit = &intel_limits_g4x_single_channel_lvds;
7798         } else if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_HDMI) ||
7799                    intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_ANALOG)) {
7800                 limit = &intel_limits_g4x_hdmi;
7801         } else if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_SDVO)) {
7802                 limit = &intel_limits_g4x_sdvo;
7803         } else {
7804                 /* The option is for other outputs */
7805                 limit = &intel_limits_i9xx_sdvo;
7806         }
7807
7808         if (!crtc_state->clock_set &&
7809             !g4x_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
7810                                 refclk, NULL, &crtc_state->dpll)) {
7811                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
7812                 return -EINVAL;
7813         }
7814
7815         i9xx_compute_dpll(crtc, crtc_state, NULL);
7816
7817         return 0;
7818 }
7819
7820 static int pnv_crtc_compute_clock(struct intel_crtc *crtc,
7821                                   struct intel_crtc_state *crtc_state)
7822 {
7823         struct drm_device *dev = crtc->base.dev;
7824         struct drm_i915_private *dev_priv = dev->dev_private;
7825         const struct intel_limit *limit;
7826         int refclk = 96000;
7827
7828         memset(&crtc_state->dpll_hw_state, 0,
7829                sizeof(crtc_state->dpll_hw_state));
7830
7831         if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_LVDS)) {
7832                 if (intel_panel_use_ssc(dev_priv)) {
7833                         refclk = dev_priv->vbt.lvds_ssc_freq;
7834                         DRM_DEBUG_KMS("using SSC reference clock of %d kHz\n", refclk);
7835                 }
7836
7837                 limit = &intel_limits_pineview_lvds;
7838         } else {
7839                 limit = &intel_limits_pineview_sdvo;
7840         }
7841
7842         if (!crtc_state->clock_set &&
7843             !pnv_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
7844                                 refclk, NULL, &crtc_state->dpll)) {
7845                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
7846                 return -EINVAL;
7847         }
7848
7849         i9xx_compute_dpll(crtc, crtc_state, NULL);
7850
7851         return 0;
7852 }
7853
7854 static int i9xx_crtc_compute_clock(struct intel_crtc *crtc,
7855                                    struct intel_crtc_state *crtc_state)
7856 {
7857         struct drm_device *dev = crtc->base.dev;
7858         struct drm_i915_private *dev_priv = dev->dev_private;
7859         const struct intel_limit *limit;
7860         int refclk = 96000;
7861
7862         memset(&crtc_state->dpll_hw_state, 0,
7863                sizeof(crtc_state->dpll_hw_state));
7864
7865         if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_LVDS)) {
7866                 if (intel_panel_use_ssc(dev_priv)) {
7867                         refclk = dev_priv->vbt.lvds_ssc_freq;
7868                         DRM_DEBUG_KMS("using SSC reference clock of %d kHz\n", refclk);
7869                 }
7870
7871                 limit = &intel_limits_i9xx_lvds;
7872         } else {
7873                 limit = &intel_limits_i9xx_sdvo;
7874         }
7875
7876         if (!crtc_state->clock_set &&
7877             !i9xx_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
7878                                  refclk, NULL, &crtc_state->dpll)) {
7879                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
7880                 return -EINVAL;
7881         }
7882
7883         i9xx_compute_dpll(crtc, crtc_state, NULL);
7884
7885         return 0;
7886 }
7887
7888 static int chv_crtc_compute_clock(struct intel_crtc *crtc,
7889                                   struct intel_crtc_state *crtc_state)
7890 {
7891         int refclk = 100000;
7892         const struct intel_limit *limit = &intel_limits_chv;
7893
7894         memset(&crtc_state->dpll_hw_state, 0,
7895                sizeof(crtc_state->dpll_hw_state));
7896
7897         if (!crtc_state->clock_set &&
7898             !chv_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
7899                                 refclk, NULL, &crtc_state->dpll)) {
7900                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
7901                 return -EINVAL;
7902         }
7903
7904         chv_compute_dpll(crtc, crtc_state);
7905
7906         return 0;
7907 }
7908
7909 static int vlv_crtc_compute_clock(struct intel_crtc *crtc,
7910                                   struct intel_crtc_state *crtc_state)
7911 {
7912         int refclk = 100000;
7913         const struct intel_limit *limit = &intel_limits_vlv;
7914
7915         memset(&crtc_state->dpll_hw_state, 0,
7916                sizeof(crtc_state->dpll_hw_state));
7917
7918         if (!crtc_state->clock_set &&
7919             !vlv_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
7920                                 refclk, NULL, &crtc_state->dpll)) {
7921                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
7922                 return -EINVAL;
7923         }
7924
7925         vlv_compute_dpll(crtc, crtc_state);
7926
7927         return 0;
7928 }
7929
7930 static void i9xx_get_pfit_config(struct intel_crtc *crtc,
7931                                  struct intel_crtc_state *pipe_config)
7932 {
7933         struct drm_device *dev = crtc->base.dev;
7934         struct drm_i915_private *dev_priv = dev->dev_private;
7935         uint32_t tmp;
7936
7937         if (INTEL_INFO(dev)->gen <= 3 && (IS_I830(dev) || !IS_MOBILE(dev)))
7938                 return;
7939
7940         tmp = I915_READ(PFIT_CONTROL);
7941         if (!(tmp & PFIT_ENABLE))
7942                 return;
7943
7944         /* Check whether the pfit is attached to our pipe. */
7945         if (INTEL_INFO(dev)->gen < 4) {
7946                 if (crtc->pipe != PIPE_B)
7947                         return;
7948         } else {
7949                 if ((tmp & PFIT_PIPE_MASK) != (crtc->pipe << PFIT_PIPE_SHIFT))
7950                         return;
7951         }
7952
7953         pipe_config->gmch_pfit.control = tmp;
7954         pipe_config->gmch_pfit.pgm_ratios = I915_READ(PFIT_PGM_RATIOS);
7955 }
7956
7957 static void vlv_crtc_clock_get(struct intel_crtc *crtc,
7958                                struct intel_crtc_state *pipe_config)
7959 {
7960         struct drm_device *dev = crtc->base.dev;
7961         struct drm_i915_private *dev_priv = dev->dev_private;
7962         int pipe = pipe_config->cpu_transcoder;
7963         struct dpll clock;
7964         u32 mdiv;
7965         int refclk = 100000;
7966
7967         /* In case of DSI, DPLL will not be used */
7968         if ((pipe_config->dpll_hw_state.dpll & DPLL_VCO_ENABLE) == 0)
7969                 return;
7970
7971         mutex_lock(&dev_priv->sb_lock);
7972         mdiv = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW3(pipe));
7973         mutex_unlock(&dev_priv->sb_lock);
7974
7975         clock.m1 = (mdiv >> DPIO_M1DIV_SHIFT) & 7;
7976         clock.m2 = mdiv & DPIO_M2DIV_MASK;
7977         clock.n = (mdiv >> DPIO_N_SHIFT) & 0xf;
7978         clock.p1 = (mdiv >> DPIO_P1_SHIFT) & 7;
7979         clock.p2 = (mdiv >> DPIO_P2_SHIFT) & 0x1f;
7980
7981         pipe_config->port_clock = vlv_calc_dpll_params(refclk, &clock);
7982 }
7983
7984 static void
7985 i9xx_get_initial_plane_config(struct intel_crtc *crtc,
7986                               struct intel_initial_plane_config *plane_config)
7987 {
7988         struct drm_device *dev = crtc->base.dev;
7989         struct drm_i915_private *dev_priv = dev->dev_private;
7990         u32 val, base, offset;
7991         int pipe = crtc->pipe, plane = crtc->plane;
7992         int fourcc, pixel_format;
7993         unsigned int aligned_height;
7994         struct drm_framebuffer *fb;
7995         struct intel_framebuffer *intel_fb;
7996
7997         val = I915_READ(DSPCNTR(plane));
7998         if (!(val & DISPLAY_PLANE_ENABLE))
7999                 return;
8000
8001         intel_fb = kzalloc(sizeof(*intel_fb), GFP_KERNEL);
8002         if (!intel_fb) {
8003                 DRM_DEBUG_KMS("failed to alloc fb\n");
8004                 return;
8005         }
8006
8007         fb = &intel_fb->base;
8008
8009         if (INTEL_INFO(dev)->gen >= 4) {
8010                 if (val & DISPPLANE_TILED) {
8011                         plane_config->tiling = I915_TILING_X;
8012                         fb->modifier[0] = I915_FORMAT_MOD_X_TILED;
8013                 }
8014         }
8015
8016         pixel_format = val & DISPPLANE_PIXFORMAT_MASK;
8017         fourcc = i9xx_format_to_fourcc(pixel_format);
8018         fb->pixel_format = fourcc;
8019         fb->bits_per_pixel = drm_format_plane_cpp(fourcc, 0) * 8;
8020
8021         if (INTEL_INFO(dev)->gen >= 4) {
8022                 if (plane_config->tiling)
8023                         offset = I915_READ(DSPTILEOFF(plane));
8024                 else
8025                         offset = I915_READ(DSPLINOFF(plane));
8026                 base = I915_READ(DSPSURF(plane)) & 0xfffff000;
8027         } else {
8028                 base = I915_READ(DSPADDR(plane));
8029         }
8030         plane_config->base = base;
8031
8032         val = I915_READ(PIPESRC(pipe));
8033         fb->width = ((val >> 16) & 0xfff) + 1;
8034         fb->height = ((val >> 0) & 0xfff) + 1;
8035
8036         val = I915_READ(DSPSTRIDE(pipe));
8037         fb->pitches[0] = val & 0xffffffc0;
8038
8039         aligned_height = intel_fb_align_height(dev, fb->height,
8040                                                fb->pixel_format,
8041                                                fb->modifier[0]);
8042
8043         plane_config->size = fb->pitches[0] * aligned_height;
8044
8045         DRM_DEBUG_KMS("pipe/plane %c/%d with fb: size=%dx%d@%d, offset=%x, pitch %d, size 0x%x\n",
8046                       pipe_name(pipe), plane, fb->width, fb->height,
8047                       fb->bits_per_pixel, base, fb->pitches[0],
8048                       plane_config->size);
8049
8050         plane_config->fb = intel_fb;
8051 }
8052
8053 static void chv_crtc_clock_get(struct intel_crtc *crtc,
8054                                struct intel_crtc_state *pipe_config)
8055 {
8056         struct drm_device *dev = crtc->base.dev;
8057         struct drm_i915_private *dev_priv = dev->dev_private;
8058         int pipe = pipe_config->cpu_transcoder;
8059         enum dpio_channel port = vlv_pipe_to_channel(pipe);
8060         struct dpll clock;
8061         u32 cmn_dw13, pll_dw0, pll_dw1, pll_dw2, pll_dw3;
8062         int refclk = 100000;
8063
8064         /* In case of DSI, DPLL will not be used */
8065         if ((pipe_config->dpll_hw_state.dpll & DPLL_VCO_ENABLE) == 0)
8066                 return;
8067
8068         mutex_lock(&dev_priv->sb_lock);
8069         cmn_dw13 = vlv_dpio_read(dev_priv, pipe, CHV_CMN_DW13(port));
8070         pll_dw0 = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW0(port));
8071         pll_dw1 = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW1(port));
8072         pll_dw2 = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW2(port));
8073         pll_dw3 = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW3(port));
8074         mutex_unlock(&dev_priv->sb_lock);
8075
8076         clock.m1 = (pll_dw1 & 0x7) == DPIO_CHV_M1_DIV_BY_2 ? 2 : 0;
8077         clock.m2 = (pll_dw0 & 0xff) << 22;
8078         if (pll_dw3 & DPIO_CHV_FRAC_DIV_EN)
8079                 clock.m2 |= pll_dw2 & 0x3fffff;
8080         clock.n = (pll_dw1 >> DPIO_CHV_N_DIV_SHIFT) & 0xf;
8081         clock.p1 = (cmn_dw13 >> DPIO_CHV_P1_DIV_SHIFT) & 0x7;
8082         clock.p2 = (cmn_dw13 >> DPIO_CHV_P2_DIV_SHIFT) & 0x1f;
8083
8084         pipe_config->port_clock = chv_calc_dpll_params(refclk, &clock);
8085 }
8086
8087 static bool i9xx_get_pipe_config(struct intel_crtc *crtc,
8088                                  struct intel_crtc_state *pipe_config)
8089 {
8090         struct drm_device *dev = crtc->base.dev;
8091         struct drm_i915_private *dev_priv = dev->dev_private;
8092         enum intel_display_power_domain power_domain;
8093         uint32_t tmp;
8094         bool ret;
8095
8096         power_domain = POWER_DOMAIN_PIPE(crtc->pipe);
8097         if (!intel_display_power_get_if_enabled(dev_priv, power_domain))
8098                 return false;
8099
8100         pipe_config->cpu_transcoder = (enum transcoder) crtc->pipe;
8101         pipe_config->shared_dpll = NULL;
8102
8103         ret = false;
8104
8105         tmp = I915_READ(PIPECONF(crtc->pipe));
8106         if (!(tmp & PIPECONF_ENABLE))
8107                 goto out;
8108
8109         if (IS_G4X(dev) || IS_VALLEYVIEW(dev) || IS_CHERRYVIEW(dev)) {
8110                 switch (tmp & PIPECONF_BPC_MASK) {
8111                 case PIPECONF_6BPC:
8112                         pipe_config->pipe_bpp = 18;
8113                         break;
8114                 case PIPECONF_8BPC:
8115                         pipe_config->pipe_bpp = 24;
8116                         break;
8117                 case PIPECONF_10BPC:
8118                         pipe_config->pipe_bpp = 30;
8119                         break;
8120                 default:
8121                         break;
8122                 }
8123         }
8124
8125         if ((IS_VALLEYVIEW(dev) || IS_CHERRYVIEW(dev)) &&
8126             (tmp & PIPECONF_COLOR_RANGE_SELECT))
8127                 pipe_config->limited_color_range = true;
8128
8129         if (INTEL_INFO(dev)->gen < 4)
8130                 pipe_config->double_wide = tmp & PIPECONF_DOUBLE_WIDE;
8131
8132         intel_get_pipe_timings(crtc, pipe_config);
8133         intel_get_pipe_src_size(crtc, pipe_config);
8134
8135         i9xx_get_pfit_config(crtc, pipe_config);
8136
8137         if (INTEL_INFO(dev)->gen >= 4) {
8138                 /* No way to read it out on pipes B and C */
8139                 if (IS_CHERRYVIEW(dev) && crtc->pipe != PIPE_A)
8140                         tmp = dev_priv->chv_dpll_md[crtc->pipe];
8141                 else
8142                         tmp = I915_READ(DPLL_MD(crtc->pipe));
8143                 pipe_config->pixel_multiplier =
8144                         ((tmp & DPLL_MD_UDI_MULTIPLIER_MASK)
8145                          >> DPLL_MD_UDI_MULTIPLIER_SHIFT) + 1;
8146                 pipe_config->dpll_hw_state.dpll_md = tmp;
8147         } else if (IS_I945G(dev) || IS_I945GM(dev) || IS_G33(dev)) {
8148                 tmp = I915_READ(DPLL(crtc->pipe));
8149                 pipe_config->pixel_multiplier =
8150                         ((tmp & SDVO_MULTIPLIER_MASK)
8151                          >> SDVO_MULTIPLIER_SHIFT_HIRES) + 1;
8152         } else {
8153                 /* Note that on i915G/GM the pixel multiplier is in the sdvo
8154                  * port and will be fixed up in the encoder->get_config
8155                  * function. */
8156                 pipe_config->pixel_multiplier = 1;
8157         }
8158         pipe_config->dpll_hw_state.dpll = I915_READ(DPLL(crtc->pipe));
8159         if (!IS_VALLEYVIEW(dev) && !IS_CHERRYVIEW(dev)) {
8160                 /*
8161                  * DPLL_DVO_2X_MODE must be enabled for both DPLLs
8162                  * on 830. Filter it out here so that we don't
8163                  * report errors due to that.
8164                  */
8165                 if (IS_I830(dev))
8166                         pipe_config->dpll_hw_state.dpll &= ~DPLL_DVO_2X_MODE;
8167
8168                 pipe_config->dpll_hw_state.fp0 = I915_READ(FP0(crtc->pipe));
8169                 pipe_config->dpll_hw_state.fp1 = I915_READ(FP1(crtc->pipe));
8170         } else {
8171                 /* Mask out read-only status bits. */
8172                 pipe_config->dpll_hw_state.dpll &= ~(DPLL_LOCK_VLV |
8173                                                      DPLL_PORTC_READY_MASK |
8174                                                      DPLL_PORTB_READY_MASK);
8175         }
8176
8177         if (IS_CHERRYVIEW(dev))
8178                 chv_crtc_clock_get(crtc, pipe_config);
8179         else if (IS_VALLEYVIEW(dev))
8180                 vlv_crtc_clock_get(crtc, pipe_config);
8181         else
8182                 i9xx_crtc_clock_get(crtc, pipe_config);
8183
8184         /*
8185          * Normally the dotclock is filled in by the encoder .get_config()
8186          * but in case the pipe is enabled w/o any ports we need a sane
8187          * default.
8188          */
8189         pipe_config->base.adjusted_mode.crtc_clock =
8190                 pipe_config->port_clock / pipe_config->pixel_multiplier;
8191
8192         ret = true;
8193
8194 out:
8195         intel_display_power_put(dev_priv, power_domain);
8196
8197         return ret;
8198 }
8199
8200 static void ironlake_init_pch_refclk(struct drm_device *dev)
8201 {
8202         struct drm_i915_private *dev_priv = dev->dev_private;
8203         struct intel_encoder *encoder;
8204         u32 val, final;
8205         bool has_lvds = false;
8206         bool has_cpu_edp = false;
8207         bool has_panel = false;
8208         bool has_ck505 = false;
8209         bool can_ssc = false;
8210
8211         /* We need to take the global config into account */
8212         for_each_intel_encoder(dev, encoder) {
8213                 switch (encoder->type) {
8214                 case INTEL_OUTPUT_LVDS:
8215                         has_panel = true;
8216                         has_lvds = true;
8217                         break;
8218                 case INTEL_OUTPUT_EDP:
8219                         has_panel = true;
8220                         if (enc_to_dig_port(&encoder->base)->port == PORT_A)
8221                                 has_cpu_edp = true;
8222                         break;
8223                 default:
8224                         break;
8225                 }
8226         }
8227
8228         if (HAS_PCH_IBX(dev)) {
8229                 has_ck505 = dev_priv->vbt.display_clock_mode;
8230                 can_ssc = has_ck505;
8231         } else {
8232                 has_ck505 = false;
8233                 can_ssc = true;
8234         }
8235
8236         DRM_DEBUG_KMS("has_panel %d has_lvds %d has_ck505 %d\n",
8237                       has_panel, has_lvds, has_ck505);
8238
8239         /* Ironlake: try to setup display ref clock before DPLL
8240          * enabling. This is only under driver's control after
8241          * PCH B stepping, previous chipset stepping should be
8242          * ignoring this setting.
8243          */
8244         val = I915_READ(PCH_DREF_CONTROL);
8245
8246         /* As we must carefully and slowly disable/enable each source in turn,
8247          * compute the final state we want first and check if we need to
8248          * make any changes at all.
8249          */
8250         final = val;
8251         final &= ~DREF_NONSPREAD_SOURCE_MASK;
8252         if (has_ck505)
8253                 final |= DREF_NONSPREAD_CK505_ENABLE;
8254         else
8255                 final |= DREF_NONSPREAD_SOURCE_ENABLE;
8256
8257         final &= ~DREF_SSC_SOURCE_MASK;
8258         final &= ~DREF_CPU_SOURCE_OUTPUT_MASK;
8259         final &= ~DREF_SSC1_ENABLE;
8260
8261         if (has_panel) {
8262                 final |= DREF_SSC_SOURCE_ENABLE;
8263
8264                 if (intel_panel_use_ssc(dev_priv) && can_ssc)
8265                         final |= DREF_SSC1_ENABLE;
8266
8267                 if (has_cpu_edp) {
8268                         if (intel_panel_use_ssc(dev_priv) && can_ssc)
8269                                 final |= DREF_CPU_SOURCE_OUTPUT_DOWNSPREAD;
8270                         else
8271                                 final |= DREF_CPU_SOURCE_OUTPUT_NONSPREAD;
8272                 } else
8273                         final |= DREF_CPU_SOURCE_OUTPUT_DISABLE;
8274         } else {
8275                 final |= DREF_SSC_SOURCE_DISABLE;
8276                 final |= DREF_CPU_SOURCE_OUTPUT_DISABLE;
8277         }
8278
8279         if (final == val)
8280                 return;
8281
8282         /* Always enable nonspread source */
8283         val &= ~DREF_NONSPREAD_SOURCE_MASK;
8284
8285         if (has_ck505)
8286                 val |= DREF_NONSPREAD_CK505_ENABLE;
8287         else
8288                 val |= DREF_NONSPREAD_SOURCE_ENABLE;
8289
8290         if (has_panel) {
8291                 val &= ~DREF_SSC_SOURCE_MASK;
8292                 val |= DREF_SSC_SOURCE_ENABLE;
8293
8294                 /* SSC must be turned on before enabling the CPU output  */
8295                 if (intel_panel_use_ssc(dev_priv) && can_ssc) {
8296                         DRM_DEBUG_KMS("Using SSC on panel\n");
8297                         val |= DREF_SSC1_ENABLE;
8298                 } else
8299                         val &= ~DREF_SSC1_ENABLE;
8300
8301                 /* Get SSC going before enabling the outputs */
8302                 I915_WRITE(PCH_DREF_CONTROL, val);
8303                 POSTING_READ(PCH_DREF_CONTROL);
8304                 udelay(200);
8305
8306                 val &= ~DREF_CPU_SOURCE_OUTPUT_MASK;
8307
8308                 /* Enable CPU source on CPU attached eDP */
8309                 if (has_cpu_edp) {
8310                         if (intel_panel_use_ssc(dev_priv) && can_ssc) {
8311                                 DRM_DEBUG_KMS("Using SSC on eDP\n");
8312                                 val |= DREF_CPU_SOURCE_OUTPUT_DOWNSPREAD;
8313                         } else
8314                                 val |= DREF_CPU_SOURCE_OUTPUT_NONSPREAD;
8315                 } else
8316                         val |= DREF_CPU_SOURCE_OUTPUT_DISABLE;
8317
8318                 I915_WRITE(PCH_DREF_CONTROL, val);
8319                 POSTING_READ(PCH_DREF_CONTROL);
8320                 udelay(200);
8321         } else {
8322                 DRM_DEBUG_KMS("Disabling SSC entirely\n");
8323
8324                 val &= ~DREF_CPU_SOURCE_OUTPUT_MASK;
8325
8326                 /* Turn off CPU output */
8327                 val |= DREF_CPU_SOURCE_OUTPUT_DISABLE;
8328
8329                 I915_WRITE(PCH_DREF_CONTROL, val);
8330                 POSTING_READ(PCH_DREF_CONTROL);
8331                 udelay(200);
8332
8333                 /* Turn off the SSC source */
8334                 val &= ~DREF_SSC_SOURCE_MASK;
8335                 val |= DREF_SSC_SOURCE_DISABLE;
8336
8337                 /* Turn off SSC1 */
8338                 val &= ~DREF_SSC1_ENABLE;
8339
8340                 I915_WRITE(PCH_DREF_CONTROL, val);
8341                 POSTING_READ(PCH_DREF_CONTROL);
8342                 udelay(200);
8343         }
8344
8345         BUG_ON(val != final);
8346 }
8347
8348 static void lpt_reset_fdi_mphy(struct drm_i915_private *dev_priv)
8349 {
8350         uint32_t tmp;
8351
8352         tmp = I915_READ(SOUTH_CHICKEN2);
8353         tmp |= FDI_MPHY_IOSFSB_RESET_CTL;
8354         I915_WRITE(SOUTH_CHICKEN2, tmp);
8355
8356         if (wait_for_atomic_us(I915_READ(SOUTH_CHICKEN2) &
8357                                FDI_MPHY_IOSFSB_RESET_STATUS, 100))
8358                 DRM_ERROR("FDI mPHY reset assert timeout\n");
8359
8360         tmp = I915_READ(SOUTH_CHICKEN2);
8361         tmp &= ~FDI_MPHY_IOSFSB_RESET_CTL;
8362         I915_WRITE(SOUTH_CHICKEN2, tmp);
8363
8364         if (wait_for_atomic_us((I915_READ(SOUTH_CHICKEN2) &
8365                                 FDI_MPHY_IOSFSB_RESET_STATUS) == 0, 100))
8366                 DRM_ERROR("FDI mPHY reset de-assert timeout\n");
8367 }
8368
8369 /* WaMPhyProgramming:hsw */
8370 static void lpt_program_fdi_mphy(struct drm_i915_private *dev_priv)
8371 {
8372         uint32_t tmp;
8373
8374         tmp = intel_sbi_read(dev_priv, 0x8008, SBI_MPHY);
8375         tmp &= ~(0xFF << 24);
8376         tmp |= (0x12 << 24);
8377         intel_sbi_write(dev_priv, 0x8008, tmp, SBI_MPHY);
8378
8379         tmp = intel_sbi_read(dev_priv, 0x2008, SBI_MPHY);
8380         tmp |= (1 << 11);
8381         intel_sbi_write(dev_priv, 0x2008, tmp, SBI_MPHY);
8382
8383         tmp = intel_sbi_read(dev_priv, 0x2108, SBI_MPHY);
8384         tmp |= (1 << 11);
8385         intel_sbi_write(dev_priv, 0x2108, tmp, SBI_MPHY);
8386
8387         tmp = intel_sbi_read(dev_priv, 0x206C, SBI_MPHY);
8388         tmp |= (1 << 24) | (1 << 21) | (1 << 18);
8389         intel_sbi_write(dev_priv, 0x206C, tmp, SBI_MPHY);
8390
8391         tmp = intel_sbi_read(dev_priv, 0x216C, SBI_MPHY);
8392         tmp |= (1 << 24) | (1 << 21) | (1 << 18);
8393         intel_sbi_write(dev_priv, 0x216C, tmp, SBI_MPHY);
8394
8395         tmp = intel_sbi_read(dev_priv, 0x2080, SBI_MPHY);
8396         tmp &= ~(7 << 13);
8397         tmp |= (5 << 13);
8398         intel_sbi_write(dev_priv, 0x2080, tmp, SBI_MPHY);
8399
8400         tmp = intel_sbi_read(dev_priv, 0x2180, SBI_MPHY);
8401         tmp &= ~(7 << 13);
8402         tmp |= (5 << 13);
8403         intel_sbi_write(dev_priv, 0x2180, tmp, SBI_MPHY);
8404
8405         tmp = intel_sbi_read(dev_priv, 0x208C, SBI_MPHY);
8406         tmp &= ~0xFF;
8407         tmp |= 0x1C;
8408         intel_sbi_write(dev_priv, 0x208C, tmp, SBI_MPHY);
8409
8410         tmp = intel_sbi_read(dev_priv, 0x218C, SBI_MPHY);
8411         tmp &= ~0xFF;
8412         tmp |= 0x1C;
8413         intel_sbi_write(dev_priv, 0x218C, tmp, SBI_MPHY);
8414
8415         tmp = intel_sbi_read(dev_priv, 0x2098, SBI_MPHY);
8416         tmp &= ~(0xFF << 16);
8417         tmp |= (0x1C << 16);
8418         intel_sbi_write(dev_priv, 0x2098, tmp, SBI_MPHY);
8419
8420         tmp = intel_sbi_read(dev_priv, 0x2198, SBI_MPHY);
8421         tmp &= ~(0xFF << 16);
8422         tmp |= (0x1C << 16);
8423         intel_sbi_write(dev_priv, 0x2198, tmp, SBI_MPHY);
8424
8425         tmp = intel_sbi_read(dev_priv, 0x20C4, SBI_MPHY);
8426         tmp |= (1 << 27);
8427         intel_sbi_write(dev_priv, 0x20C4, tmp, SBI_MPHY);
8428
8429         tmp = intel_sbi_read(dev_priv, 0x21C4, SBI_MPHY);
8430         tmp |= (1 << 27);
8431         intel_sbi_write(dev_priv, 0x21C4, tmp, SBI_MPHY);
8432
8433         tmp = intel_sbi_read(dev_priv, 0x20EC, SBI_MPHY);
8434         tmp &= ~(0xF << 28);
8435         tmp |= (4 << 28);
8436         intel_sbi_write(dev_priv, 0x20EC, tmp, SBI_MPHY);
8437
8438         tmp = intel_sbi_read(dev_priv, 0x21EC, SBI_MPHY);
8439         tmp &= ~(0xF << 28);
8440         tmp |= (4 << 28);
8441         intel_sbi_write(dev_priv, 0x21EC, tmp, SBI_MPHY);
8442 }
8443
8444 /* Implements 3 different sequences from BSpec chapter "Display iCLK
8445  * Programming" based on the parameters passed:
8446  * - Sequence to enable CLKOUT_DP
8447  * - Sequence to enable CLKOUT_DP without spread
8448  * - Sequence to enable CLKOUT_DP for FDI usage and configure PCH FDI I/O
8449  */
8450 static void lpt_enable_clkout_dp(struct drm_device *dev, bool with_spread,
8451                                  bool with_fdi)
8452 {
8453         struct drm_i915_private *dev_priv = dev->dev_private;
8454         uint32_t reg, tmp;
8455
8456         if (WARN(with_fdi && !with_spread, "FDI requires downspread\n"))
8457                 with_spread = true;
8458         if (WARN(HAS_PCH_LPT_LP(dev) && with_fdi, "LP PCH doesn't have FDI\n"))
8459                 with_fdi = false;
8460
8461         mutex_lock(&dev_priv->sb_lock);
8462
8463         tmp = intel_sbi_read(dev_priv, SBI_SSCCTL, SBI_ICLK);
8464         tmp &= ~SBI_SSCCTL_DISABLE;
8465         tmp |= SBI_SSCCTL_PATHALT;
8466         intel_sbi_write(dev_priv, SBI_SSCCTL, tmp, SBI_ICLK);
8467
8468         udelay(24);
8469
8470         if (with_spread) {
8471                 tmp = intel_sbi_read(dev_priv, SBI_SSCCTL, SBI_ICLK);
8472                 tmp &= ~SBI_SSCCTL_PATHALT;
8473                 intel_sbi_write(dev_priv, SBI_SSCCTL, tmp, SBI_ICLK);
8474
8475                 if (with_fdi) {
8476                         lpt_reset_fdi_mphy(dev_priv);
8477                         lpt_program_fdi_mphy(dev_priv);
8478                 }
8479         }
8480
8481         reg = HAS_PCH_LPT_LP(dev) ? SBI_GEN0 : SBI_DBUFF0;
8482         tmp = intel_sbi_read(dev_priv, reg, SBI_ICLK);
8483         tmp |= SBI_GEN0_CFG_BUFFENABLE_DISABLE;
8484         intel_sbi_write(dev_priv, reg, tmp, SBI_ICLK);
8485
8486         mutex_unlock(&dev_priv->sb_lock);
8487 }
8488
8489 /* Sequence to disable CLKOUT_DP */
8490 static void lpt_disable_clkout_dp(struct drm_device *dev)
8491 {
8492         struct drm_i915_private *dev_priv = dev->dev_private;
8493         uint32_t reg, tmp;
8494
8495         mutex_lock(&dev_priv->sb_lock);
8496
8497         reg = HAS_PCH_LPT_LP(dev) ? SBI_GEN0 : SBI_DBUFF0;
8498         tmp = intel_sbi_read(dev_priv, reg, SBI_ICLK);
8499         tmp &= ~SBI_GEN0_CFG_BUFFENABLE_DISABLE;
8500         intel_sbi_write(dev_priv, reg, tmp, SBI_ICLK);
8501
8502         tmp = intel_sbi_read(dev_priv, SBI_SSCCTL, SBI_ICLK);
8503         if (!(tmp & SBI_SSCCTL_DISABLE)) {
8504                 if (!(tmp & SBI_SSCCTL_PATHALT)) {
8505                         tmp |= SBI_SSCCTL_PATHALT;
8506                         intel_sbi_write(dev_priv, SBI_SSCCTL, tmp, SBI_ICLK);
8507                         udelay(32);
8508                 }
8509                 tmp |= SBI_SSCCTL_DISABLE;
8510                 intel_sbi_write(dev_priv, SBI_SSCCTL, tmp, SBI_ICLK);
8511         }
8512
8513         mutex_unlock(&dev_priv->sb_lock);
8514 }
8515
8516 #define BEND_IDX(steps) ((50 + (steps)) / 5)
8517
8518 static const uint16_t sscdivintphase[] = {
8519         [BEND_IDX( 50)] = 0x3B23,
8520         [BEND_IDX( 45)] = 0x3B23,
8521         [BEND_IDX( 40)] = 0x3C23,
8522         [BEND_IDX( 35)] = 0x3C23,
8523         [BEND_IDX( 30)] = 0x3D23,
8524         [BEND_IDX( 25)] = 0x3D23,
8525         [BEND_IDX( 20)] = 0x3E23,
8526         [BEND_IDX( 15)] = 0x3E23,
8527         [BEND_IDX( 10)] = 0x3F23,
8528         [BEND_IDX(  5)] = 0x3F23,
8529         [BEND_IDX(  0)] = 0x0025,
8530         [BEND_IDX( -5)] = 0x0025,
8531         [BEND_IDX(-10)] = 0x0125,
8532         [BEND_IDX(-15)] = 0x0125,
8533         [BEND_IDX(-20)] = 0x0225,
8534         [BEND_IDX(-25)] = 0x0225,
8535         [BEND_IDX(-30)] = 0x0325,
8536         [BEND_IDX(-35)] = 0x0325,
8537         [BEND_IDX(-40)] = 0x0425,
8538         [BEND_IDX(-45)] = 0x0425,
8539         [BEND_IDX(-50)] = 0x0525,
8540 };
8541
8542 /*
8543  * Bend CLKOUT_DP
8544  * steps -50 to 50 inclusive, in steps of 5
8545  * < 0 slow down the clock, > 0 speed up the clock, 0 == no bend (135MHz)
8546  * change in clock period = -(steps / 10) * 5.787 ps
8547  */
8548 static void lpt_bend_clkout_dp(struct drm_i915_private *dev_priv, int steps)
8549 {
8550         uint32_t tmp;
8551         int idx = BEND_IDX(steps);
8552
8553         if (WARN_ON(steps % 5 != 0))
8554                 return;
8555
8556         if (WARN_ON(idx >= ARRAY_SIZE(sscdivintphase)))
8557                 return;
8558
8559         mutex_lock(&dev_priv->sb_lock);
8560
8561         if (steps % 10 != 0)
8562                 tmp = 0xAAAAAAAB;
8563         else
8564                 tmp = 0x00000000;
8565         intel_sbi_write(dev_priv, SBI_SSCDITHPHASE, tmp, SBI_ICLK);
8566
8567         tmp = intel_sbi_read(dev_priv, SBI_SSCDIVINTPHASE, SBI_ICLK);
8568         tmp &= 0xffff0000;
8569         tmp |= sscdivintphase[idx];
8570         intel_sbi_write(dev_priv, SBI_SSCDIVINTPHASE, tmp, SBI_ICLK);
8571
8572         mutex_unlock(&dev_priv->sb_lock);
8573 }
8574
8575 #undef BEND_IDX
8576
8577 static void lpt_init_pch_refclk(struct drm_device *dev)
8578 {
8579         struct intel_encoder *encoder;
8580         bool has_vga = false;
8581
8582         for_each_intel_encoder(dev, encoder) {
8583                 switch (encoder->type) {
8584                 case INTEL_OUTPUT_ANALOG:
8585                         has_vga = true;
8586                         break;
8587                 default:
8588                         break;
8589                 }
8590         }
8591
8592         if (has_vga) {
8593                 lpt_bend_clkout_dp(to_i915(dev), 0);
8594                 lpt_enable_clkout_dp(dev, true, true);
8595         } else {
8596                 lpt_disable_clkout_dp(dev);
8597         }
8598 }
8599
8600 /*
8601  * Initialize reference clocks when the driver loads
8602  */
8603 void intel_init_pch_refclk(struct drm_device *dev)
8604 {
8605         if (HAS_PCH_IBX(dev) || HAS_PCH_CPT(dev))
8606                 ironlake_init_pch_refclk(dev);
8607         else if (HAS_PCH_LPT(dev))
8608                 lpt_init_pch_refclk(dev);
8609 }
8610
8611 static void ironlake_set_pipeconf(struct drm_crtc *crtc)
8612 {
8613         struct drm_i915_private *dev_priv = crtc->dev->dev_private;
8614         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
8615         int pipe = intel_crtc->pipe;
8616         uint32_t val;
8617
8618         val = 0;
8619
8620         switch (intel_crtc->config->pipe_bpp) {
8621         case 18:
8622                 val |= PIPECONF_6BPC;
8623                 break;
8624         case 24:
8625                 val |= PIPECONF_8BPC;
8626                 break;
8627         case 30:
8628                 val |= PIPECONF_10BPC;
8629                 break;
8630         case 36:
8631                 val |= PIPECONF_12BPC;
8632                 break;
8633         default:
8634                 /* Case prevented by intel_choose_pipe_bpp_dither. */
8635                 BUG();
8636         }
8637
8638         if (intel_crtc->config->dither)
8639                 val |= (PIPECONF_DITHER_EN | PIPECONF_DITHER_TYPE_SP);
8640
8641         if (intel_crtc->config->base.adjusted_mode.flags & DRM_MODE_FLAG_INTERLACE)
8642                 val |= PIPECONF_INTERLACED_ILK;
8643         else
8644                 val |= PIPECONF_PROGRESSIVE;
8645
8646         if (intel_crtc->config->limited_color_range)
8647                 val |= PIPECONF_COLOR_RANGE_SELECT;
8648
8649         I915_WRITE(PIPECONF(pipe), val);
8650         POSTING_READ(PIPECONF(pipe));
8651 }
8652
8653 static void haswell_set_pipeconf(struct drm_crtc *crtc)
8654 {
8655         struct drm_i915_private *dev_priv = crtc->dev->dev_private;
8656         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
8657         enum transcoder cpu_transcoder = intel_crtc->config->cpu_transcoder;
8658         u32 val = 0;
8659
8660         if (IS_HASWELL(dev_priv) && intel_crtc->config->dither)
8661                 val |= (PIPECONF_DITHER_EN | PIPECONF_DITHER_TYPE_SP);
8662
8663         if (intel_crtc->config->base.adjusted_mode.flags & DRM_MODE_FLAG_INTERLACE)
8664                 val |= PIPECONF_INTERLACED_ILK;
8665         else
8666                 val |= PIPECONF_PROGRESSIVE;
8667
8668         I915_WRITE(PIPECONF(cpu_transcoder), val);
8669         POSTING_READ(PIPECONF(cpu_transcoder));
8670 }
8671
8672 static void haswell_set_pipemisc(struct drm_crtc *crtc)
8673 {
8674         struct drm_i915_private *dev_priv = crtc->dev->dev_private;
8675         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
8676
8677         if (IS_BROADWELL(dev_priv) || INTEL_INFO(dev_priv)->gen >= 9) {
8678                 u32 val = 0;
8679
8680                 switch (intel_crtc->config->pipe_bpp) {
8681                 case 18:
8682                         val |= PIPEMISC_DITHER_6_BPC;
8683                         break;
8684                 case 24:
8685                         val |= PIPEMISC_DITHER_8_BPC;
8686                         break;
8687                 case 30:
8688                         val |= PIPEMISC_DITHER_10_BPC;
8689                         break;
8690                 case 36:
8691                         val |= PIPEMISC_DITHER_12_BPC;
8692                         break;
8693                 default:
8694                         /* Case prevented by pipe_config_set_bpp. */
8695                         BUG();
8696                 }
8697
8698                 if (intel_crtc->config->dither)
8699                         val |= PIPEMISC_DITHER_ENABLE | PIPEMISC_DITHER_TYPE_SP;
8700
8701                 I915_WRITE(PIPEMISC(intel_crtc->pipe), val);
8702         }
8703 }
8704
8705 int ironlake_get_lanes_required(int target_clock, int link_bw, int bpp)
8706 {
8707         /*
8708          * Account for spread spectrum to avoid
8709          * oversubscribing the link. Max center spread
8710          * is 2.5%; use 5% for safety's sake.
8711          */
8712         u32 bps = target_clock * bpp * 21 / 20;
8713         return DIV_ROUND_UP(bps, link_bw * 8);
8714 }
8715
8716 static bool ironlake_needs_fb_cb_tune(struct dpll *dpll, int factor)
8717 {
8718         return i9xx_dpll_compute_m(dpll) < factor * dpll->n;
8719 }
8720
8721 static void ironlake_compute_dpll(struct intel_crtc *intel_crtc,
8722                                   struct intel_crtc_state *crtc_state,
8723                                   struct dpll *reduced_clock)
8724 {
8725         struct drm_crtc *crtc = &intel_crtc->base;
8726         struct drm_device *dev = crtc->dev;
8727         struct drm_i915_private *dev_priv = dev->dev_private;
8728         struct drm_atomic_state *state = crtc_state->base.state;
8729         struct drm_connector *connector;
8730         struct drm_connector_state *connector_state;
8731         struct intel_encoder *encoder;
8732         u32 dpll, fp, fp2;
8733         int factor, i;
8734         bool is_lvds = false, is_sdvo = false;
8735
8736         for_each_connector_in_state(state, connector, connector_state, i) {
8737                 if (connector_state->crtc != crtc_state->base.crtc)
8738                         continue;
8739
8740                 encoder = to_intel_encoder(connector_state->best_encoder);
8741
8742                 switch (encoder->type) {
8743                 case INTEL_OUTPUT_LVDS:
8744                         is_lvds = true;
8745                         break;
8746                 case INTEL_OUTPUT_SDVO:
8747                 case INTEL_OUTPUT_HDMI:
8748                         is_sdvo = true;
8749                         break;
8750                 default:
8751                         break;
8752                 }
8753         }
8754
8755         /* Enable autotuning of the PLL clock (if permissible) */
8756         factor = 21;
8757         if (is_lvds) {
8758                 if ((intel_panel_use_ssc(dev_priv) &&
8759                      dev_priv->vbt.lvds_ssc_freq == 100000) ||
8760                     (HAS_PCH_IBX(dev) && intel_is_dual_link_lvds(dev)))
8761                         factor = 25;
8762         } else if (crtc_state->sdvo_tv_clock)
8763                 factor = 20;
8764
8765         fp = i9xx_dpll_compute_fp(&crtc_state->dpll);
8766
8767         if (ironlake_needs_fb_cb_tune(&crtc_state->dpll, factor))
8768                 fp |= FP_CB_TUNE;
8769
8770         if (reduced_clock) {
8771                 fp2 = i9xx_dpll_compute_fp(reduced_clock);
8772
8773                 if (reduced_clock->m < factor * reduced_clock->n)
8774                         fp2 |= FP_CB_TUNE;
8775         } else {
8776                 fp2 = fp;
8777         }
8778
8779         dpll = 0;
8780
8781         if (is_lvds)
8782                 dpll |= DPLLB_MODE_LVDS;
8783         else
8784                 dpll |= DPLLB_MODE_DAC_SERIAL;
8785
8786         dpll |= (crtc_state->pixel_multiplier - 1)
8787                 << PLL_REF_SDVO_HDMI_MULTIPLIER_SHIFT;
8788
8789         if (is_sdvo)
8790                 dpll |= DPLL_SDVO_HIGH_SPEED;
8791         if (crtc_state->has_dp_encoder)
8792                 dpll |= DPLL_SDVO_HIGH_SPEED;
8793
8794         /* compute bitmask from p1 value */
8795         dpll |= (1 << (crtc_state->dpll.p1 - 1)) << DPLL_FPA01_P1_POST_DIV_SHIFT;
8796         /* also FPA1 */
8797         dpll |= (1 << (crtc_state->dpll.p1 - 1)) << DPLL_FPA1_P1_POST_DIV_SHIFT;
8798
8799         switch (crtc_state->dpll.p2) {
8800         case 5:
8801                 dpll |= DPLL_DAC_SERIAL_P2_CLOCK_DIV_5;
8802                 break;
8803         case 7:
8804                 dpll |= DPLLB_LVDS_P2_CLOCK_DIV_7;
8805                 break;
8806         case 10:
8807                 dpll |= DPLL_DAC_SERIAL_P2_CLOCK_DIV_10;
8808                 break;
8809         case 14:
8810                 dpll |= DPLLB_LVDS_P2_CLOCK_DIV_14;
8811                 break;
8812         }
8813
8814         if (is_lvds && intel_panel_use_ssc(dev_priv))
8815                 dpll |= PLLB_REF_INPUT_SPREADSPECTRUMIN;
8816         else
8817                 dpll |= PLL_REF_INPUT_DREFCLK;
8818
8819         dpll |= DPLL_VCO_ENABLE;
8820
8821         crtc_state->dpll_hw_state.dpll = dpll;
8822         crtc_state->dpll_hw_state.fp0 = fp;
8823         crtc_state->dpll_hw_state.fp1 = fp2;
8824 }
8825
8826 static int ironlake_crtc_compute_clock(struct intel_crtc *crtc,
8827                                        struct intel_crtc_state *crtc_state)
8828 {
8829         struct drm_device *dev = crtc->base.dev;
8830         struct drm_i915_private *dev_priv = dev->dev_private;
8831         struct dpll reduced_clock;
8832         bool has_reduced_clock = false;
8833         struct intel_shared_dpll *pll;
8834         const struct intel_limit *limit;
8835         int refclk = 120000;
8836
8837         memset(&crtc_state->dpll_hw_state, 0,
8838                sizeof(crtc_state->dpll_hw_state));
8839
8840         crtc->lowfreq_avail = false;
8841
8842         /* CPU eDP is the only output that doesn't need a PCH PLL of its own. */
8843         if (!crtc_state->has_pch_encoder)
8844                 return 0;
8845
8846         if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_LVDS)) {
8847                 if (intel_panel_use_ssc(dev_priv)) {
8848                         DRM_DEBUG_KMS("using SSC reference clock of %d kHz\n",
8849                                       dev_priv->vbt.lvds_ssc_freq);
8850                         refclk = dev_priv->vbt.lvds_ssc_freq;
8851                 }
8852
8853                 if (intel_is_dual_link_lvds(dev)) {
8854                         if (refclk == 100000)
8855                                 limit = &intel_limits_ironlake_dual_lvds_100m;
8856                         else
8857                                 limit = &intel_limits_ironlake_dual_lvds;
8858                 } else {
8859                         if (refclk == 100000)
8860                                 limit = &intel_limits_ironlake_single_lvds_100m;
8861                         else
8862                                 limit = &intel_limits_ironlake_single_lvds;
8863                 }
8864         } else {
8865                 limit = &intel_limits_ironlake_dac;
8866         }
8867
8868         if (!crtc_state->clock_set &&
8869             !g4x_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
8870                                 refclk, NULL, &crtc_state->dpll)) {
8871                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
8872                 return -EINVAL;
8873         }
8874
8875         ironlake_compute_dpll(crtc, crtc_state,
8876                               has_reduced_clock ? &reduced_clock : NULL);
8877
8878         pll = intel_get_shared_dpll(crtc, crtc_state, NULL);
8879         if (pll == NULL) {
8880                 DRM_DEBUG_DRIVER("failed to find PLL for pipe %c\n",
8881                                  pipe_name(crtc->pipe));
8882                 return -EINVAL;
8883         }
8884
8885         if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_LVDS) &&
8886             has_reduced_clock)
8887                 crtc->lowfreq_avail = true;
8888
8889         return 0;
8890 }
8891
8892 static void intel_pch_transcoder_get_m_n(struct intel_crtc *crtc,
8893                                          struct intel_link_m_n *m_n)
8894 {
8895         struct drm_device *dev = crtc->base.dev;
8896         struct drm_i915_private *dev_priv = dev->dev_private;
8897         enum pipe pipe = crtc->pipe;
8898
8899         m_n->link_m = I915_READ(PCH_TRANS_LINK_M1(pipe));
8900         m_n->link_n = I915_READ(PCH_TRANS_LINK_N1(pipe));
8901         m_n->gmch_m = I915_READ(PCH_TRANS_DATA_M1(pipe))
8902                 & ~TU_SIZE_MASK;
8903         m_n->gmch_n = I915_READ(PCH_TRANS_DATA_N1(pipe));
8904         m_n->tu = ((I915_READ(PCH_TRANS_DATA_M1(pipe))
8905                     & TU_SIZE_MASK) >> TU_SIZE_SHIFT) + 1;
8906 }
8907
8908 static void intel_cpu_transcoder_get_m_n(struct intel_crtc *crtc,
8909                                          enum transcoder transcoder,
8910                                          struct intel_link_m_n *m_n,
8911                                          struct intel_link_m_n *m2_n2)
8912 {
8913         struct drm_device *dev = crtc->base.dev;
8914         struct drm_i915_private *dev_priv = dev->dev_private;
8915         enum pipe pipe = crtc->pipe;
8916
8917         if (INTEL_INFO(dev)->gen >= 5) {
8918                 m_n->link_m = I915_READ(PIPE_LINK_M1(transcoder));
8919                 m_n->link_n = I915_READ(PIPE_LINK_N1(transcoder));
8920                 m_n->gmch_m = I915_READ(PIPE_DATA_M1(transcoder))
8921                         & ~TU_SIZE_MASK;
8922                 m_n->gmch_n = I915_READ(PIPE_DATA_N1(transcoder));
8923                 m_n->tu = ((I915_READ(PIPE_DATA_M1(transcoder))
8924                             & TU_SIZE_MASK) >> TU_SIZE_SHIFT) + 1;
8925                 /* Read M2_N2 registers only for gen < 8 (M2_N2 available for
8926                  * gen < 8) and if DRRS is supported (to make sure the
8927                  * registers are not unnecessarily read).
8928                  */
8929                 if (m2_n2 && INTEL_INFO(dev)->gen < 8 &&
8930                         crtc->config->has_drrs) {
8931                         m2_n2->link_m = I915_READ(PIPE_LINK_M2(transcoder));
8932                         m2_n2->link_n = I915_READ(PIPE_LINK_N2(transcoder));
8933                         m2_n2->gmch_m = I915_READ(PIPE_DATA_M2(transcoder))
8934                                         & ~TU_SIZE_MASK;
8935                         m2_n2->gmch_n = I915_READ(PIPE_DATA_N2(transcoder));
8936                         m2_n2->tu = ((I915_READ(PIPE_DATA_M2(transcoder))
8937                                         & TU_SIZE_MASK) >> TU_SIZE_SHIFT) + 1;
8938                 }
8939         } else {
8940                 m_n->link_m = I915_READ(PIPE_LINK_M_G4X(pipe));
8941                 m_n->link_n = I915_READ(PIPE_LINK_N_G4X(pipe));
8942                 m_n->gmch_m = I915_READ(PIPE_DATA_M_G4X(pipe))
8943                         & ~TU_SIZE_MASK;
8944                 m_n->gmch_n = I915_READ(PIPE_DATA_N_G4X(pipe));
8945                 m_n->tu = ((I915_READ(PIPE_DATA_M_G4X(pipe))
8946                             & TU_SIZE_MASK) >> TU_SIZE_SHIFT) + 1;
8947         }
8948 }
8949
8950 void intel_dp_get_m_n(struct intel_crtc *crtc,
8951                       struct intel_crtc_state *pipe_config)
8952 {
8953         if (pipe_config->has_pch_encoder)
8954                 intel_pch_transcoder_get_m_n(crtc, &pipe_config->dp_m_n);
8955         else
8956                 intel_cpu_transcoder_get_m_n(crtc, pipe_config->cpu_transcoder,
8957                                              &pipe_config->dp_m_n,
8958                                              &pipe_config->dp_m2_n2);
8959 }
8960
8961 static void ironlake_get_fdi_m_n_config(struct intel_crtc *crtc,
8962                                         struct intel_crtc_state *pipe_config)
8963 {
8964         intel_cpu_transcoder_get_m_n(crtc, pipe_config->cpu_transcoder,
8965                                      &pipe_config->fdi_m_n, NULL);
8966 }
8967
8968 static void skylake_get_pfit_config(struct intel_crtc *crtc,
8969                                     struct intel_crtc_state *pipe_config)
8970 {
8971         struct drm_device *dev = crtc->base.dev;
8972         struct drm_i915_private *dev_priv = dev->dev_private;
8973         struct intel_crtc_scaler_state *scaler_state = &pipe_config->scaler_state;
8974         uint32_t ps_ctrl = 0;
8975         int id = -1;
8976         int i;
8977
8978         /* find scaler attached to this pipe */
8979         for (i = 0; i < crtc->num_scalers; i++) {
8980                 ps_ctrl = I915_READ(SKL_PS_CTRL(crtc->pipe, i));
8981                 if (ps_ctrl & PS_SCALER_EN && !(ps_ctrl & PS_PLANE_SEL_MASK)) {
8982                         id = i;
8983                         pipe_config->pch_pfit.enabled = true;
8984                         pipe_config->pch_pfit.pos = I915_READ(SKL_PS_WIN_POS(crtc->pipe, i));
8985                         pipe_config->pch_pfit.size = I915_READ(SKL_PS_WIN_SZ(crtc->pipe, i));
8986                         break;
8987                 }
8988         }
8989
8990         scaler_state->scaler_id = id;
8991         if (id >= 0) {
8992                 scaler_state->scaler_users |= (1 << SKL_CRTC_INDEX);
8993         } else {
8994                 scaler_state->scaler_users &= ~(1 << SKL_CRTC_INDEX);
8995         }
8996 }
8997
8998 static void
8999 skylake_get_initial_plane_config(struct intel_crtc *crtc,
9000                                  struct intel_initial_plane_config *plane_config)
9001 {
9002         struct drm_device *dev = crtc->base.dev;
9003         struct drm_i915_private *dev_priv = dev->dev_private;
9004         u32 val, base, offset, stride_mult, tiling;
9005         int pipe = crtc->pipe;
9006         int fourcc, pixel_format;
9007         unsigned int aligned_height;
9008         struct drm_framebuffer *fb;
9009         struct intel_framebuffer *intel_fb;
9010
9011         intel_fb = kzalloc(sizeof(*intel_fb), GFP_KERNEL);
9012         if (!intel_fb) {
9013                 DRM_DEBUG_KMS("failed to alloc fb\n");
9014                 return;
9015         }
9016
9017         fb = &intel_fb->base;
9018
9019         val = I915_READ(PLANE_CTL(pipe, 0));
9020         if (!(val & PLANE_CTL_ENABLE))
9021                 goto error;
9022
9023         pixel_format = val & PLANE_CTL_FORMAT_MASK;
9024         fourcc = skl_format_to_fourcc(pixel_format,
9025                                       val & PLANE_CTL_ORDER_RGBX,
9026                                       val & PLANE_CTL_ALPHA_MASK);
9027         fb->pixel_format = fourcc;
9028         fb->bits_per_pixel = drm_format_plane_cpp(fourcc, 0) * 8;
9029
9030         tiling = val & PLANE_CTL_TILED_MASK;
9031         switch (tiling) {
9032         case PLANE_CTL_TILED_LINEAR:
9033                 fb->modifier[0] = DRM_FORMAT_MOD_NONE;
9034                 break;
9035         case PLANE_CTL_TILED_X:
9036                 plane_config->tiling = I915_TILING_X;
9037                 fb->modifier[0] = I915_FORMAT_MOD_X_TILED;
9038                 break;
9039         case PLANE_CTL_TILED_Y:
9040                 fb->modifier[0] = I915_FORMAT_MOD_Y_TILED;
9041                 break;
9042         case PLANE_CTL_TILED_YF:
9043                 fb->modifier[0] = I915_FORMAT_MOD_Yf_TILED;
9044                 break;
9045         default:
9046                 MISSING_CASE(tiling);
9047                 goto error;
9048         }
9049
9050         base = I915_READ(PLANE_SURF(pipe, 0)) & 0xfffff000;
9051         plane_config->base = base;
9052
9053         offset = I915_READ(PLANE_OFFSET(pipe, 0));
9054
9055         val = I915_READ(PLANE_SIZE(pipe, 0));
9056         fb->height = ((val >> 16) & 0xfff) + 1;
9057         fb->width = ((val >> 0) & 0x1fff) + 1;
9058
9059         val = I915_READ(PLANE_STRIDE(pipe, 0));
9060         stride_mult = intel_fb_stride_alignment(dev_priv, fb->modifier[0],
9061                                                 fb->pixel_format);
9062         fb->pitches[0] = (val & 0x3ff) * stride_mult;
9063
9064         aligned_height = intel_fb_align_height(dev, fb->height,
9065                                                fb->pixel_format,
9066                                                fb->modifier[0]);
9067
9068         plane_config->size = fb->pitches[0] * aligned_height;
9069
9070         DRM_DEBUG_KMS("pipe %c with fb: size=%dx%d@%d, offset=%x, pitch %d, size 0x%x\n",
9071                       pipe_name(pipe), fb->width, fb->height,
9072                       fb->bits_per_pixel, base, fb->pitches[0],
9073                       plane_config->size);
9074
9075         plane_config->fb = intel_fb;
9076         return;
9077
9078 error:
9079         kfree(fb);
9080 }
9081
9082 static void ironlake_get_pfit_config(struct intel_crtc *crtc,
9083                                      struct intel_crtc_state *pipe_config)
9084 {
9085         struct drm_device *dev = crtc->base.dev;
9086         struct drm_i915_private *dev_priv = dev->dev_private;
9087         uint32_t tmp;
9088
9089         tmp = I915_READ(PF_CTL(crtc->pipe));
9090
9091         if (tmp & PF_ENABLE) {
9092                 pipe_config->pch_pfit.enabled = true;
9093                 pipe_config->pch_pfit.pos = I915_READ(PF_WIN_POS(crtc->pipe));
9094                 pipe_config->pch_pfit.size = I915_READ(PF_WIN_SZ(crtc->pipe));
9095
9096                 /* We currently do not free assignements of panel fitters on
9097                  * ivb/hsw (since we don't use the higher upscaling modes which
9098                  * differentiates them) so just WARN about this case for now. */
9099                 if (IS_GEN7(dev)) {
9100                         WARN_ON((tmp & PF_PIPE_SEL_MASK_IVB) !=
9101                                 PF_PIPE_SEL_IVB(crtc->pipe));
9102                 }
9103         }
9104 }
9105
9106 static void
9107 ironlake_get_initial_plane_config(struct intel_crtc *crtc,
9108                                   struct intel_initial_plane_config *plane_config)
9109 {
9110         struct drm_device *dev = crtc->base.dev;
9111         struct drm_i915_private *dev_priv = dev->dev_private;
9112         u32 val, base, offset;
9113         int pipe = crtc->pipe;
9114         int fourcc, pixel_format;
9115         unsigned int aligned_height;
9116         struct drm_framebuffer *fb;
9117         struct intel_framebuffer *intel_fb;
9118
9119         val = I915_READ(DSPCNTR(pipe));
9120         if (!(val & DISPLAY_PLANE_ENABLE))
9121                 return;
9122
9123         intel_fb = kzalloc(sizeof(*intel_fb), GFP_KERNEL);
9124         if (!intel_fb) {
9125                 DRM_DEBUG_KMS("failed to alloc fb\n");
9126                 return;
9127         }
9128
9129         fb = &intel_fb->base;
9130
9131         if (INTEL_INFO(dev)->gen >= 4) {
9132                 if (val & DISPPLANE_TILED) {
9133                         plane_config->tiling = I915_TILING_X;
9134                         fb->modifier[0] = I915_FORMAT_MOD_X_TILED;
9135                 }
9136         }
9137
9138         pixel_format = val & DISPPLANE_PIXFORMAT_MASK;
9139         fourcc = i9xx_format_to_fourcc(pixel_format);
9140         fb->pixel_format = fourcc;
9141         fb->bits_per_pixel = drm_format_plane_cpp(fourcc, 0) * 8;
9142
9143         base = I915_READ(DSPSURF(pipe)) & 0xfffff000;
9144         if (IS_HASWELL(dev) || IS_BROADWELL(dev)) {
9145                 offset = I915_READ(DSPOFFSET(pipe));
9146         } else {
9147                 if (plane_config->tiling)
9148                         offset = I915_READ(DSPTILEOFF(pipe));
9149                 else
9150                         offset = I915_READ(DSPLINOFF(pipe));
9151         }
9152         plane_config->base = base;
9153
9154         val = I915_READ(PIPESRC(pipe));
9155         fb->width = ((val >> 16) & 0xfff) + 1;
9156         fb->height = ((val >> 0) & 0xfff) + 1;
9157
9158         val = I915_READ(DSPSTRIDE(pipe));
9159         fb->pitches[0] = val & 0xffffffc0;
9160
9161         aligned_height = intel_fb_align_height(dev, fb->height,
9162                                                fb->pixel_format,
9163                                                fb->modifier[0]);
9164
9165         plane_config->size = fb->pitches[0] * aligned_height;
9166
9167         DRM_DEBUG_KMS("pipe %c with fb: size=%dx%d@%d, offset=%x, pitch %d, size 0x%x\n",
9168                       pipe_name(pipe), fb->width, fb->height,
9169                       fb->bits_per_pixel, base, fb->pitches[0],
9170                       plane_config->size);
9171
9172         plane_config->fb = intel_fb;
9173 }
9174
9175 static bool ironlake_get_pipe_config(struct intel_crtc *crtc,
9176                                      struct intel_crtc_state *pipe_config)
9177 {
9178         struct drm_device *dev = crtc->base.dev;
9179         struct drm_i915_private *dev_priv = dev->dev_private;
9180         enum intel_display_power_domain power_domain;
9181         uint32_t tmp;
9182         bool ret;
9183
9184         power_domain = POWER_DOMAIN_PIPE(crtc->pipe);
9185         if (!intel_display_power_get_if_enabled(dev_priv, power_domain))
9186                 return false;
9187
9188         pipe_config->cpu_transcoder = (enum transcoder) crtc->pipe;
9189         pipe_config->shared_dpll = NULL;
9190
9191         ret = false;
9192         tmp = I915_READ(PIPECONF(crtc->pipe));
9193         if (!(tmp & PIPECONF_ENABLE))
9194                 goto out;
9195
9196         switch (tmp & PIPECONF_BPC_MASK) {
9197         case PIPECONF_6BPC:
9198                 pipe_config->pipe_bpp = 18;
9199                 break;
9200         case PIPECONF_8BPC:
9201                 pipe_config->pipe_bpp = 24;
9202                 break;
9203         case PIPECONF_10BPC:
9204                 pipe_config->pipe_bpp = 30;
9205                 break;
9206         case PIPECONF_12BPC:
9207                 pipe_config->pipe_bpp = 36;
9208                 break;
9209         default:
9210                 break;
9211         }
9212
9213         if (tmp & PIPECONF_COLOR_RANGE_SELECT)
9214                 pipe_config->limited_color_range = true;
9215
9216         if (I915_READ(PCH_TRANSCONF(crtc->pipe)) & TRANS_ENABLE) {
9217                 struct intel_shared_dpll *pll;
9218                 enum intel_dpll_id pll_id;
9219
9220                 pipe_config->has_pch_encoder = true;
9221
9222                 tmp = I915_READ(FDI_RX_CTL(crtc->pipe));
9223                 pipe_config->fdi_lanes = ((FDI_DP_PORT_WIDTH_MASK & tmp) >>
9224                                           FDI_DP_PORT_WIDTH_SHIFT) + 1;
9225
9226                 ironlake_get_fdi_m_n_config(crtc, pipe_config);
9227
9228                 if (HAS_PCH_IBX(dev_priv)) {
9229                         /*
9230                          * The pipe->pch transcoder and pch transcoder->pll
9231                          * mapping is fixed.
9232                          */
9233                         pll_id = (enum intel_dpll_id) crtc->pipe;
9234                 } else {
9235                         tmp = I915_READ(PCH_DPLL_SEL);
9236                         if (tmp & TRANS_DPLLB_SEL(crtc->pipe))
9237                                 pll_id = DPLL_ID_PCH_PLL_B;
9238                         else
9239                                 pll_id= DPLL_ID_PCH_PLL_A;
9240                 }
9241
9242                 pipe_config->shared_dpll =
9243                         intel_get_shared_dpll_by_id(dev_priv, pll_id);
9244                 pll = pipe_config->shared_dpll;
9245
9246                 WARN_ON(!pll->funcs.get_hw_state(dev_priv, pll,
9247                                                  &pipe_config->dpll_hw_state));
9248
9249                 tmp = pipe_config->dpll_hw_state.dpll;
9250                 pipe_config->pixel_multiplier =
9251                         ((tmp & PLL_REF_SDVO_HDMI_MULTIPLIER_MASK)
9252                          >> PLL_REF_SDVO_HDMI_MULTIPLIER_SHIFT) + 1;
9253
9254                 ironlake_pch_clock_get(crtc, pipe_config);
9255         } else {
9256                 pipe_config->pixel_multiplier = 1;
9257         }
9258
9259         intel_get_pipe_timings(crtc, pipe_config);
9260         intel_get_pipe_src_size(crtc, pipe_config);
9261
9262         ironlake_get_pfit_config(crtc, pipe_config);
9263
9264         ret = true;
9265
9266 out:
9267         intel_display_power_put(dev_priv, power_domain);
9268
9269         return ret;
9270 }
9271
9272 static void assert_can_disable_lcpll(struct drm_i915_private *dev_priv)
9273 {
9274         struct drm_device *dev = dev_priv->dev;
9275         struct intel_crtc *crtc;
9276
9277         for_each_intel_crtc(dev, crtc)
9278                 I915_STATE_WARN(crtc->active, "CRTC for pipe %c enabled\n",
9279                      pipe_name(crtc->pipe));
9280
9281         I915_STATE_WARN(I915_READ(HSW_PWR_WELL_DRIVER), "Power well on\n");
9282         I915_STATE_WARN(I915_READ(SPLL_CTL) & SPLL_PLL_ENABLE, "SPLL enabled\n");
9283         I915_STATE_WARN(I915_READ(WRPLL_CTL(0)) & WRPLL_PLL_ENABLE, "WRPLL1 enabled\n");
9284         I915_STATE_WARN(I915_READ(WRPLL_CTL(1)) & WRPLL_PLL_ENABLE, "WRPLL2 enabled\n");
9285         I915_STATE_WARN(I915_READ(PCH_PP_STATUS) & PP_ON, "Panel power on\n");
9286         I915_STATE_WARN(I915_READ(BLC_PWM_CPU_CTL2) & BLM_PWM_ENABLE,
9287              "CPU PWM1 enabled\n");
9288         if (IS_HASWELL(dev))
9289                 I915_STATE_WARN(I915_READ(HSW_BLC_PWM2_CTL) & BLM_PWM_ENABLE,
9290                      "CPU PWM2 enabled\n");
9291         I915_STATE_WARN(I915_READ(BLC_PWM_PCH_CTL1) & BLM_PCH_PWM_ENABLE,
9292              "PCH PWM1 enabled\n");
9293         I915_STATE_WARN(I915_READ(UTIL_PIN_CTL) & UTIL_PIN_ENABLE,
9294              "Utility pin enabled\n");
9295         I915_STATE_WARN(I915_READ(PCH_GTC_CTL) & PCH_GTC_ENABLE, "PCH GTC enabled\n");
9296
9297         /*
9298          * In theory we can still leave IRQs enabled, as long as only the HPD
9299          * interrupts remain enabled. We used to check for that, but since it's
9300          * gen-specific and since we only disable LCPLL after we fully disable
9301          * the interrupts, the check below should be enough.
9302          */
9303         I915_STATE_WARN(intel_irqs_enabled(dev_priv), "IRQs enabled\n");
9304 }
9305
9306 static uint32_t hsw_read_dcomp(struct drm_i915_private *dev_priv)
9307 {
9308         struct drm_device *dev = dev_priv->dev;
9309
9310         if (IS_HASWELL(dev))
9311                 return I915_READ(D_COMP_HSW);
9312         else
9313                 return I915_READ(D_COMP_BDW);
9314 }
9315
9316 static void hsw_write_dcomp(struct drm_i915_private *dev_priv, uint32_t val)
9317 {
9318         struct drm_device *dev = dev_priv->dev;
9319
9320         if (IS_HASWELL(dev)) {
9321                 mutex_lock(&dev_priv->rps.hw_lock);
9322                 if (sandybridge_pcode_write(dev_priv, GEN6_PCODE_WRITE_D_COMP,
9323                                             val))
9324                         DRM_ERROR("Failed to write to D_COMP\n");
9325                 mutex_unlock(&dev_priv->rps.hw_lock);
9326         } else {
9327                 I915_WRITE(D_COMP_BDW, val);
9328                 POSTING_READ(D_COMP_BDW);
9329         }
9330 }
9331
9332 /*
9333  * This function implements pieces of two sequences from BSpec:
9334  * - Sequence for display software to disable LCPLL
9335  * - Sequence for display software to allow package C8+
9336  * The steps implemented here are just the steps that actually touch the LCPLL
9337  * register. Callers should take care of disabling all the display engine
9338  * functions, doing the mode unset, fixing interrupts, etc.
9339  */
9340 static void hsw_disable_lcpll(struct drm_i915_private *dev_priv,
9341                               bool switch_to_fclk, bool allow_power_down)
9342 {
9343         uint32_t val;
9344
9345         assert_can_disable_lcpll(dev_priv);
9346
9347         val = I915_READ(LCPLL_CTL);
9348
9349         if (switch_to_fclk) {
9350                 val |= LCPLL_CD_SOURCE_FCLK;
9351                 I915_WRITE(LCPLL_CTL, val);
9352
9353                 if (wait_for_atomic_us(I915_READ(LCPLL_CTL) &
9354                                        LCPLL_CD_SOURCE_FCLK_DONE, 1))
9355                         DRM_ERROR("Switching to FCLK failed\n");
9356
9357                 val = I915_READ(LCPLL_CTL);
9358         }
9359
9360         val |= LCPLL_PLL_DISABLE;
9361         I915_WRITE(LCPLL_CTL, val);
9362         POSTING_READ(LCPLL_CTL);
9363
9364         if (wait_for((I915_READ(LCPLL_CTL) & LCPLL_PLL_LOCK) == 0, 1))
9365                 DRM_ERROR("LCPLL still locked\n");
9366
9367         val = hsw_read_dcomp(dev_priv);
9368         val |= D_COMP_COMP_DISABLE;
9369         hsw_write_dcomp(dev_priv, val);
9370         ndelay(100);
9371
9372         if (wait_for((hsw_read_dcomp(dev_priv) & D_COMP_RCOMP_IN_PROGRESS) == 0,
9373                      1))
9374                 DRM_ERROR("D_COMP RCOMP still in progress\n");
9375
9376         if (allow_power_down) {
9377                 val = I915_READ(LCPLL_CTL);
9378                 val |= LCPLL_POWER_DOWN_ALLOW;
9379                 I915_WRITE(LCPLL_CTL, val);
9380                 POSTING_READ(LCPLL_CTL);
9381         }
9382 }
9383
9384 /*
9385  * Fully restores LCPLL, disallowing power down and switching back to LCPLL
9386  * source.
9387  */
9388 static void hsw_restore_lcpll(struct drm_i915_private *dev_priv)
9389 {
9390         uint32_t val;
9391
9392         val = I915_READ(LCPLL_CTL);
9393
9394         if ((val & (LCPLL_PLL_LOCK | LCPLL_PLL_DISABLE | LCPLL_CD_SOURCE_FCLK |
9395                     LCPLL_POWER_DOWN_ALLOW)) == LCPLL_PLL_LOCK)
9396                 return;
9397
9398         /*
9399          * Make sure we're not on PC8 state before disabling PC8, otherwise
9400          * we'll hang the machine. To prevent PC8 state, just enable force_wake.
9401          */
9402         intel_uncore_forcewake_get(dev_priv, FORCEWAKE_ALL);
9403
9404         if (val & LCPLL_POWER_DOWN_ALLOW) {
9405                 val &= ~LCPLL_POWER_DOWN_ALLOW;
9406                 I915_WRITE(LCPLL_CTL, val);
9407                 POSTING_READ(LCPLL_CTL);
9408         }
9409
9410         val = hsw_read_dcomp(dev_priv);
9411         val |= D_COMP_COMP_FORCE;
9412         val &= ~D_COMP_COMP_DISABLE;
9413         hsw_write_dcomp(dev_priv, val);
9414
9415         val = I915_READ(LCPLL_CTL);
9416         val &= ~LCPLL_PLL_DISABLE;
9417         I915_WRITE(LCPLL_CTL, val);
9418
9419         if (wait_for(I915_READ(LCPLL_CTL) & LCPLL_PLL_LOCK, 5))
9420                 DRM_ERROR("LCPLL not locked yet\n");
9421
9422         if (val & LCPLL_CD_SOURCE_FCLK) {
9423                 val = I915_READ(LCPLL_CTL);
9424                 val &= ~LCPLL_CD_SOURCE_FCLK;
9425                 I915_WRITE(LCPLL_CTL, val);
9426
9427                 if (wait_for_atomic_us((I915_READ(LCPLL_CTL) &
9428                                         LCPLL_CD_SOURCE_FCLK_DONE) == 0, 1))
9429                         DRM_ERROR("Switching back to LCPLL failed\n");
9430         }
9431
9432         intel_uncore_forcewake_put(dev_priv, FORCEWAKE_ALL);
9433         intel_update_cdclk(dev_priv->dev);
9434 }
9435
9436 /*
9437  * Package states C8 and deeper are really deep PC states that can only be
9438  * reached when all the devices on the system allow it, so even if the graphics
9439  * device allows PC8+, it doesn't mean the system will actually get to these
9440  * states. Our driver only allows PC8+ when going into runtime PM.
9441  *
9442  * The requirements for PC8+ are that all the outputs are disabled, the power
9443  * well is disabled and most interrupts are disabled, and these are also
9444  * requirements for runtime PM. When these conditions are met, we manually do
9445  * the other conditions: disable the interrupts, clocks and switch LCPLL refclk
9446  * to Fclk. If we're in PC8+ and we get an non-hotplug interrupt, we can hard
9447  * hang the machine.
9448  *
9449  * When we really reach PC8 or deeper states (not just when we allow it) we lose
9450  * the state of some registers, so when we come back from PC8+ we need to
9451  * restore this state. We don't get into PC8+ if we're not in RC6, so we don't
9452  * need to take care of the registers kept by RC6. Notice that this happens even
9453  * if we don't put the device in PCI D3 state (which is what currently happens
9454  * because of the runtime PM support).
9455  *
9456  * For more, read "Display Sequences for Package C8" on the hardware
9457  * documentation.
9458  */
9459 void hsw_enable_pc8(struct drm_i915_private *dev_priv)
9460 {
9461         struct drm_device *dev = dev_priv->dev;
9462         uint32_t val;
9463
9464         DRM_DEBUG_KMS("Enabling package C8+\n");
9465
9466         if (HAS_PCH_LPT_LP(dev)) {
9467                 val = I915_READ(SOUTH_DSPCLK_GATE_D);
9468                 val &= ~PCH_LP_PARTITION_LEVEL_DISABLE;
9469                 I915_WRITE(SOUTH_DSPCLK_GATE_D, val);
9470         }
9471
9472         lpt_disable_clkout_dp(dev);
9473         hsw_disable_lcpll(dev_priv, true, true);
9474 }
9475
9476 void hsw_disable_pc8(struct drm_i915_private *dev_priv)
9477 {
9478         struct drm_device *dev = dev_priv->dev;
9479         uint32_t val;
9480
9481         DRM_DEBUG_KMS("Disabling package C8+\n");
9482
9483         hsw_restore_lcpll(dev_priv);
9484         lpt_init_pch_refclk(dev);
9485
9486         if (HAS_PCH_LPT_LP(dev)) {
9487                 val = I915_READ(SOUTH_DSPCLK_GATE_D);
9488                 val |= PCH_LP_PARTITION_LEVEL_DISABLE;
9489                 I915_WRITE(SOUTH_DSPCLK_GATE_D, val);
9490         }
9491 }
9492
9493 static void broxton_modeset_commit_cdclk(struct drm_atomic_state *old_state)
9494 {
9495         struct drm_device *dev = old_state->dev;
9496         struct intel_atomic_state *old_intel_state =
9497                 to_intel_atomic_state(old_state);
9498         unsigned int req_cdclk = old_intel_state->dev_cdclk;
9499
9500         broxton_set_cdclk(to_i915(dev), req_cdclk);
9501 }
9502
9503 /* compute the max rate for new configuration */
9504 static int ilk_max_pixel_rate(struct drm_atomic_state *state)
9505 {
9506         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
9507         struct drm_i915_private *dev_priv = state->dev->dev_private;
9508         struct drm_crtc *crtc;
9509         struct drm_crtc_state *cstate;
9510         struct intel_crtc_state *crtc_state;
9511         unsigned max_pixel_rate = 0, i;
9512         enum pipe pipe;
9513
9514         memcpy(intel_state->min_pixclk, dev_priv->min_pixclk,
9515                sizeof(intel_state->min_pixclk));
9516
9517         for_each_crtc_in_state(state, crtc, cstate, i) {
9518                 int pixel_rate;
9519
9520                 crtc_state = to_intel_crtc_state(cstate);
9521                 if (!crtc_state->base.enable) {
9522                         intel_state->min_pixclk[i] = 0;
9523                         continue;
9524                 }
9525
9526                 pixel_rate = ilk_pipe_pixel_rate(crtc_state);
9527
9528                 /* pixel rate mustn't exceed 95% of cdclk with IPS on BDW */
9529                 if (IS_BROADWELL(dev_priv) && crtc_state->ips_enabled)
9530                         pixel_rate = DIV_ROUND_UP(pixel_rate * 100, 95);
9531
9532                 intel_state->min_pixclk[i] = pixel_rate;
9533         }
9534
9535         for_each_pipe(dev_priv, pipe)
9536                 max_pixel_rate = max(intel_state->min_pixclk[pipe], max_pixel_rate);
9537
9538         return max_pixel_rate;
9539 }
9540
9541 static void broadwell_set_cdclk(struct drm_device *dev, int cdclk)
9542 {
9543         struct drm_i915_private *dev_priv = dev->dev_private;
9544         uint32_t val, data;
9545         int ret;
9546
9547         if (WARN((I915_READ(LCPLL_CTL) &
9548                   (LCPLL_PLL_DISABLE | LCPLL_PLL_LOCK |
9549                    LCPLL_CD_CLOCK_DISABLE | LCPLL_ROOT_CD_CLOCK_DISABLE |
9550                    LCPLL_CD2X_CLOCK_DISABLE | LCPLL_POWER_DOWN_ALLOW |
9551                    LCPLL_CD_SOURCE_FCLK)) != LCPLL_PLL_LOCK,
9552                  "trying to change cdclk frequency with cdclk not enabled\n"))
9553                 return;
9554
9555         mutex_lock(&dev_priv->rps.hw_lock);
9556         ret = sandybridge_pcode_write(dev_priv,
9557                                       BDW_PCODE_DISPLAY_FREQ_CHANGE_REQ, 0x0);
9558         mutex_unlock(&dev_priv->rps.hw_lock);
9559         if (ret) {
9560                 DRM_ERROR("failed to inform pcode about cdclk change\n");
9561                 return;
9562         }
9563
9564         val = I915_READ(LCPLL_CTL);
9565         val |= LCPLL_CD_SOURCE_FCLK;
9566         I915_WRITE(LCPLL_CTL, val);
9567
9568         if (wait_for_us(I915_READ(LCPLL_CTL) &
9569                         LCPLL_CD_SOURCE_FCLK_DONE, 1))
9570                 DRM_ERROR("Switching to FCLK failed\n");
9571
9572         val = I915_READ(LCPLL_CTL);
9573         val &= ~LCPLL_CLK_FREQ_MASK;
9574
9575         switch (cdclk) {
9576         case 450000:
9577                 val |= LCPLL_CLK_FREQ_450;
9578                 data = 0;
9579                 break;
9580         case 540000:
9581                 val |= LCPLL_CLK_FREQ_54O_BDW;
9582                 data = 1;
9583                 break;
9584         case 337500:
9585                 val |= LCPLL_CLK_FREQ_337_5_BDW;
9586                 data = 2;
9587                 break;
9588         case 675000:
9589                 val |= LCPLL_CLK_FREQ_675_BDW;
9590                 data = 3;
9591                 break;
9592         default:
9593                 WARN(1, "invalid cdclk frequency\n");
9594                 return;
9595         }
9596
9597         I915_WRITE(LCPLL_CTL, val);
9598
9599         val = I915_READ(LCPLL_CTL);
9600         val &= ~LCPLL_CD_SOURCE_FCLK;
9601         I915_WRITE(LCPLL_CTL, val);
9602
9603         if (wait_for_us((I915_READ(LCPLL_CTL) &
9604                         LCPLL_CD_SOURCE_FCLK_DONE) == 0, 1))
9605                 DRM_ERROR("Switching back to LCPLL failed\n");
9606
9607         mutex_lock(&dev_priv->rps.hw_lock);
9608         sandybridge_pcode_write(dev_priv, HSW_PCODE_DE_WRITE_FREQ_REQ, data);
9609         mutex_unlock(&dev_priv->rps.hw_lock);
9610
9611         I915_WRITE(CDCLK_FREQ, DIV_ROUND_CLOSEST(cdclk, 1000) - 1);
9612
9613         intel_update_cdclk(dev);
9614
9615         WARN(cdclk != dev_priv->cdclk_freq,
9616              "cdclk requested %d kHz but got %d kHz\n",
9617              cdclk, dev_priv->cdclk_freq);
9618 }
9619
9620 static int broadwell_calc_cdclk(int max_pixclk)
9621 {
9622         if (max_pixclk > 540000)
9623                 return 675000;
9624         else if (max_pixclk > 450000)
9625                 return 540000;
9626         else if (max_pixclk > 337500)
9627                 return 450000;
9628         else
9629                 return 337500;
9630 }
9631
9632 static int broadwell_modeset_calc_cdclk(struct drm_atomic_state *state)
9633 {
9634         struct drm_i915_private *dev_priv = to_i915(state->dev);
9635         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
9636         int max_pixclk = ilk_max_pixel_rate(state);
9637         int cdclk;
9638
9639         /*
9640          * FIXME should also account for plane ratio
9641          * once 64bpp pixel formats are supported.
9642          */
9643         cdclk = broadwell_calc_cdclk(max_pixclk);
9644
9645         if (cdclk > dev_priv->max_cdclk_freq) {
9646                 DRM_DEBUG_KMS("requested cdclk (%d kHz) exceeds max (%d kHz)\n",
9647                               cdclk, dev_priv->max_cdclk_freq);
9648                 return -EINVAL;
9649         }
9650
9651         intel_state->cdclk = intel_state->dev_cdclk = cdclk;
9652         if (!intel_state->active_crtcs)
9653                 intel_state->dev_cdclk = broadwell_calc_cdclk(0);
9654
9655         return 0;
9656 }
9657
9658 static void broadwell_modeset_commit_cdclk(struct drm_atomic_state *old_state)
9659 {
9660         struct drm_device *dev = old_state->dev;
9661         struct intel_atomic_state *old_intel_state =
9662                 to_intel_atomic_state(old_state);
9663         unsigned req_cdclk = old_intel_state->dev_cdclk;
9664
9665         broadwell_set_cdclk(dev, req_cdclk);
9666 }
9667
9668 static int skl_modeset_calc_cdclk(struct drm_atomic_state *state)
9669 {
9670         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
9671         struct drm_i915_private *dev_priv = to_i915(state->dev);
9672         const int max_pixclk = ilk_max_pixel_rate(state);
9673         int vco = intel_state->cdclk_pll_vco;
9674         int cdclk;
9675
9676         /*
9677          * FIXME should also account for plane ratio
9678          * once 64bpp pixel formats are supported.
9679          */
9680         cdclk = skl_calc_cdclk(max_pixclk, vco);
9681
9682         /*
9683          * FIXME move the cdclk caclulation to
9684          * compute_config() so we can fail gracegully.
9685          */
9686         if (cdclk > dev_priv->max_cdclk_freq) {
9687                 DRM_ERROR("requested cdclk (%d kHz) exceeds max (%d kHz)\n",
9688                           cdclk, dev_priv->max_cdclk_freq);
9689                 cdclk = dev_priv->max_cdclk_freq;
9690         }
9691
9692         intel_state->cdclk = intel_state->dev_cdclk = cdclk;
9693         if (!intel_state->active_crtcs)
9694                 intel_state->dev_cdclk = skl_calc_cdclk(0, vco);
9695
9696         return 0;
9697 }
9698
9699 static void skl_modeset_commit_cdclk(struct drm_atomic_state *old_state)
9700 {
9701         struct drm_device *dev = old_state->dev;
9702         struct drm_i915_private *dev_priv = dev->dev_private;
9703         unsigned int req_cdclk = to_intel_atomic_state(old_state)->dev_cdclk;
9704
9705         /*
9706          * FIXME disable/enable PLL should wrap set_cdclk()
9707          */
9708         skl_set_cdclk(dev_priv, req_cdclk);
9709
9710         dev_priv->skl_vco_freq = to_intel_atomic_state(old_state)->cdclk_pll_vco;
9711 }
9712
9713 static int haswell_crtc_compute_clock(struct intel_crtc *crtc,
9714                                       struct intel_crtc_state *crtc_state)
9715 {
9716         struct intel_encoder *intel_encoder =
9717                 intel_ddi_get_crtc_new_encoder(crtc_state);
9718
9719         if (intel_encoder->type != INTEL_OUTPUT_DSI) {
9720                 if (!intel_ddi_pll_select(crtc, crtc_state))
9721                         return -EINVAL;
9722         }
9723
9724         crtc->lowfreq_avail = false;
9725
9726         return 0;
9727 }
9728
9729 static void bxt_get_ddi_pll(struct drm_i915_private *dev_priv,
9730                                 enum port port,
9731                                 struct intel_crtc_state *pipe_config)
9732 {
9733         enum intel_dpll_id id;
9734
9735         switch (port) {
9736         case PORT_A:
9737                 pipe_config->ddi_pll_sel = SKL_DPLL0;
9738                 id = DPLL_ID_SKL_DPLL0;
9739                 break;
9740         case PORT_B:
9741                 pipe_config->ddi_pll_sel = SKL_DPLL1;
9742                 id = DPLL_ID_SKL_DPLL1;
9743                 break;
9744         case PORT_C:
9745                 pipe_config->ddi_pll_sel = SKL_DPLL2;
9746                 id = DPLL_ID_SKL_DPLL2;
9747                 break;
9748         default:
9749                 DRM_ERROR("Incorrect port type\n");
9750                 return;
9751         }
9752
9753         pipe_config->shared_dpll = intel_get_shared_dpll_by_id(dev_priv, id);
9754 }
9755
9756 static void skylake_get_ddi_pll(struct drm_i915_private *dev_priv,
9757                                 enum port port,
9758                                 struct intel_crtc_state *pipe_config)
9759 {
9760         enum intel_dpll_id id;
9761         u32 temp;
9762
9763         temp = I915_READ(DPLL_CTRL2) & DPLL_CTRL2_DDI_CLK_SEL_MASK(port);
9764         pipe_config->ddi_pll_sel = temp >> (port * 3 + 1);
9765
9766         switch (pipe_config->ddi_pll_sel) {
9767         case SKL_DPLL0:
9768                 id = DPLL_ID_SKL_DPLL0;
9769                 break;
9770         case SKL_DPLL1:
9771                 id = DPLL_ID_SKL_DPLL1;
9772                 break;
9773         case SKL_DPLL2:
9774                 id = DPLL_ID_SKL_DPLL2;
9775                 break;
9776         case SKL_DPLL3:
9777                 id = DPLL_ID_SKL_DPLL3;
9778                 break;
9779         default:
9780                 MISSING_CASE(pipe_config->ddi_pll_sel);
9781                 return;
9782         }
9783
9784         pipe_config->shared_dpll = intel_get_shared_dpll_by_id(dev_priv, id);
9785 }
9786
9787 static void haswell_get_ddi_pll(struct drm_i915_private *dev_priv,
9788                                 enum port port,
9789                                 struct intel_crtc_state *pipe_config)
9790 {
9791         enum intel_dpll_id id;
9792
9793         pipe_config->ddi_pll_sel = I915_READ(PORT_CLK_SEL(port));
9794
9795         switch (pipe_config->ddi_pll_sel) {
9796         case PORT_CLK_SEL_WRPLL1:
9797                 id = DPLL_ID_WRPLL1;
9798                 break;
9799         case PORT_CLK_SEL_WRPLL2:
9800                 id = DPLL_ID_WRPLL2;
9801                 break;
9802         case PORT_CLK_SEL_SPLL:
9803                 id = DPLL_ID_SPLL;
9804                 break;
9805         case PORT_CLK_SEL_LCPLL_810:
9806                 id = DPLL_ID_LCPLL_810;
9807                 break;
9808         case PORT_CLK_SEL_LCPLL_1350:
9809                 id = DPLL_ID_LCPLL_1350;
9810                 break;
9811         case PORT_CLK_SEL_LCPLL_2700:
9812                 id = DPLL_ID_LCPLL_2700;
9813                 break;
9814         default:
9815                 MISSING_CASE(pipe_config->ddi_pll_sel);
9816                 /* fall through */
9817         case PORT_CLK_SEL_NONE:
9818                 return;
9819         }
9820
9821         pipe_config->shared_dpll = intel_get_shared_dpll_by_id(dev_priv, id);
9822 }
9823
9824 static bool hsw_get_transcoder_state(struct intel_crtc *crtc,
9825                                      struct intel_crtc_state *pipe_config,
9826                                      unsigned long *power_domain_mask)
9827 {
9828         struct drm_device *dev = crtc->base.dev;
9829         struct drm_i915_private *dev_priv = dev->dev_private;
9830         enum intel_display_power_domain power_domain;
9831         u32 tmp;
9832
9833         /*
9834          * The pipe->transcoder mapping is fixed with the exception of the eDP
9835          * transcoder handled below.
9836          */
9837         pipe_config->cpu_transcoder = (enum transcoder) crtc->pipe;
9838
9839         /*
9840          * XXX: Do intel_display_power_get_if_enabled before reading this (for
9841          * consistency and less surprising code; it's in always on power).
9842          */
9843         tmp = I915_READ(TRANS_DDI_FUNC_CTL(TRANSCODER_EDP));
9844         if (tmp & TRANS_DDI_FUNC_ENABLE) {
9845                 enum pipe trans_edp_pipe;
9846                 switch (tmp & TRANS_DDI_EDP_INPUT_MASK) {
9847                 default:
9848                         WARN(1, "unknown pipe linked to edp transcoder\n");
9849                 case TRANS_DDI_EDP_INPUT_A_ONOFF:
9850                 case TRANS_DDI_EDP_INPUT_A_ON:
9851                         trans_edp_pipe = PIPE_A;
9852                         break;
9853                 case TRANS_DDI_EDP_INPUT_B_ONOFF:
9854                         trans_edp_pipe = PIPE_B;
9855                         break;
9856                 case TRANS_DDI_EDP_INPUT_C_ONOFF:
9857                         trans_edp_pipe = PIPE_C;
9858                         break;
9859                 }
9860
9861                 if (trans_edp_pipe == crtc->pipe)
9862                         pipe_config->cpu_transcoder = TRANSCODER_EDP;
9863         }
9864
9865         power_domain = POWER_DOMAIN_TRANSCODER(pipe_config->cpu_transcoder);
9866         if (!intel_display_power_get_if_enabled(dev_priv, power_domain))
9867                 return false;
9868         *power_domain_mask |= BIT(power_domain);
9869
9870         tmp = I915_READ(PIPECONF(pipe_config->cpu_transcoder));
9871
9872         return tmp & PIPECONF_ENABLE;
9873 }
9874
9875 static bool bxt_get_dsi_transcoder_state(struct intel_crtc *crtc,
9876                                          struct intel_crtc_state *pipe_config,
9877                                          unsigned long *power_domain_mask)
9878 {
9879         struct drm_device *dev = crtc->base.dev;
9880         struct drm_i915_private *dev_priv = dev->dev_private;
9881         enum intel_display_power_domain power_domain;
9882         enum port port;
9883         enum transcoder cpu_transcoder;
9884         u32 tmp;
9885
9886         pipe_config->has_dsi_encoder = false;
9887
9888         for_each_port_masked(port, BIT(PORT_A) | BIT(PORT_C)) {
9889                 if (port == PORT_A)
9890                         cpu_transcoder = TRANSCODER_DSI_A;
9891                 else
9892                         cpu_transcoder = TRANSCODER_DSI_C;
9893
9894                 power_domain = POWER_DOMAIN_TRANSCODER(cpu_transcoder);
9895                 if (!intel_display_power_get_if_enabled(dev_priv, power_domain))
9896                         continue;
9897                 *power_domain_mask |= BIT(power_domain);
9898
9899                 /*
9900                  * The PLL needs to be enabled with a valid divider
9901                  * configuration, otherwise accessing DSI registers will hang
9902                  * the machine. See BSpec North Display Engine
9903                  * registers/MIPI[BXT]. We can break out here early, since we
9904                  * need the same DSI PLL to be enabled for both DSI ports.
9905                  */
9906                 if (!intel_dsi_pll_is_enabled(dev_priv))
9907                         break;
9908
9909                 /* XXX: this works for video mode only */
9910                 tmp = I915_READ(BXT_MIPI_PORT_CTRL(port));
9911                 if (!(tmp & DPI_ENABLE))
9912                         continue;
9913
9914                 tmp = I915_READ(MIPI_CTRL(port));
9915                 if ((tmp & BXT_PIPE_SELECT_MASK) != BXT_PIPE_SELECT(crtc->pipe))
9916                         continue;
9917
9918                 pipe_config->cpu_transcoder = cpu_transcoder;
9919                 pipe_config->has_dsi_encoder = true;
9920                 break;
9921         }
9922
9923         return pipe_config->has_dsi_encoder;
9924 }
9925
9926 static void haswell_get_ddi_port_state(struct intel_crtc *crtc,
9927                                        struct intel_crtc_state *pipe_config)
9928 {
9929         struct drm_device *dev = crtc->base.dev;
9930         struct drm_i915_private *dev_priv = dev->dev_private;
9931         struct intel_shared_dpll *pll;
9932         enum port port;
9933         uint32_t tmp;
9934
9935         tmp = I915_READ(TRANS_DDI_FUNC_CTL(pipe_config->cpu_transcoder));
9936
9937         port = (tmp & TRANS_DDI_PORT_MASK) >> TRANS_DDI_PORT_SHIFT;
9938
9939         if (IS_SKYLAKE(dev) || IS_KABYLAKE(dev))
9940                 skylake_get_ddi_pll(dev_priv, port, pipe_config);
9941         else if (IS_BROXTON(dev))
9942                 bxt_get_ddi_pll(dev_priv, port, pipe_config);
9943         else
9944                 haswell_get_ddi_pll(dev_priv, port, pipe_config);
9945
9946         pll = pipe_config->shared_dpll;
9947         if (pll) {
9948                 WARN_ON(!pll->funcs.get_hw_state(dev_priv, pll,
9949                                                  &pipe_config->dpll_hw_state));
9950         }
9951
9952         /*
9953          * Haswell has only FDI/PCH transcoder A. It is which is connected to
9954          * DDI E. So just check whether this pipe is wired to DDI E and whether
9955          * the PCH transcoder is on.
9956          */
9957         if (INTEL_INFO(dev)->gen < 9 &&
9958             (port == PORT_E) && I915_READ(LPT_TRANSCONF) & TRANS_ENABLE) {
9959                 pipe_config->has_pch_encoder = true;
9960
9961                 tmp = I915_READ(FDI_RX_CTL(PIPE_A));
9962                 pipe_config->fdi_lanes = ((FDI_DP_PORT_WIDTH_MASK & tmp) >>
9963                                           FDI_DP_PORT_WIDTH_SHIFT) + 1;
9964
9965                 ironlake_get_fdi_m_n_config(crtc, pipe_config);
9966         }
9967 }
9968
9969 static bool haswell_get_pipe_config(struct intel_crtc *crtc,
9970                                     struct intel_crtc_state *pipe_config)
9971 {
9972         struct drm_device *dev = crtc->base.dev;
9973         struct drm_i915_private *dev_priv = dev->dev_private;
9974         enum intel_display_power_domain power_domain;
9975         unsigned long power_domain_mask;
9976         bool active;
9977
9978         power_domain = POWER_DOMAIN_PIPE(crtc->pipe);
9979         if (!intel_display_power_get_if_enabled(dev_priv, power_domain))
9980                 return false;
9981         power_domain_mask = BIT(power_domain);
9982
9983         pipe_config->shared_dpll = NULL;
9984
9985         active = hsw_get_transcoder_state(crtc, pipe_config, &power_domain_mask);
9986
9987         if (IS_BROXTON(dev_priv)) {
9988                 bxt_get_dsi_transcoder_state(crtc, pipe_config,
9989                                              &power_domain_mask);
9990                 WARN_ON(active && pipe_config->has_dsi_encoder);
9991                 if (pipe_config->has_dsi_encoder)
9992                         active = true;
9993         }
9994
9995         if (!active)
9996                 goto out;
9997
9998         if (!pipe_config->has_dsi_encoder) {
9999                 haswell_get_ddi_port_state(crtc, pipe_config);
10000                 intel_get_pipe_timings(crtc, pipe_config);
10001         }
10002
10003         intel_get_pipe_src_size(crtc, pipe_config);
10004
10005         pipe_config->gamma_mode =
10006                 I915_READ(GAMMA_MODE(crtc->pipe)) & GAMMA_MODE_MODE_MASK;
10007
10008         if (INTEL_INFO(dev)->gen >= 9) {
10009                 skl_init_scalers(dev, crtc, pipe_config);
10010         }
10011
10012         if (INTEL_INFO(dev)->gen >= 9) {
10013                 pipe_config->scaler_state.scaler_id = -1;
10014                 pipe_config->scaler_state.scaler_users &= ~(1 << SKL_CRTC_INDEX);
10015         }
10016
10017         power_domain = POWER_DOMAIN_PIPE_PANEL_FITTER(crtc->pipe);
10018         if (intel_display_power_get_if_enabled(dev_priv, power_domain)) {
10019                 power_domain_mask |= BIT(power_domain);
10020                 if (INTEL_INFO(dev)->gen >= 9)
10021                         skylake_get_pfit_config(crtc, pipe_config);
10022                 else
10023                         ironlake_get_pfit_config(crtc, pipe_config);
10024         }
10025
10026         if (IS_HASWELL(dev))
10027                 pipe_config->ips_enabled = hsw_crtc_supports_ips(crtc) &&
10028                         (I915_READ(IPS_CTL) & IPS_ENABLE);
10029
10030         if (pipe_config->cpu_transcoder != TRANSCODER_EDP &&
10031             !transcoder_is_dsi(pipe_config->cpu_transcoder)) {
10032                 pipe_config->pixel_multiplier =
10033                         I915_READ(PIPE_MULT(pipe_config->cpu_transcoder)) + 1;
10034         } else {
10035                 pipe_config->pixel_multiplier = 1;
10036         }
10037
10038 out:
10039         for_each_power_domain(power_domain, power_domain_mask)
10040                 intel_display_power_put(dev_priv, power_domain);
10041
10042         return active;
10043 }
10044
10045 static void i845_update_cursor(struct drm_crtc *crtc, u32 base,
10046                                const struct intel_plane_state *plane_state)
10047 {
10048         struct drm_device *dev = crtc->dev;
10049         struct drm_i915_private *dev_priv = dev->dev_private;
10050         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
10051         uint32_t cntl = 0, size = 0;
10052
10053         if (plane_state && plane_state->visible) {
10054                 unsigned int width = plane_state->base.crtc_w;
10055                 unsigned int height = plane_state->base.crtc_h;
10056                 unsigned int stride = roundup_pow_of_two(width) * 4;
10057
10058                 switch (stride) {
10059                 default:
10060                         WARN_ONCE(1, "Invalid cursor width/stride, width=%u, stride=%u\n",
10061                                   width, stride);
10062                         stride = 256;
10063                         /* fallthrough */
10064                 case 256:
10065                 case 512:
10066                 case 1024:
10067                 case 2048:
10068                         break;
10069                 }
10070
10071                 cntl |= CURSOR_ENABLE |
10072                         CURSOR_GAMMA_ENABLE |
10073                         CURSOR_FORMAT_ARGB |
10074                         CURSOR_STRIDE(stride);
10075
10076                 size = (height << 12) | width;
10077         }
10078
10079         if (intel_crtc->cursor_cntl != 0 &&
10080             (intel_crtc->cursor_base != base ||
10081              intel_crtc->cursor_size != size ||
10082              intel_crtc->cursor_cntl != cntl)) {
10083                 /* On these chipsets we can only modify the base/size/stride
10084                  * whilst the cursor is disabled.
10085                  */
10086                 I915_WRITE(CURCNTR(PIPE_A), 0);
10087                 POSTING_READ(CURCNTR(PIPE_A));
10088                 intel_crtc->cursor_cntl = 0;
10089         }
10090
10091         if (intel_crtc->cursor_base != base) {
10092                 I915_WRITE(CURBASE(PIPE_A), base);
10093                 intel_crtc->cursor_base = base;
10094         }
10095
10096         if (intel_crtc->cursor_size != size) {
10097                 I915_WRITE(CURSIZE, size);
10098                 intel_crtc->cursor_size = size;
10099         }
10100
10101         if (intel_crtc->cursor_cntl != cntl) {
10102                 I915_WRITE(CURCNTR(PIPE_A), cntl);
10103                 POSTING_READ(CURCNTR(PIPE_A));
10104                 intel_crtc->cursor_cntl = cntl;
10105         }
10106 }
10107
10108 static void i9xx_update_cursor(struct drm_crtc *crtc, u32 base,
10109                                const struct intel_plane_state *plane_state)
10110 {
10111         struct drm_device *dev = crtc->dev;
10112         struct drm_i915_private *dev_priv = dev->dev_private;
10113         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
10114         int pipe = intel_crtc->pipe;
10115         uint32_t cntl = 0;
10116
10117         if (plane_state && plane_state->visible) {
10118                 cntl = MCURSOR_GAMMA_ENABLE;
10119                 switch (plane_state->base.crtc_w) {
10120                         case 64:
10121                                 cntl |= CURSOR_MODE_64_ARGB_AX;
10122                                 break;
10123                         case 128:
10124                                 cntl |= CURSOR_MODE_128_ARGB_AX;
10125                                 break;
10126                         case 256:
10127                                 cntl |= CURSOR_MODE_256_ARGB_AX;
10128                                 break;
10129                         default:
10130                                 MISSING_CASE(plane_state->base.crtc_w);
10131                                 return;
10132                 }
10133                 cntl |= pipe << 28; /* Connect to correct pipe */
10134
10135                 if (HAS_DDI(dev))
10136                         cntl |= CURSOR_PIPE_CSC_ENABLE;
10137
10138                 if (plane_state->base.rotation == BIT(DRM_ROTATE_180))
10139                         cntl |= CURSOR_ROTATE_180;
10140         }
10141
10142         if (intel_crtc->cursor_cntl != cntl) {
10143                 I915_WRITE(CURCNTR(pipe), cntl);
10144                 POSTING_READ(CURCNTR(pipe));
10145                 intel_crtc->cursor_cntl = cntl;
10146         }
10147
10148         /* and commit changes on next vblank */
10149         I915_WRITE(CURBASE(pipe), base);
10150         POSTING_READ(CURBASE(pipe));
10151
10152         intel_crtc->cursor_base = base;
10153 }
10154
10155 /* If no-part of the cursor is visible on the framebuffer, then the GPU may hang... */
10156 static void intel_crtc_update_cursor(struct drm_crtc *crtc,
10157                                      const struct intel_plane_state *plane_state)
10158 {
10159         struct drm_device *dev = crtc->dev;
10160         struct drm_i915_private *dev_priv = dev->dev_private;
10161         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
10162         int pipe = intel_crtc->pipe;
10163         u32 base = intel_crtc->cursor_addr;
10164         u32 pos = 0;
10165
10166         if (plane_state) {
10167                 int x = plane_state->base.crtc_x;
10168                 int y = plane_state->base.crtc_y;
10169
10170                 if (x < 0) {
10171                         pos |= CURSOR_POS_SIGN << CURSOR_X_SHIFT;
10172                         x = -x;
10173                 }
10174                 pos |= x << CURSOR_X_SHIFT;
10175
10176                 if (y < 0) {
10177                         pos |= CURSOR_POS_SIGN << CURSOR_Y_SHIFT;
10178                         y = -y;
10179                 }
10180                 pos |= y << CURSOR_Y_SHIFT;
10181
10182                 /* ILK+ do this automagically */
10183                 if (HAS_GMCH_DISPLAY(dev) &&
10184                     plane_state->base.rotation == BIT(DRM_ROTATE_180)) {
10185                         base += (plane_state->base.crtc_h *
10186                                  plane_state->base.crtc_w - 1) * 4;
10187                 }
10188         }
10189
10190         I915_WRITE(CURPOS(pipe), pos);
10191
10192         if (IS_845G(dev) || IS_I865G(dev))
10193                 i845_update_cursor(crtc, base, plane_state);
10194         else
10195                 i9xx_update_cursor(crtc, base, plane_state);
10196 }
10197
10198 static bool cursor_size_ok(struct drm_device *dev,
10199                            uint32_t width, uint32_t height)
10200 {
10201         if (width == 0 || height == 0)
10202                 return false;
10203
10204         /*
10205          * 845g/865g are special in that they are only limited by
10206          * the width of their cursors, the height is arbitrary up to
10207          * the precision of the register. Everything else requires
10208          * square cursors, limited to a few power-of-two sizes.
10209          */
10210         if (IS_845G(dev) || IS_I865G(dev)) {
10211                 if ((width & 63) != 0)
10212                         return false;
10213
10214                 if (width > (IS_845G(dev) ? 64 : 512))
10215                         return false;
10216
10217                 if (height > 1023)
10218                         return false;
10219         } else {
10220                 switch (width | height) {
10221                 case 256:
10222                 case 128:
10223                         if (IS_GEN2(dev))
10224                                 return false;
10225                 case 64:
10226                         break;
10227                 default:
10228                         return false;
10229                 }
10230         }
10231
10232         return true;
10233 }
10234
10235 /* VESA 640x480x72Hz mode to set on the pipe */
10236 static struct drm_display_mode load_detect_mode = {
10237         DRM_MODE("640x480", DRM_MODE_TYPE_DEFAULT, 31500, 640, 664,
10238                  704, 832, 0, 480, 489, 491, 520, 0, DRM_MODE_FLAG_NHSYNC | DRM_MODE_FLAG_NVSYNC),
10239 };
10240
10241 struct drm_framebuffer *
10242 __intel_framebuffer_create(struct drm_device *dev,
10243                            struct drm_mode_fb_cmd2 *mode_cmd,
10244                            struct drm_i915_gem_object *obj)
10245 {
10246         struct intel_framebuffer *intel_fb;
10247         int ret;
10248
10249         intel_fb = kzalloc(sizeof(*intel_fb), GFP_KERNEL);
10250         if (!intel_fb)
10251                 return ERR_PTR(-ENOMEM);
10252
10253         ret = intel_framebuffer_init(dev, intel_fb, mode_cmd, obj);
10254         if (ret)
10255                 goto err;
10256
10257         return &intel_fb->base;
10258
10259 err:
10260         kfree(intel_fb);
10261         return ERR_PTR(ret);
10262 }
10263
10264 static struct drm_framebuffer *
10265 intel_framebuffer_create(struct drm_device *dev,
10266                          struct drm_mode_fb_cmd2 *mode_cmd,
10267                          struct drm_i915_gem_object *obj)
10268 {
10269         struct drm_framebuffer *fb;
10270         int ret;
10271
10272         ret = i915_mutex_lock_interruptible(dev);
10273         if (ret)
10274                 return ERR_PTR(ret);
10275         fb = __intel_framebuffer_create(dev, mode_cmd, obj);
10276         mutex_unlock(&dev->struct_mutex);
10277
10278         return fb;
10279 }
10280
10281 static u32
10282 intel_framebuffer_pitch_for_width(int width, int bpp)
10283 {
10284         u32 pitch = DIV_ROUND_UP(width * bpp, 8);
10285         return ALIGN(pitch, 64);
10286 }
10287
10288 static u32
10289 intel_framebuffer_size_for_mode(struct drm_display_mode *mode, int bpp)
10290 {
10291         u32 pitch = intel_framebuffer_pitch_for_width(mode->hdisplay, bpp);
10292         return PAGE_ALIGN(pitch * mode->vdisplay);
10293 }
10294
10295 static struct drm_framebuffer *
10296 intel_framebuffer_create_for_mode(struct drm_device *dev,
10297                                   struct drm_display_mode *mode,
10298                                   int depth, int bpp)
10299 {
10300         struct drm_framebuffer *fb;
10301         struct drm_i915_gem_object *obj;
10302         struct drm_mode_fb_cmd2 mode_cmd = { 0 };
10303
10304         obj = i915_gem_object_create(dev,
10305                                     intel_framebuffer_size_for_mode(mode, bpp));
10306         if (IS_ERR(obj))
10307                 return ERR_CAST(obj);
10308
10309         mode_cmd.width = mode->hdisplay;
10310         mode_cmd.height = mode->vdisplay;
10311         mode_cmd.pitches[0] = intel_framebuffer_pitch_for_width(mode_cmd.width,
10312                                                                 bpp);
10313         mode_cmd.pixel_format = drm_mode_legacy_fb_format(bpp, depth);
10314
10315         fb = intel_framebuffer_create(dev, &mode_cmd, obj);
10316         if (IS_ERR(fb))
10317                 drm_gem_object_unreference_unlocked(&obj->base);
10318
10319         return fb;
10320 }
10321
10322 static struct drm_framebuffer *
10323 mode_fits_in_fbdev(struct drm_device *dev,
10324                    struct drm_display_mode *mode)
10325 {
10326 #ifdef CONFIG_DRM_FBDEV_EMULATION
10327         struct drm_i915_private *dev_priv = dev->dev_private;
10328         struct drm_i915_gem_object *obj;
10329         struct drm_framebuffer *fb;
10330
10331         if (!dev_priv->fbdev)
10332                 return NULL;
10333
10334         if (!dev_priv->fbdev->fb)
10335                 return NULL;
10336
10337         obj = dev_priv->fbdev->fb->obj;
10338         BUG_ON(!obj);
10339
10340         fb = &dev_priv->fbdev->fb->base;
10341         if (fb->pitches[0] < intel_framebuffer_pitch_for_width(mode->hdisplay,
10342                                                                fb->bits_per_pixel))
10343                 return NULL;
10344
10345         if (obj->base.size < mode->vdisplay * fb->pitches[0])
10346                 return NULL;
10347
10348         drm_framebuffer_reference(fb);
10349         return fb;
10350 #else
10351         return NULL;
10352 #endif
10353 }
10354
10355 static int intel_modeset_setup_plane_state(struct drm_atomic_state *state,
10356                                            struct drm_crtc *crtc,
10357                                            struct drm_display_mode *mode,
10358                                            struct drm_framebuffer *fb,
10359                                            int x, int y)
10360 {
10361         struct drm_plane_state *plane_state;
10362         int hdisplay, vdisplay;
10363         int ret;
10364
10365         plane_state = drm_atomic_get_plane_state(state, crtc->primary);
10366         if (IS_ERR(plane_state))
10367                 return PTR_ERR(plane_state);
10368
10369         if (mode)
10370                 drm_crtc_get_hv_timing(mode, &hdisplay, &vdisplay);
10371         else
10372                 hdisplay = vdisplay = 0;
10373
10374         ret = drm_atomic_set_crtc_for_plane(plane_state, fb ? crtc : NULL);
10375         if (ret)
10376                 return ret;
10377         drm_atomic_set_fb_for_plane(plane_state, fb);
10378         plane_state->crtc_x = 0;
10379         plane_state->crtc_y = 0;
10380         plane_state->crtc_w = hdisplay;
10381         plane_state->crtc_h = vdisplay;
10382         plane_state->src_x = x << 16;
10383         plane_state->src_y = y << 16;
10384         plane_state->src_w = hdisplay << 16;
10385         plane_state->src_h = vdisplay << 16;
10386
10387         return 0;
10388 }
10389
10390 bool intel_get_load_detect_pipe(struct drm_connector *connector,
10391                                 struct drm_display_mode *mode,
10392                                 struct intel_load_detect_pipe *old,
10393                                 struct drm_modeset_acquire_ctx *ctx)
10394 {
10395         struct intel_crtc *intel_crtc;
10396         struct intel_encoder *intel_encoder =
10397                 intel_attached_encoder(connector);
10398         struct drm_crtc *possible_crtc;
10399         struct drm_encoder *encoder = &intel_encoder->base;
10400         struct drm_crtc *crtc = NULL;
10401         struct drm_device *dev = encoder->dev;
10402         struct drm_framebuffer *fb;
10403         struct drm_mode_config *config = &dev->mode_config;
10404         struct drm_atomic_state *state = NULL, *restore_state = NULL;
10405         struct drm_connector_state *connector_state;
10406         struct intel_crtc_state *crtc_state;
10407         int ret, i = -1;
10408
10409         DRM_DEBUG_KMS("[CONNECTOR:%d:%s], [ENCODER:%d:%s]\n",
10410                       connector->base.id, connector->name,
10411                       encoder->base.id, encoder->name);
10412
10413         old->restore_state = NULL;
10414
10415 retry:
10416         ret = drm_modeset_lock(&config->connection_mutex, ctx);
10417         if (ret)
10418                 goto fail;
10419
10420         /*
10421          * Algorithm gets a little messy:
10422          *
10423          *   - if the connector already has an assigned crtc, use it (but make
10424          *     sure it's on first)
10425          *
10426          *   - try to find the first unused crtc that can drive this connector,
10427          *     and use that if we find one
10428          */
10429
10430         /* See if we already have a CRTC for this connector */
10431         if (connector->state->crtc) {
10432                 crtc = connector->state->crtc;
10433
10434                 ret = drm_modeset_lock(&crtc->mutex, ctx);
10435                 if (ret)
10436                         goto fail;
10437
10438                 /* Make sure the crtc and connector are running */
10439                 goto found;
10440         }
10441
10442         /* Find an unused one (if possible) */
10443         for_each_crtc(dev, possible_crtc) {
10444                 i++;
10445                 if (!(encoder->possible_crtcs & (1 << i)))
10446                         continue;
10447
10448                 ret = drm_modeset_lock(&possible_crtc->mutex, ctx);
10449                 if (ret)
10450                         goto fail;
10451
10452                 if (possible_crtc->state->enable) {
10453                         drm_modeset_unlock(&possible_crtc->mutex);
10454                         continue;
10455                 }
10456
10457                 crtc = possible_crtc;
10458                 break;
10459         }
10460
10461         /*
10462          * If we didn't find an unused CRTC, don't use any.
10463          */
10464         if (!crtc) {
10465                 DRM_DEBUG_KMS("no pipe available for load-detect\n");
10466                 goto fail;
10467         }
10468
10469 found:
10470         intel_crtc = to_intel_crtc(crtc);
10471
10472         ret = drm_modeset_lock(&crtc->primary->mutex, ctx);
10473         if (ret)
10474                 goto fail;
10475
10476         state = drm_atomic_state_alloc(dev);
10477         restore_state = drm_atomic_state_alloc(dev);
10478         if (!state || !restore_state) {
10479                 ret = -ENOMEM;
10480                 goto fail;
10481         }
10482
10483         state->acquire_ctx = ctx;
10484         restore_state->acquire_ctx = ctx;
10485
10486         connector_state = drm_atomic_get_connector_state(state, connector);
10487         if (IS_ERR(connector_state)) {
10488                 ret = PTR_ERR(connector_state);
10489                 goto fail;
10490         }
10491
10492         ret = drm_atomic_set_crtc_for_connector(connector_state, crtc);
10493         if (ret)
10494                 goto fail;
10495
10496         crtc_state = intel_atomic_get_crtc_state(state, intel_crtc);
10497         if (IS_ERR(crtc_state)) {
10498                 ret = PTR_ERR(crtc_state);
10499                 goto fail;
10500         }
10501
10502         crtc_state->base.active = crtc_state->base.enable = true;
10503
10504         if (!mode)
10505                 mode = &load_detect_mode;
10506
10507         /* We need a framebuffer large enough to accommodate all accesses
10508          * that the plane may generate whilst we perform load detection.
10509          * We can not rely on the fbcon either being present (we get called
10510          * during its initialisation to detect all boot displays, or it may
10511          * not even exist) or that it is large enough to satisfy the
10512          * requested mode.
10513          */
10514         fb = mode_fits_in_fbdev(dev, mode);
10515         if (fb == NULL) {
10516                 DRM_DEBUG_KMS("creating tmp fb for load-detection\n");
10517                 fb = intel_framebuffer_create_for_mode(dev, mode, 24, 32);
10518         } else
10519                 DRM_DEBUG_KMS("reusing fbdev for load-detection framebuffer\n");
10520         if (IS_ERR(fb)) {
10521                 DRM_DEBUG_KMS("failed to allocate framebuffer for load-detection\n");
10522                 goto fail;
10523         }
10524
10525         ret = intel_modeset_setup_plane_state(state, crtc, mode, fb, 0, 0);
10526         if (ret)
10527                 goto fail;
10528
10529         drm_framebuffer_unreference(fb);
10530
10531         ret = drm_atomic_set_mode_for_crtc(&crtc_state->base, mode);
10532         if (ret)
10533                 goto fail;
10534
10535         ret = PTR_ERR_OR_ZERO(drm_atomic_get_connector_state(restore_state, connector));
10536         if (!ret)
10537                 ret = PTR_ERR_OR_ZERO(drm_atomic_get_crtc_state(restore_state, crtc));
10538         if (!ret)
10539                 ret = PTR_ERR_OR_ZERO(drm_atomic_get_plane_state(restore_state, crtc->primary));
10540         if (ret) {
10541                 DRM_DEBUG_KMS("Failed to create a copy of old state to restore: %i\n", ret);
10542                 goto fail;
10543         }
10544
10545         ret = drm_atomic_commit(state);
10546         if (ret) {
10547                 DRM_DEBUG_KMS("failed to set mode on load-detect pipe\n");
10548                 goto fail;
10549         }
10550
10551         old->restore_state = restore_state;
10552
10553         /* let the connector get through one full cycle before testing */
10554         intel_wait_for_vblank(dev, intel_crtc->pipe);
10555         return true;
10556
10557 fail:
10558         drm_atomic_state_free(state);
10559         drm_atomic_state_free(restore_state);
10560         restore_state = state = NULL;
10561
10562         if (ret == -EDEADLK) {
10563                 drm_modeset_backoff(ctx);
10564                 goto retry;
10565         }
10566
10567         return false;
10568 }
10569
10570 void intel_release_load_detect_pipe(struct drm_connector *connector,
10571                                     struct intel_load_detect_pipe *old,
10572                                     struct drm_modeset_acquire_ctx *ctx)
10573 {
10574         struct intel_encoder *intel_encoder =
10575                 intel_attached_encoder(connector);
10576         struct drm_encoder *encoder = &intel_encoder->base;
10577         struct drm_atomic_state *state = old->restore_state;
10578         int ret;
10579
10580         DRM_DEBUG_KMS("[CONNECTOR:%d:%s], [ENCODER:%d:%s]\n",
10581                       connector->base.id, connector->name,
10582                       encoder->base.id, encoder->name);
10583
10584         if (!state)
10585                 return;
10586
10587         ret = drm_atomic_commit(state);
10588         if (ret) {
10589                 DRM_DEBUG_KMS("Couldn't release load detect pipe: %i\n", ret);
10590                 drm_atomic_state_free(state);
10591         }
10592 }
10593
10594 static int i9xx_pll_refclk(struct drm_device *dev,
10595                            const struct intel_crtc_state *pipe_config)
10596 {
10597         struct drm_i915_private *dev_priv = dev->dev_private;
10598         u32 dpll = pipe_config->dpll_hw_state.dpll;
10599
10600         if ((dpll & PLL_REF_INPUT_MASK) == PLLB_REF_INPUT_SPREADSPECTRUMIN)
10601                 return dev_priv->vbt.lvds_ssc_freq;
10602         else if (HAS_PCH_SPLIT(dev))
10603                 return 120000;
10604         else if (!IS_GEN2(dev))
10605                 return 96000;
10606         else
10607                 return 48000;
10608 }
10609
10610 /* Returns the clock of the currently programmed mode of the given pipe. */
10611 static void i9xx_crtc_clock_get(struct intel_crtc *crtc,
10612                                 struct intel_crtc_state *pipe_config)
10613 {
10614         struct drm_device *dev = crtc->base.dev;
10615         struct drm_i915_private *dev_priv = dev->dev_private;
10616         int pipe = pipe_config->cpu_transcoder;
10617         u32 dpll = pipe_config->dpll_hw_state.dpll;
10618         u32 fp;
10619         struct dpll clock;
10620         int port_clock;
10621         int refclk = i9xx_pll_refclk(dev, pipe_config);
10622
10623         if ((dpll & DISPLAY_RATE_SELECT_FPA1) == 0)
10624                 fp = pipe_config->dpll_hw_state.fp0;
10625         else
10626                 fp = pipe_config->dpll_hw_state.fp1;
10627
10628         clock.m1 = (fp & FP_M1_DIV_MASK) >> FP_M1_DIV_SHIFT;
10629         if (IS_PINEVIEW(dev)) {
10630                 clock.n = ffs((fp & FP_N_PINEVIEW_DIV_MASK) >> FP_N_DIV_SHIFT) - 1;
10631                 clock.m2 = (fp & FP_M2_PINEVIEW_DIV_MASK) >> FP_M2_DIV_SHIFT;
10632         } else {
10633                 clock.n = (fp & FP_N_DIV_MASK) >> FP_N_DIV_SHIFT;
10634                 clock.m2 = (fp & FP_M2_DIV_MASK) >> FP_M2_DIV_SHIFT;
10635         }
10636
10637         if (!IS_GEN2(dev)) {
10638                 if (IS_PINEVIEW(dev))
10639                         clock.p1 = ffs((dpll & DPLL_FPA01_P1_POST_DIV_MASK_PINEVIEW) >>
10640                                 DPLL_FPA01_P1_POST_DIV_SHIFT_PINEVIEW);
10641                 else
10642                         clock.p1 = ffs((dpll & DPLL_FPA01_P1_POST_DIV_MASK) >>
10643                                DPLL_FPA01_P1_POST_DIV_SHIFT);
10644
10645                 switch (dpll & DPLL_MODE_MASK) {
10646                 case DPLLB_MODE_DAC_SERIAL:
10647                         clock.p2 = dpll & DPLL_DAC_SERIAL_P2_CLOCK_DIV_5 ?
10648                                 5 : 10;
10649                         break;
10650                 case DPLLB_MODE_LVDS:
10651                         clock.p2 = dpll & DPLLB_LVDS_P2_CLOCK_DIV_7 ?
10652                                 7 : 14;
10653                         break;
10654                 default:
10655                         DRM_DEBUG_KMS("Unknown DPLL mode %08x in programmed "
10656                                   "mode\n", (int)(dpll & DPLL_MODE_MASK));
10657                         return;
10658                 }
10659
10660                 if (IS_PINEVIEW(dev))
10661                         port_clock = pnv_calc_dpll_params(refclk, &clock);
10662                 else
10663                         port_clock = i9xx_calc_dpll_params(refclk, &clock);
10664         } else {
10665                 u32 lvds = IS_I830(dev) ? 0 : I915_READ(LVDS);
10666                 bool is_lvds = (pipe == 1) && (lvds & LVDS_PORT_EN);
10667
10668                 if (is_lvds) {
10669                         clock.p1 = ffs((dpll & DPLL_FPA01_P1_POST_DIV_MASK_I830_LVDS) >>
10670                                        DPLL_FPA01_P1_POST_DIV_SHIFT);
10671
10672                         if (lvds & LVDS_CLKB_POWER_UP)
10673                                 clock.p2 = 7;
10674                         else
10675                                 clock.p2 = 14;
10676                 } else {
10677                         if (dpll & PLL_P1_DIVIDE_BY_TWO)
10678                                 clock.p1 = 2;
10679                         else {
10680                                 clock.p1 = ((dpll & DPLL_FPA01_P1_POST_DIV_MASK_I830) >>
10681                                             DPLL_FPA01_P1_POST_DIV_SHIFT) + 2;
10682                         }
10683                         if (dpll & PLL_P2_DIVIDE_BY_4)
10684                                 clock.p2 = 4;
10685                         else
10686                                 clock.p2 = 2;
10687                 }
10688
10689                 port_clock = i9xx_calc_dpll_params(refclk, &clock);
10690         }
10691
10692         /*
10693          * This value includes pixel_multiplier. We will use
10694          * port_clock to compute adjusted_mode.crtc_clock in the
10695          * encoder's get_config() function.
10696          */
10697         pipe_config->port_clock = port_clock;
10698 }
10699
10700 int intel_dotclock_calculate(int link_freq,
10701                              const struct intel_link_m_n *m_n)
10702 {
10703         /*
10704          * The calculation for the data clock is:
10705          * pixel_clock = ((m/n)*(link_clock * nr_lanes))/bpp
10706          * But we want to avoid losing precison if possible, so:
10707          * pixel_clock = ((m * link_clock * nr_lanes)/(n*bpp))
10708          *
10709          * and the link clock is simpler:
10710          * link_clock = (m * link_clock) / n
10711          */
10712
10713         if (!m_n->link_n)
10714                 return 0;
10715
10716         return div_u64((u64)m_n->link_m * link_freq, m_n->link_n);
10717 }
10718
10719 static void ironlake_pch_clock_get(struct intel_crtc *crtc,
10720                                    struct intel_crtc_state *pipe_config)
10721 {
10722         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
10723
10724         /* read out port_clock from the DPLL */
10725         i9xx_crtc_clock_get(crtc, pipe_config);
10726
10727         /*
10728          * In case there is an active pipe without active ports,
10729          * we may need some idea for the dotclock anyway.
10730          * Calculate one based on the FDI configuration.
10731          */
10732         pipe_config->base.adjusted_mode.crtc_clock =
10733                 intel_dotclock_calculate(intel_fdi_link_freq(dev_priv, pipe_config),
10734                                          &pipe_config->fdi_m_n);
10735 }
10736
10737 /** Returns the currently programmed mode of the given pipe. */
10738 struct drm_display_mode *intel_crtc_mode_get(struct drm_device *dev,
10739                                              struct drm_crtc *crtc)
10740 {
10741         struct drm_i915_private *dev_priv = dev->dev_private;
10742         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
10743         enum transcoder cpu_transcoder = intel_crtc->config->cpu_transcoder;
10744         struct drm_display_mode *mode;
10745         struct intel_crtc_state *pipe_config;
10746         int htot = I915_READ(HTOTAL(cpu_transcoder));
10747         int hsync = I915_READ(HSYNC(cpu_transcoder));
10748         int vtot = I915_READ(VTOTAL(cpu_transcoder));
10749         int vsync = I915_READ(VSYNC(cpu_transcoder));
10750         enum pipe pipe = intel_crtc->pipe;
10751
10752         mode = kzalloc(sizeof(*mode), GFP_KERNEL);
10753         if (!mode)
10754                 return NULL;
10755
10756         pipe_config = kzalloc(sizeof(*pipe_config), GFP_KERNEL);
10757         if (!pipe_config) {
10758                 kfree(mode);
10759                 return NULL;
10760         }
10761
10762         /*
10763          * Construct a pipe_config sufficient for getting the clock info
10764          * back out of crtc_clock_get.
10765          *
10766          * Note, if LVDS ever uses a non-1 pixel multiplier, we'll need
10767          * to use a real value here instead.
10768          */
10769         pipe_config->cpu_transcoder = (enum transcoder) pipe;
10770         pipe_config->pixel_multiplier = 1;
10771         pipe_config->dpll_hw_state.dpll = I915_READ(DPLL(pipe));
10772         pipe_config->dpll_hw_state.fp0 = I915_READ(FP0(pipe));
10773         pipe_config->dpll_hw_state.fp1 = I915_READ(FP1(pipe));
10774         i9xx_crtc_clock_get(intel_crtc, pipe_config);
10775
10776         mode->clock = pipe_config->port_clock / pipe_config->pixel_multiplier;
10777         mode->hdisplay = (htot & 0xffff) + 1;
10778         mode->htotal = ((htot & 0xffff0000) >> 16) + 1;
10779         mode->hsync_start = (hsync & 0xffff) + 1;
10780         mode->hsync_end = ((hsync & 0xffff0000) >> 16) + 1;
10781         mode->vdisplay = (vtot & 0xffff) + 1;
10782         mode->vtotal = ((vtot & 0xffff0000) >> 16) + 1;
10783         mode->vsync_start = (vsync & 0xffff) + 1;
10784         mode->vsync_end = ((vsync & 0xffff0000) >> 16) + 1;
10785
10786         drm_mode_set_name(mode);
10787
10788         kfree(pipe_config);
10789
10790         return mode;
10791 }
10792
10793 void intel_mark_busy(struct drm_i915_private *dev_priv)
10794 {
10795         if (dev_priv->mm.busy)
10796                 return;
10797
10798         intel_runtime_pm_get(dev_priv);
10799         i915_update_gfx_val(dev_priv);
10800         if (INTEL_GEN(dev_priv) >= 6)
10801                 gen6_rps_busy(dev_priv);
10802         dev_priv->mm.busy = true;
10803 }
10804
10805 void intel_mark_idle(struct drm_i915_private *dev_priv)
10806 {
10807         if (!dev_priv->mm.busy)
10808                 return;
10809
10810         dev_priv->mm.busy = false;
10811
10812         if (INTEL_GEN(dev_priv) >= 6)
10813                 gen6_rps_idle(dev_priv);
10814
10815         intel_runtime_pm_put(dev_priv);
10816 }
10817
10818 void intel_free_flip_work(struct intel_flip_work *work)
10819 {
10820         kfree(work->old_connector_state);
10821         kfree(work->new_connector_state);
10822         kfree(work);
10823 }
10824
10825 static void intel_crtc_destroy(struct drm_crtc *crtc)
10826 {
10827         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
10828         struct drm_device *dev = crtc->dev;
10829         struct intel_flip_work *work;
10830
10831         spin_lock_irq(&dev->event_lock);
10832         while (!list_empty(&intel_crtc->flip_work)) {
10833                 work = list_first_entry(&intel_crtc->flip_work,
10834                                         struct intel_flip_work, head);
10835                 list_del_init(&work->head);
10836                 spin_unlock_irq(&dev->event_lock);
10837
10838                 cancel_work_sync(&work->mmio_work);
10839                 cancel_work_sync(&work->unpin_work);
10840                 intel_free_flip_work(work);
10841
10842                 spin_lock_irq(&dev->event_lock);
10843         }
10844         spin_unlock_irq(&dev->event_lock);
10845
10846         drm_crtc_cleanup(crtc);
10847
10848         kfree(intel_crtc);
10849 }
10850
10851 static void intel_crtc_post_flip_update(struct intel_flip_work *work,
10852                                         struct drm_crtc *crtc)
10853 {
10854         struct intel_crtc_state *crtc_state = work->new_crtc_state;
10855         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
10856
10857         if (crtc_state->disable_cxsr)
10858                 intel_crtc->wm.cxsr_allowed = true;
10859
10860         if (crtc_state->update_wm_post && crtc_state->base.active)
10861                 intel_update_watermarks(crtc);
10862
10863         if (work->num_planes > 0 &&
10864             work->old_plane_state[0]->base.plane == crtc->primary) {
10865                 struct intel_plane_state *plane_state =
10866                         work->new_plane_state[0];
10867
10868                 if (plane_state->visible &&
10869                     (needs_modeset(&crtc_state->base) ||
10870                      !work->old_plane_state[0]->visible))
10871                         intel_post_enable_primary(crtc);
10872         }
10873 }
10874
10875 static void intel_unpin_work_fn(struct work_struct *__work)
10876 {
10877         struct intel_flip_work *work =
10878                 container_of(__work, struct intel_flip_work, unpin_work);
10879         struct drm_crtc *crtc = work->old_crtc_state->base.crtc;
10880         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
10881         struct drm_device *dev = crtc->dev;
10882         struct drm_i915_private *dev_priv = dev->dev_private;
10883         int i;
10884
10885         if (work->fb_bits)
10886                 intel_frontbuffer_flip_complete(dev, work->fb_bits);
10887
10888         /*
10889          * Unless work->can_async_unpin is false, there's no way to ensure
10890          * that work->new_crtc_state contains valid memory during unpin
10891          * because intel_atomic_commit may free it before this runs.
10892          */
10893         if (!work->can_async_unpin) {
10894                 intel_crtc_post_flip_update(work, crtc);
10895
10896                 if (dev_priv->display.optimize_watermarks)
10897                         dev_priv->display.optimize_watermarks(work->new_crtc_state);
10898         }
10899
10900         if (work->fb_bits & to_intel_plane(crtc->primary)->frontbuffer_bit)
10901                 intel_fbc_post_update(intel_crtc);
10902
10903         if (work->put_power_domains)
10904                 modeset_put_power_domains(dev_priv, work->put_power_domains);
10905
10906         /* Make sure mmio work is completely finished before freeing all state here. */
10907         flush_work(&work->mmio_work);
10908
10909         if (!work->can_async_unpin &&
10910             (work->new_crtc_state->update_pipe ||
10911              needs_modeset(&work->new_crtc_state->base))) {
10912                 /* This must be called before work is unpinned for serialization. */
10913                 intel_modeset_verify_crtc(crtc, &work->old_crtc_state->base,
10914                                           &work->new_crtc_state->base);
10915
10916                 for (i = 0; i < work->num_new_connectors; i++) {
10917                         struct drm_connector_state *conn_state =
10918                                 work->new_connector_state[i];
10919                         struct drm_connector *con = conn_state->connector;
10920
10921                         WARN_ON(!con);
10922
10923                         intel_connector_verify_state(to_intel_connector(con),
10924                                                      conn_state);
10925                 }
10926         }
10927
10928         for (i = 0; i < work->num_old_connectors; i++) {
10929                 struct drm_connector_state *old_con_state =
10930                         work->old_connector_state[i];
10931                 struct drm_connector *con =
10932                         old_con_state->connector;
10933
10934                 con->funcs->atomic_destroy_state(con, old_con_state);
10935         }
10936
10937         if (!work->can_async_unpin || !list_empty(&work->head)) {
10938                 spin_lock_irq(&dev->event_lock);
10939                 WARN(list_empty(&work->head) != work->can_async_unpin,
10940                      "[CRTC:%i] Pin work %p async %i with %i planes, active %i -> %i ms %i\n",
10941                      crtc->base.id, work, work->can_async_unpin, work->num_planes,
10942                      work->old_crtc_state->base.active, work->new_crtc_state->base.active,
10943                      needs_modeset(&work->new_crtc_state->base));
10944
10945                 if (!list_empty(&work->head))
10946                         list_del(&work->head);
10947
10948                 wake_up_all(&dev_priv->pending_flip_queue);
10949                 spin_unlock_irq(&dev->event_lock);
10950         }
10951
10952         /* New crtc_state freed? */
10953         if (work->free_new_crtc_state)
10954                 intel_crtc_destroy_state(crtc, &work->new_crtc_state->base);
10955
10956         intel_crtc_destroy_state(crtc, &work->old_crtc_state->base);
10957
10958         for (i = 0; i < work->num_planes; i++) {
10959                 struct intel_plane_state *old_plane_state =
10960                         work->old_plane_state[i];
10961                 struct drm_framebuffer *old_fb = old_plane_state->base.fb;
10962                 struct drm_plane *plane = old_plane_state->base.plane;
10963                 struct drm_i915_gem_request *req;
10964
10965                 req = old_plane_state->wait_req;
10966                 old_plane_state->wait_req = NULL;
10967                 if (req)
10968                         i915_gem_request_unreference(req);
10969
10970                 fence_put(old_plane_state->base.fence);
10971                 old_plane_state->base.fence = NULL;
10972
10973                 if (old_fb &&
10974                     (plane->type != DRM_PLANE_TYPE_CURSOR ||
10975                      !INTEL_INFO(dev_priv)->cursor_needs_physical)) {
10976                         mutex_lock(&dev->struct_mutex);
10977                         intel_unpin_fb_obj(old_fb, old_plane_state->base.rotation);
10978                         mutex_unlock(&dev->struct_mutex);
10979                 }
10980
10981                 intel_plane_destroy_state(plane, &old_plane_state->base);
10982         }
10983
10984         if (!WARN_ON(atomic_read(&intel_crtc->unpin_work_count) == 0))
10985                 atomic_dec(&intel_crtc->unpin_work_count);
10986
10987         intel_free_flip_work(work);
10988 }
10989
10990
10991 static bool pageflip_finished(struct intel_crtc *crtc,
10992                               struct intel_flip_work *work)
10993 {
10994         if (!atomic_read(&work->pending))
10995                 return false;
10996
10997         smp_rmb();
10998
10999         /*
11000          * MMIO work completes when vblank is different from
11001          * flip_queued_vblank.
11002          */
11003         return intel_crtc_get_vblank_counter(crtc) != work->flip_queued_vblank;
11004 }
11005
11006 void intel_finish_page_flip_mmio(struct drm_i915_private *dev_priv, int pipe)
11007 {
11008         struct drm_device *dev = dev_priv->dev;
11009         struct drm_crtc *crtc = dev_priv->pipe_to_crtc_mapping[pipe];
11010         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
11011         struct intel_flip_work *work;
11012         unsigned long flags;
11013
11014         /* Ignore early vblank irqs */
11015         if (!crtc)
11016                 return;
11017
11018         /*
11019          * This is called both by irq handlers and the reset code (to complete
11020          * lost pageflips) so needs the full irqsave spinlocks.
11021          */
11022         spin_lock_irqsave(&dev->event_lock, flags);
11023         while (!list_empty(&intel_crtc->flip_work)) {
11024                 work = list_first_entry(&intel_crtc->flip_work,
11025                                         struct intel_flip_work,
11026                                         head);
11027
11028                 if (!pageflip_finished(intel_crtc, work) ||
11029                     work_busy(&work->unpin_work))
11030                         break;
11031
11032                 page_flip_completed(intel_crtc, work);
11033         }
11034         spin_unlock_irqrestore(&dev->event_lock, flags);
11035 }
11036
11037 static void intel_mmio_flip_work_func(struct work_struct *w)
11038 {
11039         struct intel_flip_work *work =
11040                 container_of(w, struct intel_flip_work, mmio_work);
11041         struct drm_crtc *crtc = work->old_crtc_state->base.crtc;
11042         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
11043         struct intel_crtc_state *crtc_state = work->new_crtc_state;
11044         struct drm_device *dev = crtc->dev;
11045         struct drm_i915_private *dev_priv = dev->dev_private;
11046         struct drm_i915_gem_request *req;
11047         int i, ret;
11048
11049         if (!needs_modeset(&crtc_state->base) && crtc_state->update_pipe) {
11050                 work->put_power_domains =
11051                         modeset_get_crtc_power_domains(crtc, crtc_state);
11052         }
11053
11054         for (i = 0; i < work->num_planes; i++) {
11055                 struct intel_plane_state *old_plane_state = work->old_plane_state[i];
11056
11057                 /* For framebuffer backed by dmabuf, wait for fence */
11058                 if (old_plane_state->base.fence)
11059                         WARN_ON(fence_wait(old_plane_state->base.fence, false) < 0);
11060
11061                 req = old_plane_state->wait_req;
11062                 if (!req)
11063                         continue;
11064
11065                 WARN_ON(__i915_wait_request(req, false, NULL,
11066                                             &dev_priv->rps.mmioflips));
11067         }
11068
11069         ret = drm_crtc_vblank_get(crtc);
11070         I915_STATE_WARN(ret < 0, "enabling vblank failed with %i\n", ret);
11071
11072         if (work->num_planes &&
11073             work->old_plane_state[0]->base.plane == crtc->primary)
11074                 intel_fbc_enable(intel_crtc, work->new_crtc_state, work->new_plane_state[0]);
11075
11076         intel_frontbuffer_flip_prepare(dev, work->fb_bits);
11077
11078         intel_pipe_update_start(intel_crtc);
11079         if (!needs_modeset(&crtc_state->base)) {
11080                 if (crtc_state->base.color_mgmt_changed || crtc_state->update_pipe) {
11081                         intel_color_set_csc(&crtc_state->base);
11082                         intel_color_load_luts(&crtc_state->base);
11083                 }
11084
11085                 if (crtc_state->update_pipe)
11086                         intel_update_pipe_config(intel_crtc, work->old_crtc_state);
11087                 else if (INTEL_INFO(dev)->gen >= 9)
11088                         skl_detach_scalers(intel_crtc);
11089         }
11090
11091         for (i = 0; i < work->num_planes; i++) {
11092                 struct intel_plane_state *new_plane_state = work->new_plane_state[i];
11093                 struct intel_plane *plane = to_intel_plane(new_plane_state->base.plane);
11094
11095                 if (new_plane_state->visible)
11096                         plane->update_plane(&plane->base, crtc_state, new_plane_state);
11097                 else
11098                         plane->disable_plane(&plane->base, crtc);
11099         }
11100
11101         intel_pipe_update_end(intel_crtc, work);
11102 }
11103
11104 /**
11105  * intel_wm_need_update - Check whether watermarks need updating
11106  * @plane: drm plane
11107  * @state: new plane state
11108  *
11109  * Check current plane state versus the new one to determine whether
11110  * watermarks need to be recalculated.
11111  *
11112  * Returns true or false.
11113  */
11114 static bool intel_wm_need_update(struct drm_plane *plane,
11115                                  struct drm_plane_state *state)
11116 {
11117         struct intel_plane_state *new = to_intel_plane_state(state);
11118         struct intel_plane_state *cur = to_intel_plane_state(plane->state);
11119
11120         /* Update watermarks on tiling or size changes. */
11121         if (new->visible != cur->visible)
11122                 return true;
11123
11124         if (!cur->base.fb || !new->base.fb)
11125                 return false;
11126
11127         if (cur->base.fb->modifier[0] != new->base.fb->modifier[0] ||
11128             cur->base.rotation != new->base.rotation ||
11129             drm_rect_width(&new->src) != drm_rect_width(&cur->src) ||
11130             drm_rect_height(&new->src) != drm_rect_height(&cur->src) ||
11131             drm_rect_width(&new->dst) != drm_rect_width(&cur->dst) ||
11132             drm_rect_height(&new->dst) != drm_rect_height(&cur->dst))
11133                 return true;
11134
11135         return false;
11136 }
11137
11138 static bool needs_scaling(struct intel_plane_state *state)
11139 {
11140         int src_w = drm_rect_width(&state->src) >> 16;
11141         int src_h = drm_rect_height(&state->src) >> 16;
11142         int dst_w = drm_rect_width(&state->dst);
11143         int dst_h = drm_rect_height(&state->dst);
11144
11145         return (src_w != dst_w || src_h != dst_h);
11146 }
11147
11148 int intel_plane_atomic_calc_changes(struct drm_crtc_state *crtc_state,
11149                                     struct drm_plane_state *plane_state)
11150 {
11151         struct intel_crtc_state *pipe_config = to_intel_crtc_state(crtc_state);
11152         struct drm_crtc *crtc = crtc_state->crtc;
11153         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
11154         struct drm_plane *plane = plane_state->plane;
11155         struct drm_device *dev = crtc->dev;
11156         struct drm_i915_private *dev_priv = to_i915(dev);
11157         struct intel_plane_state *old_plane_state =
11158                 to_intel_plane_state(plane->state);
11159         int idx = intel_crtc->base.base.id, ret;
11160         bool mode_changed = needs_modeset(crtc_state);
11161         bool was_crtc_enabled = crtc->state->active;
11162         bool is_crtc_enabled = crtc_state->active;
11163         bool turn_off, turn_on, visible, was_visible;
11164         struct drm_framebuffer *fb = plane_state->fb;
11165
11166         if (crtc_state && INTEL_INFO(dev)->gen >= 9 &&
11167             plane->type != DRM_PLANE_TYPE_CURSOR) {
11168                 ret = skl_update_scaler_plane(
11169                         to_intel_crtc_state(crtc_state),
11170                         to_intel_plane_state(plane_state));
11171                 if (ret)
11172                         return ret;
11173         }
11174
11175         was_visible = old_plane_state->visible;
11176         visible = to_intel_plane_state(plane_state)->visible;
11177
11178         if (!was_crtc_enabled && WARN_ON(was_visible))
11179                 was_visible = false;
11180
11181         /*
11182          * Visibility is calculated as if the crtc was on, but
11183          * after scaler setup everything depends on it being off
11184          * when the crtc isn't active.
11185          *
11186          * FIXME this is wrong for watermarks. Watermarks should also
11187          * be computed as if the pipe would be active. Perhaps move
11188          * per-plane wm computation to the .check_plane() hook, and
11189          * only combine the results from all planes in the current place?
11190          */
11191         if (!is_crtc_enabled)
11192                 to_intel_plane_state(plane_state)->visible = visible = false;
11193
11194         if (!was_visible && !visible)
11195                 return 0;
11196
11197         if (fb != old_plane_state->base.fb)
11198                 pipe_config->fb_changed = true;
11199
11200         turn_off = was_visible && (!visible || mode_changed);
11201         turn_on = visible && (!was_visible || mode_changed);
11202
11203         DRM_DEBUG_ATOMIC("[CRTC:%i] has [PLANE:%i] with fb %i\n", idx,
11204                          plane->base.id, fb ? fb->base.id : -1);
11205
11206         DRM_DEBUG_ATOMIC("[PLANE:%i] visible %i -> %i, off %i, on %i, ms %i\n",
11207                          plane->base.id, was_visible, visible,
11208                          turn_off, turn_on, mode_changed);
11209
11210         if (turn_on) {
11211                 pipe_config->update_wm_pre = true;
11212
11213                 /* must disable cxsr around plane enable/disable */
11214                 if (plane->type != DRM_PLANE_TYPE_CURSOR)
11215                         pipe_config->disable_cxsr = true;
11216         } else if (turn_off) {
11217                 pipe_config->update_wm_post = true;
11218
11219                 /* must disable cxsr around plane enable/disable */
11220                 if (plane->type != DRM_PLANE_TYPE_CURSOR)
11221                         pipe_config->disable_cxsr = true;
11222         } else if (intel_wm_need_update(plane, plane_state)) {
11223                 /* FIXME bollocks */
11224                 pipe_config->update_wm_pre = true;
11225                 pipe_config->update_wm_post = true;
11226         }
11227
11228         /* Pre-gen9 platforms need two-step watermark updates */
11229         if ((pipe_config->update_wm_pre || pipe_config->update_wm_post) &&
11230             INTEL_INFO(dev)->gen < 9 && dev_priv->display.optimize_watermarks)
11231                 to_intel_crtc_state(crtc_state)->wm.need_postvbl_update = true;
11232
11233         if (visible || was_visible)
11234                 pipe_config->fb_bits |= to_intel_plane(plane)->frontbuffer_bit;
11235
11236         /*
11237          * WaCxSRDisabledForSpriteScaling:ivb
11238          *
11239          * cstate->update_wm was already set above, so this flag will
11240          * take effect when we commit and program watermarks.
11241          */
11242         if (plane->type == DRM_PLANE_TYPE_OVERLAY && IS_IVYBRIDGE(dev) &&
11243             needs_scaling(to_intel_plane_state(plane_state)) &&
11244             !needs_scaling(old_plane_state))
11245                 pipe_config->disable_lp_wm = true;
11246
11247         return 0;
11248 }
11249
11250 static bool encoders_cloneable(const struct intel_encoder *a,
11251                                const struct intel_encoder *b)
11252 {
11253         /* masks could be asymmetric, so check both ways */
11254         return a == b || (a->cloneable & (1 << b->type) &&
11255                           b->cloneable & (1 << a->type));
11256 }
11257
11258 static bool check_single_encoder_cloning(struct drm_atomic_state *state,
11259                                          struct intel_crtc *crtc,
11260                                          struct intel_encoder *encoder)
11261 {
11262         struct intel_encoder *source_encoder;
11263         struct drm_connector *connector;
11264         struct drm_connector_state *connector_state;
11265         int i;
11266
11267         for_each_connector_in_state(state, connector, connector_state, i) {
11268                 if (connector_state->crtc != &crtc->base)
11269                         continue;
11270
11271                 source_encoder =
11272                         to_intel_encoder(connector_state->best_encoder);
11273                 if (!encoders_cloneable(encoder, source_encoder))
11274                         return false;
11275         }
11276
11277         return true;
11278 }
11279
11280 static bool check_encoder_cloning(struct drm_atomic_state *state,
11281                                   struct intel_crtc *crtc)
11282 {
11283         struct intel_encoder *encoder;
11284         struct drm_connector *connector;
11285         struct drm_connector_state *connector_state;
11286         int i;
11287
11288         for_each_connector_in_state(state, connector, connector_state, i) {
11289                 if (connector_state->crtc != &crtc->base)
11290                         continue;
11291
11292                 encoder = to_intel_encoder(connector_state->best_encoder);
11293                 if (!check_single_encoder_cloning(state, crtc, encoder))
11294                         return false;
11295         }
11296
11297         return true;
11298 }
11299
11300 static int intel_crtc_atomic_check(struct drm_crtc *crtc,
11301                                    struct drm_crtc_state *crtc_state)
11302 {
11303         struct drm_device *dev = crtc->dev;
11304         struct drm_i915_private *dev_priv = dev->dev_private;
11305         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
11306         struct intel_crtc_state *pipe_config =
11307                 to_intel_crtc_state(crtc_state);
11308         struct drm_atomic_state *state = crtc_state->state;
11309         int ret;
11310         bool mode_changed = needs_modeset(crtc_state);
11311
11312         if (mode_changed && !check_encoder_cloning(state, intel_crtc)) {
11313                 DRM_DEBUG_KMS("rejecting invalid cloning configuration\n");
11314                 return -EINVAL;
11315         }
11316
11317         if (mode_changed && !crtc_state->active)
11318                 pipe_config->update_wm_post = true;
11319
11320         if (mode_changed && crtc_state->enable &&
11321             dev_priv->display.crtc_compute_clock &&
11322             !WARN_ON(pipe_config->shared_dpll)) {
11323                 ret = dev_priv->display.crtc_compute_clock(intel_crtc,
11324                                                            pipe_config);
11325                 if (ret)
11326                         return ret;
11327         }
11328
11329         if (crtc_state->color_mgmt_changed) {
11330                 ret = intel_color_check(crtc, crtc_state);
11331                 if (ret)
11332                         return ret;
11333         }
11334
11335         ret = 0;
11336         if (dev_priv->display.compute_pipe_wm) {
11337                 ret = dev_priv->display.compute_pipe_wm(pipe_config);
11338                 if (ret) {
11339                         DRM_DEBUG_KMS("Target pipe watermarks are invalid\n");
11340                         return ret;
11341                 }
11342         }
11343
11344         if (dev_priv->display.compute_intermediate_wm &&
11345             !to_intel_atomic_state(state)->skip_intermediate_wm) {
11346                 if (WARN_ON(!dev_priv->display.compute_pipe_wm))
11347                         return 0;
11348
11349                 /*
11350                  * Calculate 'intermediate' watermarks that satisfy both the
11351                  * old state and the new state.  We can program these
11352                  * immediately.
11353                  */
11354                 ret = dev_priv->display.compute_intermediate_wm(crtc->dev,
11355                                                                 intel_crtc,
11356                                                                 pipe_config);
11357                 if (ret) {
11358                         DRM_DEBUG_KMS("No valid intermediate pipe watermarks are possible\n");
11359                         return ret;
11360                 }
11361         } else if (dev_priv->display.compute_intermediate_wm) {
11362                 if (HAS_PCH_SPLIT(dev_priv) && INTEL_GEN(dev_priv) < 9)
11363                         pipe_config->wm.ilk.intermediate = pipe_config->wm.ilk.optimal;
11364         }
11365
11366         if (INTEL_INFO(dev)->gen >= 9) {
11367                 if (mode_changed)
11368                         ret = skl_update_scaler_crtc(pipe_config);
11369
11370                 if (!ret)
11371                         ret = intel_atomic_setup_scalers(dev, intel_crtc,
11372                                                          pipe_config);
11373         }
11374
11375         return ret;
11376 }
11377
11378 static const struct drm_crtc_helper_funcs intel_helper_funcs = {
11379         .mode_set_base_atomic = intel_pipe_set_base_atomic,
11380         .atomic_check = intel_crtc_atomic_check,
11381 };
11382
11383 static void intel_modeset_update_connector_atomic_state(struct drm_device *dev)
11384 {
11385         struct intel_connector *connector;
11386
11387         for_each_intel_connector(dev, connector) {
11388                 if (connector->base.state->crtc)
11389                         drm_connector_unreference(&connector->base);
11390
11391                 if (connector->base.encoder) {
11392                         connector->base.state->best_encoder =
11393                                 connector->base.encoder;
11394                         connector->base.state->crtc =
11395                                 connector->base.encoder->crtc;
11396
11397                         drm_connector_reference(&connector->base);
11398                 } else {
11399                         connector->base.state->best_encoder = NULL;
11400                         connector->base.state->crtc = NULL;
11401                 }
11402         }
11403 }
11404
11405 static void
11406 connected_sink_compute_bpp(struct intel_connector *connector,
11407                            struct intel_crtc_state *pipe_config)
11408 {
11409         int bpp = pipe_config->pipe_bpp;
11410
11411         DRM_DEBUG_KMS("[CONNECTOR:%d:%s] checking for sink bpp constrains\n",
11412                 connector->base.base.id,
11413                 connector->base.name);
11414
11415         /* Don't use an invalid EDID bpc value */
11416         if (connector->base.display_info.bpc &&
11417             connector->base.display_info.bpc * 3 < bpp) {
11418                 DRM_DEBUG_KMS("clamping display bpp (was %d) to EDID reported max of %d\n",
11419                               bpp, connector->base.display_info.bpc*3);
11420                 pipe_config->pipe_bpp = connector->base.display_info.bpc*3;
11421         }
11422
11423         /* Clamp bpp to default limit on screens without EDID 1.4 */
11424         if (connector->base.display_info.bpc == 0) {
11425                 int type = connector->base.connector_type;
11426                 int clamp_bpp = 24;
11427
11428                 /* Fall back to 18 bpp when DP sink capability is unknown. */
11429                 if (type == DRM_MODE_CONNECTOR_DisplayPort ||
11430                     type == DRM_MODE_CONNECTOR_eDP)
11431                         clamp_bpp = 18;
11432
11433                 if (bpp > clamp_bpp) {
11434                         DRM_DEBUG_KMS("clamping display bpp (was %d) to default limit of %d\n",
11435                                       bpp, clamp_bpp);
11436                         pipe_config->pipe_bpp = clamp_bpp;
11437                 }
11438         }
11439 }
11440
11441 static int
11442 compute_baseline_pipe_bpp(struct intel_crtc *crtc,
11443                           struct intel_crtc_state *pipe_config)
11444 {
11445         struct drm_device *dev = crtc->base.dev;
11446         struct drm_atomic_state *state;
11447         struct drm_connector *connector;
11448         struct drm_connector_state *connector_state;
11449         int bpp, i;
11450
11451         if ((IS_G4X(dev) || IS_VALLEYVIEW(dev) || IS_CHERRYVIEW(dev)))
11452                 bpp = 10*3;
11453         else if (INTEL_INFO(dev)->gen >= 5)
11454                 bpp = 12*3;
11455         else
11456                 bpp = 8*3;
11457
11458
11459         pipe_config->pipe_bpp = bpp;
11460
11461         state = pipe_config->base.state;
11462
11463         /* Clamp display bpp to EDID value */
11464         for_each_connector_in_state(state, connector, connector_state, i) {
11465                 if (connector_state->crtc != &crtc->base)
11466                         continue;
11467
11468                 connected_sink_compute_bpp(to_intel_connector(connector),
11469                                            pipe_config);
11470         }
11471
11472         return bpp;
11473 }
11474
11475 static void intel_dump_crtc_timings(const struct drm_display_mode *mode)
11476 {
11477         DRM_DEBUG_KMS("crtc timings: %d %d %d %d %d %d %d %d %d, "
11478                         "type: 0x%x flags: 0x%x\n",
11479                 mode->crtc_clock,
11480                 mode->crtc_hdisplay, mode->crtc_hsync_start,
11481                 mode->crtc_hsync_end, mode->crtc_htotal,
11482                 mode->crtc_vdisplay, mode->crtc_vsync_start,
11483                 mode->crtc_vsync_end, mode->crtc_vtotal, mode->type, mode->flags);
11484 }
11485
11486 static void intel_dump_pipe_config(struct intel_crtc *crtc,
11487                                    struct intel_crtc_state *pipe_config,
11488                                    const char *context)
11489 {
11490         struct drm_device *dev = crtc->base.dev;
11491         struct drm_plane *plane;
11492         struct intel_plane *intel_plane;
11493         struct intel_plane_state *state;
11494         struct drm_framebuffer *fb;
11495
11496         DRM_DEBUG_KMS("[CRTC:%d]%s config %p for pipe %c\n", crtc->base.base.id,
11497                       context, pipe_config, pipe_name(crtc->pipe));
11498
11499         DRM_DEBUG_KMS("cpu_transcoder: %s\n", transcoder_name(pipe_config->cpu_transcoder));
11500         DRM_DEBUG_KMS("pipe bpp: %i, dithering: %i\n",
11501                       pipe_config->pipe_bpp, pipe_config->dither);
11502         DRM_DEBUG_KMS("fdi/pch: %i, lanes: %i, gmch_m: %u, gmch_n: %u, link_m: %u, link_n: %u, tu: %u\n",
11503                       pipe_config->has_pch_encoder,
11504                       pipe_config->fdi_lanes,
11505                       pipe_config->fdi_m_n.gmch_m, pipe_config->fdi_m_n.gmch_n,
11506                       pipe_config->fdi_m_n.link_m, pipe_config->fdi_m_n.link_n,
11507                       pipe_config->fdi_m_n.tu);
11508         DRM_DEBUG_KMS("dp: %i, lanes: %i, gmch_m: %u, gmch_n: %u, link_m: %u, link_n: %u, tu: %u\n",
11509                       pipe_config->has_dp_encoder,
11510                       pipe_config->lane_count,
11511                       pipe_config->dp_m_n.gmch_m, pipe_config->dp_m_n.gmch_n,
11512                       pipe_config->dp_m_n.link_m, pipe_config->dp_m_n.link_n,
11513                       pipe_config->dp_m_n.tu);
11514
11515         DRM_DEBUG_KMS("dp: %i, lanes: %i, gmch_m2: %u, gmch_n2: %u, link_m2: %u, link_n2: %u, tu2: %u\n",
11516                       pipe_config->has_dp_encoder,
11517                       pipe_config->lane_count,
11518                       pipe_config->dp_m2_n2.gmch_m,
11519                       pipe_config->dp_m2_n2.gmch_n,
11520                       pipe_config->dp_m2_n2.link_m,
11521                       pipe_config->dp_m2_n2.link_n,
11522                       pipe_config->dp_m2_n2.tu);
11523
11524         DRM_DEBUG_KMS("audio: %i, infoframes: %i\n",
11525                       pipe_config->has_audio,
11526                       pipe_config->has_infoframe);
11527
11528         DRM_DEBUG_KMS("requested mode:\n");
11529         drm_mode_debug_printmodeline(&pipe_config->base.mode);
11530         DRM_DEBUG_KMS("adjusted mode:\n");
11531         drm_mode_debug_printmodeline(&pipe_config->base.adjusted_mode);
11532         intel_dump_crtc_timings(&pipe_config->base.adjusted_mode);
11533         DRM_DEBUG_KMS("port clock: %d\n", pipe_config->port_clock);
11534         DRM_DEBUG_KMS("pipe src size: %dx%d\n",
11535                       pipe_config->pipe_src_w, pipe_config->pipe_src_h);
11536         DRM_DEBUG_KMS("num_scalers: %d, scaler_users: 0x%x, scaler_id: %d\n",
11537                       crtc->num_scalers,
11538                       pipe_config->scaler_state.scaler_users,
11539                       pipe_config->scaler_state.scaler_id);
11540         DRM_DEBUG_KMS("gmch pfit: control: 0x%08x, ratios: 0x%08x, lvds border: 0x%08x\n",
11541                       pipe_config->gmch_pfit.control,
11542                       pipe_config->gmch_pfit.pgm_ratios,
11543                       pipe_config->gmch_pfit.lvds_border_bits);
11544         DRM_DEBUG_KMS("pch pfit: pos: 0x%08x, size: 0x%08x, %s\n",
11545                       pipe_config->pch_pfit.pos,
11546                       pipe_config->pch_pfit.size,
11547                       pipe_config->pch_pfit.enabled ? "enabled" : "disabled");
11548         DRM_DEBUG_KMS("ips: %i\n", pipe_config->ips_enabled);
11549         DRM_DEBUG_KMS("double wide: %i\n", pipe_config->double_wide);
11550
11551         if (IS_BROXTON(dev)) {
11552                 DRM_DEBUG_KMS("ddi_pll_sel: %u; dpll_hw_state: ebb0: 0x%x, ebb4: 0x%x,"
11553                               "pll0: 0x%x, pll1: 0x%x, pll2: 0x%x, pll3: 0x%x, "
11554                               "pll6: 0x%x, pll8: 0x%x, pll9: 0x%x, pll10: 0x%x, pcsdw12: 0x%x\n",
11555                               pipe_config->ddi_pll_sel,
11556                               pipe_config->dpll_hw_state.ebb0,
11557                               pipe_config->dpll_hw_state.ebb4,
11558                               pipe_config->dpll_hw_state.pll0,
11559                               pipe_config->dpll_hw_state.pll1,
11560                               pipe_config->dpll_hw_state.pll2,
11561                               pipe_config->dpll_hw_state.pll3,
11562                               pipe_config->dpll_hw_state.pll6,
11563                               pipe_config->dpll_hw_state.pll8,
11564                               pipe_config->dpll_hw_state.pll9,
11565                               pipe_config->dpll_hw_state.pll10,
11566                               pipe_config->dpll_hw_state.pcsdw12);
11567         } else if (IS_SKYLAKE(dev) || IS_KABYLAKE(dev)) {
11568                 DRM_DEBUG_KMS("ddi_pll_sel: %u; dpll_hw_state: "
11569                               "ctrl1: 0x%x, cfgcr1: 0x%x, cfgcr2: 0x%x\n",
11570                               pipe_config->ddi_pll_sel,
11571                               pipe_config->dpll_hw_state.ctrl1,
11572                               pipe_config->dpll_hw_state.cfgcr1,
11573                               pipe_config->dpll_hw_state.cfgcr2);
11574         } else if (HAS_DDI(dev)) {
11575                 DRM_DEBUG_KMS("ddi_pll_sel: 0x%x; dpll_hw_state: wrpll: 0x%x spll: 0x%x\n",
11576                               pipe_config->ddi_pll_sel,
11577                               pipe_config->dpll_hw_state.wrpll,
11578                               pipe_config->dpll_hw_state.spll);
11579         } else {
11580                 DRM_DEBUG_KMS("dpll_hw_state: dpll: 0x%x, dpll_md: 0x%x, "
11581                               "fp0: 0x%x, fp1: 0x%x\n",
11582                               pipe_config->dpll_hw_state.dpll,
11583                               pipe_config->dpll_hw_state.dpll_md,
11584                               pipe_config->dpll_hw_state.fp0,
11585                               pipe_config->dpll_hw_state.fp1);
11586         }
11587
11588         DRM_DEBUG_KMS("planes on this crtc\n");
11589         list_for_each_entry(plane, &dev->mode_config.plane_list, head) {
11590                 intel_plane = to_intel_plane(plane);
11591                 if (intel_plane->pipe != crtc->pipe)
11592                         continue;
11593
11594                 state = to_intel_plane_state(plane->state);
11595                 fb = state->base.fb;
11596                 if (!fb) {
11597                         DRM_DEBUG_KMS("%s PLANE:%d plane: %u.%u idx: %d "
11598                                 "disabled, scaler_id = %d\n",
11599                                 plane->type == DRM_PLANE_TYPE_CURSOR ? "CURSOR" : "STANDARD",
11600                                 plane->base.id, intel_plane->pipe,
11601                                 (crtc->base.primary == plane) ? 0 : intel_plane->plane + 1,
11602                                 drm_plane_index(plane), state->scaler_id);
11603                         continue;
11604                 }
11605
11606                 DRM_DEBUG_KMS("%s PLANE:%d plane: %u.%u idx: %d enabled",
11607                         plane->type == DRM_PLANE_TYPE_CURSOR ? "CURSOR" : "STANDARD",
11608                         plane->base.id, intel_plane->pipe,
11609                         crtc->base.primary == plane ? 0 : intel_plane->plane + 1,
11610                         drm_plane_index(plane));
11611                 DRM_DEBUG_KMS("\tFB:%d, fb = %ux%u format = 0x%x",
11612                         fb->base.id, fb->width, fb->height, fb->pixel_format);
11613                 DRM_DEBUG_KMS("\tscaler:%d src (%u, %u) %ux%u dst (%u, %u) %ux%u\n",
11614                         state->scaler_id,
11615                         state->src.x1 >> 16, state->src.y1 >> 16,
11616                         drm_rect_width(&state->src) >> 16,
11617                         drm_rect_height(&state->src) >> 16,
11618                         state->dst.x1, state->dst.y1,
11619                         drm_rect_width(&state->dst), drm_rect_height(&state->dst));
11620         }
11621 }
11622
11623 static bool check_digital_port_conflicts(struct drm_atomic_state *state)
11624 {
11625         struct drm_device *dev = state->dev;
11626         struct drm_connector *connector;
11627         unsigned int used_ports = 0;
11628
11629         /*
11630          * Walk the connector list instead of the encoder
11631          * list to detect the problem on ddi platforms
11632          * where there's just one encoder per digital port.
11633          */
11634         drm_for_each_connector(connector, dev) {
11635                 struct drm_connector_state *connector_state;
11636                 struct intel_encoder *encoder;
11637
11638                 connector_state = drm_atomic_get_existing_connector_state(state, connector);
11639                 if (!connector_state)
11640                         connector_state = connector->state;
11641
11642                 if (!connector_state->best_encoder)
11643                         continue;
11644
11645                 encoder = to_intel_encoder(connector_state->best_encoder);
11646
11647                 WARN_ON(!connector_state->crtc);
11648
11649                 switch (encoder->type) {
11650                         unsigned int port_mask;
11651                 case INTEL_OUTPUT_UNKNOWN:
11652                         if (WARN_ON(!HAS_DDI(dev)))
11653                                 break;
11654                 case INTEL_OUTPUT_DISPLAYPORT:
11655                 case INTEL_OUTPUT_HDMI:
11656                 case INTEL_OUTPUT_EDP:
11657                         port_mask = 1 << enc_to_dig_port(&encoder->base)->port;
11658
11659                         /* the same port mustn't appear more than once */
11660                         if (used_ports & port_mask)
11661                                 return false;
11662
11663                         used_ports |= port_mask;
11664                 default:
11665                         break;
11666                 }
11667         }
11668
11669         return true;
11670 }
11671
11672 static void
11673 clear_intel_crtc_state(struct intel_crtc_state *crtc_state)
11674 {
11675         struct drm_crtc_state tmp_state;
11676         struct intel_crtc_scaler_state scaler_state;
11677         struct intel_dpll_hw_state dpll_hw_state;
11678         struct intel_shared_dpll *shared_dpll;
11679         uint32_t ddi_pll_sel;
11680         bool force_thru;
11681
11682         /* FIXME: before the switch to atomic started, a new pipe_config was
11683          * kzalloc'd. Code that depends on any field being zero should be
11684          * fixed, so that the crtc_state can be safely duplicated. For now,
11685          * only fields that are know to not cause problems are preserved. */
11686
11687         tmp_state = crtc_state->base;
11688         scaler_state = crtc_state->scaler_state;
11689         shared_dpll = crtc_state->shared_dpll;
11690         dpll_hw_state = crtc_state->dpll_hw_state;
11691         ddi_pll_sel = crtc_state->ddi_pll_sel;
11692         force_thru = crtc_state->pch_pfit.force_thru;
11693
11694         memset(crtc_state, 0, sizeof *crtc_state);
11695
11696         crtc_state->base = tmp_state;
11697         crtc_state->scaler_state = scaler_state;
11698         crtc_state->shared_dpll = shared_dpll;
11699         crtc_state->dpll_hw_state = dpll_hw_state;
11700         crtc_state->ddi_pll_sel = ddi_pll_sel;
11701         crtc_state->pch_pfit.force_thru = force_thru;
11702 }
11703
11704 static int
11705 intel_modeset_pipe_config(struct drm_crtc *crtc,
11706                           struct intel_crtc_state *pipe_config)
11707 {
11708         struct drm_atomic_state *state = pipe_config->base.state;
11709         struct intel_encoder *encoder;
11710         struct drm_connector *connector;
11711         struct drm_connector_state *connector_state;
11712         int base_bpp, ret = -EINVAL;
11713         int i;
11714         bool retry = true;
11715
11716         clear_intel_crtc_state(pipe_config);
11717
11718         pipe_config->cpu_transcoder =
11719                 (enum transcoder) to_intel_crtc(crtc)->pipe;
11720
11721         /*
11722          * Sanitize sync polarity flags based on requested ones. If neither
11723          * positive or negative polarity is requested, treat this as meaning
11724          * negative polarity.
11725          */
11726         if (!(pipe_config->base.adjusted_mode.flags &
11727               (DRM_MODE_FLAG_PHSYNC | DRM_MODE_FLAG_NHSYNC)))
11728                 pipe_config->base.adjusted_mode.flags |= DRM_MODE_FLAG_NHSYNC;
11729
11730         if (!(pipe_config->base.adjusted_mode.flags &
11731               (DRM_MODE_FLAG_PVSYNC | DRM_MODE_FLAG_NVSYNC)))
11732                 pipe_config->base.adjusted_mode.flags |= DRM_MODE_FLAG_NVSYNC;
11733
11734         base_bpp = compute_baseline_pipe_bpp(to_intel_crtc(crtc),
11735                                              pipe_config);
11736         if (base_bpp < 0)
11737                 goto fail;
11738
11739         /*
11740          * Determine the real pipe dimensions. Note that stereo modes can
11741          * increase the actual pipe size due to the frame doubling and
11742          * insertion of additional space for blanks between the frame. This
11743          * is stored in the crtc timings. We use the requested mode to do this
11744          * computation to clearly distinguish it from the adjusted mode, which
11745          * can be changed by the connectors in the below retry loop.
11746          */
11747         drm_crtc_get_hv_timing(&pipe_config->base.mode,
11748                                &pipe_config->pipe_src_w,
11749                                &pipe_config->pipe_src_h);
11750
11751 encoder_retry:
11752         /* Ensure the port clock defaults are reset when retrying. */
11753         pipe_config->port_clock = 0;
11754         pipe_config->pixel_multiplier = 1;
11755
11756         /* Fill in default crtc timings, allow encoders to overwrite them. */
11757         drm_mode_set_crtcinfo(&pipe_config->base.adjusted_mode,
11758                               CRTC_STEREO_DOUBLE);
11759
11760         /* Pass our mode to the connectors and the CRTC to give them a chance to
11761          * adjust it according to limitations or connector properties, and also
11762          * a chance to reject the mode entirely.
11763          */
11764         for_each_connector_in_state(state, connector, connector_state, i) {
11765                 if (connector_state->crtc != crtc)
11766                         continue;
11767
11768                 encoder = to_intel_encoder(connector_state->best_encoder);
11769
11770                 if (!(encoder->compute_config(encoder, pipe_config))) {
11771                         DRM_DEBUG_KMS("Encoder config failure\n");
11772                         goto fail;
11773                 }
11774         }
11775
11776         /* Set default port clock if not overwritten by the encoder. Needs to be
11777          * done afterwards in case the encoder adjusts the mode. */
11778         if (!pipe_config->port_clock)
11779                 pipe_config->port_clock = pipe_config->base.adjusted_mode.crtc_clock
11780                         * pipe_config->pixel_multiplier;
11781
11782         ret = intel_crtc_compute_config(to_intel_crtc(crtc), pipe_config);
11783         if (ret < 0) {
11784                 DRM_DEBUG_KMS("CRTC fixup failed\n");
11785                 goto fail;
11786         }
11787
11788         if (ret == RETRY) {
11789                 if (WARN(!retry, "loop in pipe configuration computation\n")) {
11790                         ret = -EINVAL;
11791                         goto fail;
11792                 }
11793
11794                 DRM_DEBUG_KMS("CRTC bw constrained, retrying\n");
11795                 retry = false;
11796                 goto encoder_retry;
11797         }
11798
11799         /* Dithering seems to not pass-through bits correctly when it should, so
11800          * only enable it on 6bpc panels. */
11801         pipe_config->dither = pipe_config->pipe_bpp == 6*3;
11802         DRM_DEBUG_KMS("hw max bpp: %i, pipe bpp: %i, dithering: %i\n",
11803                       base_bpp, pipe_config->pipe_bpp, pipe_config->dither);
11804
11805 fail:
11806         return ret;
11807 }
11808
11809 static void
11810 intel_modeset_update_crtc_state(struct drm_atomic_state *state)
11811 {
11812         struct drm_crtc *crtc;
11813         struct drm_crtc_state *crtc_state;
11814         int i;
11815
11816         /* Double check state. */
11817         for_each_crtc_in_state(state, crtc, crtc_state, i) {
11818                 to_intel_crtc(crtc)->config = to_intel_crtc_state(crtc->state);
11819
11820                 /* Update hwmode for vblank functions */
11821                 if (crtc->state->active)
11822                         crtc->hwmode = crtc->state->adjusted_mode;
11823                 else
11824                         crtc->hwmode.crtc_clock = 0;
11825
11826                 /*
11827                  * Update legacy state to satisfy fbc code. This can
11828                  * be removed when fbc uses the atomic state.
11829                  */
11830                 if (drm_atomic_get_existing_plane_state(state, crtc->primary)) {
11831                         struct drm_plane_state *plane_state = crtc->primary->state;
11832
11833                         crtc->primary->fb = plane_state->fb;
11834                         crtc->x = plane_state->src_x >> 16;
11835                         crtc->y = plane_state->src_y >> 16;
11836                 }
11837         }
11838 }
11839
11840 static bool intel_fuzzy_clock_check(int clock1, int clock2)
11841 {
11842         int diff;
11843
11844         if (clock1 == clock2)
11845                 return true;
11846
11847         if (!clock1 || !clock2)
11848                 return false;
11849
11850         diff = abs(clock1 - clock2);
11851
11852         if (((((diff + clock1 + clock2) * 100)) / (clock1 + clock2)) < 105)
11853                 return true;
11854
11855         return false;
11856 }
11857
11858 #define for_each_intel_crtc_masked(dev, mask, intel_crtc) \
11859         list_for_each_entry((intel_crtc), \
11860                             &(dev)->mode_config.crtc_list, \
11861                             base.head) \
11862                 for_each_if (mask & (1 <<(intel_crtc)->pipe))
11863
11864 static bool
11865 intel_compare_m_n(unsigned int m, unsigned int n,
11866                   unsigned int m2, unsigned int n2,
11867                   bool exact)
11868 {
11869         if (m == m2 && n == n2)
11870                 return true;
11871
11872         if (exact || !m || !n || !m2 || !n2)
11873                 return false;
11874
11875         BUILD_BUG_ON(DATA_LINK_M_N_MASK > INT_MAX);
11876
11877         if (n > n2) {
11878                 while (n > n2) {
11879                         m2 <<= 1;
11880                         n2 <<= 1;
11881                 }
11882         } else if (n < n2) {
11883                 while (n < n2) {
11884                         m <<= 1;
11885                         n <<= 1;
11886                 }
11887         }
11888
11889         if (n != n2)
11890                 return false;
11891
11892         return intel_fuzzy_clock_check(m, m2);
11893 }
11894
11895 static bool
11896 intel_compare_link_m_n(const struct intel_link_m_n *m_n,
11897                        struct intel_link_m_n *m2_n2,
11898                        bool adjust)
11899 {
11900         if (m_n->tu == m2_n2->tu &&
11901             intel_compare_m_n(m_n->gmch_m, m_n->gmch_n,
11902                               m2_n2->gmch_m, m2_n2->gmch_n, !adjust) &&
11903             intel_compare_m_n(m_n->link_m, m_n->link_n,
11904                               m2_n2->link_m, m2_n2->link_n, !adjust)) {
11905                 if (adjust)
11906                         *m2_n2 = *m_n;
11907
11908                 return true;
11909         }
11910
11911         return false;
11912 }
11913
11914 static bool
11915 intel_pipe_config_compare(struct drm_device *dev,
11916                           struct intel_crtc_state *current_config,
11917                           struct intel_crtc_state *pipe_config,
11918                           bool adjust)
11919 {
11920         bool ret = true;
11921
11922 #define INTEL_ERR_OR_DBG_KMS(fmt, ...) \
11923         do { \
11924                 if (!adjust) \
11925                         DRM_ERROR(fmt, ##__VA_ARGS__); \
11926                 else \
11927                         DRM_DEBUG_KMS(fmt, ##__VA_ARGS__); \
11928         } while (0)
11929
11930 #define PIPE_CONF_CHECK_X(name) \
11931         if (current_config->name != pipe_config->name) { \
11932                 INTEL_ERR_OR_DBG_KMS("mismatch in " #name " " \
11933                           "(expected 0x%08x, found 0x%08x)\n", \
11934                           current_config->name, \
11935                           pipe_config->name); \
11936                 ret = false; \
11937         }
11938
11939 #define PIPE_CONF_CHECK_I(name) \
11940         if (current_config->name != pipe_config->name) { \
11941                 INTEL_ERR_OR_DBG_KMS("mismatch in " #name " " \
11942                           "(expected %i, found %i)\n", \
11943                           current_config->name, \
11944                           pipe_config->name); \
11945                 ret = false; \
11946         }
11947
11948 #define PIPE_CONF_CHECK_P(name) \
11949         if (current_config->name != pipe_config->name) { \
11950                 INTEL_ERR_OR_DBG_KMS("mismatch in " #name " " \
11951                           "(expected %p, found %p)\n", \
11952                           current_config->name, \
11953                           pipe_config->name); \
11954                 ret = false; \
11955         }
11956
11957 #define PIPE_CONF_CHECK_M_N(name) \
11958         if (!intel_compare_link_m_n(&current_config->name, \
11959                                     &pipe_config->name,\
11960                                     adjust)) { \
11961                 INTEL_ERR_OR_DBG_KMS("mismatch in " #name " " \
11962                           "(expected tu %i gmch %i/%i link %i/%i, " \
11963                           "found tu %i, gmch %i/%i link %i/%i)\n", \
11964                           current_config->name.tu, \
11965                           current_config->name.gmch_m, \
11966                           current_config->name.gmch_n, \
11967                           current_config->name.link_m, \
11968                           current_config->name.link_n, \
11969                           pipe_config->name.tu, \
11970                           pipe_config->name.gmch_m, \
11971                           pipe_config->name.gmch_n, \
11972                           pipe_config->name.link_m, \
11973                           pipe_config->name.link_n); \
11974                 ret = false; \
11975         }
11976
11977 /* This is required for BDW+ where there is only one set of registers for
11978  * switching between high and low RR.
11979  * This macro can be used whenever a comparison has to be made between one
11980  * hw state and multiple sw state variables.
11981  */
11982 #define PIPE_CONF_CHECK_M_N_ALT(name, alt_name) \
11983         if (!intel_compare_link_m_n(&current_config->name, \
11984                                     &pipe_config->name, adjust) && \
11985             !intel_compare_link_m_n(&current_config->alt_name, \
11986                                     &pipe_config->name, adjust)) { \
11987                 INTEL_ERR_OR_DBG_KMS("mismatch in " #name " " \
11988                           "(expected tu %i gmch %i/%i link %i/%i, " \
11989                           "or tu %i gmch %i/%i link %i/%i, " \
11990                           "found tu %i, gmch %i/%i link %i/%i)\n", \
11991                           current_config->name.tu, \
11992                           current_config->name.gmch_m, \
11993                           current_config->name.gmch_n, \
11994                           current_config->name.link_m, \
11995                           current_config->name.link_n, \
11996                           current_config->alt_name.tu, \
11997                           current_config->alt_name.gmch_m, \
11998                           current_config->alt_name.gmch_n, \
11999                           current_config->alt_name.link_m, \
12000                           current_config->alt_name.link_n, \
12001                           pipe_config->name.tu, \
12002                           pipe_config->name.gmch_m, \
12003                           pipe_config->name.gmch_n, \
12004                           pipe_config->name.link_m, \
12005                           pipe_config->name.link_n); \
12006                 ret = false; \
12007         }
12008
12009 #define PIPE_CONF_CHECK_FLAGS(name, mask)       \
12010         if ((current_config->name ^ pipe_config->name) & (mask)) { \
12011                 INTEL_ERR_OR_DBG_KMS("mismatch in " #name "(" #mask ") " \
12012                           "(expected %i, found %i)\n", \
12013                           current_config->name & (mask), \
12014                           pipe_config->name & (mask)); \
12015                 ret = false; \
12016         }
12017
12018 #define PIPE_CONF_CHECK_CLOCK_FUZZY(name) \
12019         if (!intel_fuzzy_clock_check(current_config->name, pipe_config->name)) { \
12020                 INTEL_ERR_OR_DBG_KMS("mismatch in " #name " " \
12021                           "(expected %i, found %i)\n", \
12022                           current_config->name, \
12023                           pipe_config->name); \
12024                 ret = false; \
12025         }
12026
12027 #define PIPE_CONF_QUIRK(quirk)  \
12028         ((current_config->quirks | pipe_config->quirks) & (quirk))
12029
12030         PIPE_CONF_CHECK_I(cpu_transcoder);
12031
12032         PIPE_CONF_CHECK_I(has_pch_encoder);
12033         PIPE_CONF_CHECK_I(fdi_lanes);
12034         PIPE_CONF_CHECK_M_N(fdi_m_n);
12035
12036         PIPE_CONF_CHECK_I(has_dp_encoder);
12037         PIPE_CONF_CHECK_I(lane_count);
12038
12039         if (INTEL_INFO(dev)->gen < 8) {
12040                 PIPE_CONF_CHECK_M_N(dp_m_n);
12041
12042                 if (current_config->has_drrs)
12043                         PIPE_CONF_CHECK_M_N(dp_m2_n2);
12044         } else
12045                 PIPE_CONF_CHECK_M_N_ALT(dp_m_n, dp_m2_n2);
12046
12047         PIPE_CONF_CHECK_I(has_dsi_encoder);
12048
12049         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hdisplay);
12050         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_htotal);
12051         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hblank_start);
12052         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hblank_end);
12053         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hsync_start);
12054         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hsync_end);
12055
12056         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vdisplay);
12057         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vtotal);
12058         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vblank_start);
12059         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vblank_end);
12060         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vsync_start);
12061         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vsync_end);
12062
12063         PIPE_CONF_CHECK_I(pixel_multiplier);
12064         PIPE_CONF_CHECK_I(has_hdmi_sink);
12065         if ((INTEL_INFO(dev)->gen < 8 && !IS_HASWELL(dev)) ||
12066             IS_VALLEYVIEW(dev) || IS_CHERRYVIEW(dev))
12067                 PIPE_CONF_CHECK_I(limited_color_range);
12068         PIPE_CONF_CHECK_I(has_infoframe);
12069
12070         PIPE_CONF_CHECK_I(has_audio);
12071
12072         PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
12073                               DRM_MODE_FLAG_INTERLACE);
12074
12075         if (!PIPE_CONF_QUIRK(PIPE_CONFIG_QUIRK_MODE_SYNC_FLAGS)) {
12076                 PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
12077                                       DRM_MODE_FLAG_PHSYNC);
12078                 PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
12079                                       DRM_MODE_FLAG_NHSYNC);
12080                 PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
12081                                       DRM_MODE_FLAG_PVSYNC);
12082                 PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
12083                                       DRM_MODE_FLAG_NVSYNC);
12084         }
12085
12086         PIPE_CONF_CHECK_X(gmch_pfit.control);
12087         /* pfit ratios are autocomputed by the hw on gen4+ */
12088         if (INTEL_INFO(dev)->gen < 4)
12089                 PIPE_CONF_CHECK_X(gmch_pfit.pgm_ratios);
12090         PIPE_CONF_CHECK_X(gmch_pfit.lvds_border_bits);
12091
12092         if (!adjust) {
12093                 PIPE_CONF_CHECK_I(pipe_src_w);
12094                 PIPE_CONF_CHECK_I(pipe_src_h);
12095
12096                 PIPE_CONF_CHECK_I(pch_pfit.enabled);
12097                 if (current_config->pch_pfit.enabled) {
12098                         PIPE_CONF_CHECK_X(pch_pfit.pos);
12099                         PIPE_CONF_CHECK_X(pch_pfit.size);
12100                 }
12101
12102                 PIPE_CONF_CHECK_I(scaler_state.scaler_id);
12103         }
12104
12105         /* BDW+ don't expose a synchronous way to read the state */
12106         if (IS_HASWELL(dev))
12107                 PIPE_CONF_CHECK_I(ips_enabled);
12108
12109         PIPE_CONF_CHECK_I(double_wide);
12110
12111         PIPE_CONF_CHECK_X(ddi_pll_sel);
12112
12113         PIPE_CONF_CHECK_P(shared_dpll);
12114         PIPE_CONF_CHECK_X(dpll_hw_state.dpll);
12115         PIPE_CONF_CHECK_X(dpll_hw_state.dpll_md);
12116         PIPE_CONF_CHECK_X(dpll_hw_state.fp0);
12117         PIPE_CONF_CHECK_X(dpll_hw_state.fp1);
12118         PIPE_CONF_CHECK_X(dpll_hw_state.wrpll);
12119         PIPE_CONF_CHECK_X(dpll_hw_state.spll);
12120         PIPE_CONF_CHECK_X(dpll_hw_state.ctrl1);
12121         PIPE_CONF_CHECK_X(dpll_hw_state.cfgcr1);
12122         PIPE_CONF_CHECK_X(dpll_hw_state.cfgcr2);
12123
12124         PIPE_CONF_CHECK_X(dsi_pll.ctrl);
12125         PIPE_CONF_CHECK_X(dsi_pll.div);
12126
12127         if (IS_G4X(dev) || INTEL_INFO(dev)->gen >= 5)
12128                 PIPE_CONF_CHECK_I(pipe_bpp);
12129
12130         PIPE_CONF_CHECK_CLOCK_FUZZY(base.adjusted_mode.crtc_clock);
12131         PIPE_CONF_CHECK_CLOCK_FUZZY(port_clock);
12132
12133 #undef PIPE_CONF_CHECK_X
12134 #undef PIPE_CONF_CHECK_I
12135 #undef PIPE_CONF_CHECK_P
12136 #undef PIPE_CONF_CHECK_FLAGS
12137 #undef PIPE_CONF_CHECK_CLOCK_FUZZY
12138 #undef PIPE_CONF_QUIRK
12139 #undef INTEL_ERR_OR_DBG_KMS
12140
12141         return ret;
12142 }
12143
12144 static void intel_pipe_config_sanity_check(struct drm_i915_private *dev_priv,
12145                                            const struct intel_crtc_state *pipe_config)
12146 {
12147         if (pipe_config->has_pch_encoder) {
12148                 int fdi_dotclock = intel_dotclock_calculate(intel_fdi_link_freq(dev_priv, pipe_config),
12149                                                             &pipe_config->fdi_m_n);
12150                 int dotclock = pipe_config->base.adjusted_mode.crtc_clock;
12151
12152                 /*
12153                  * FDI already provided one idea for the dotclock.
12154                  * Yell if the encoder disagrees.
12155                  */
12156                 WARN(!intel_fuzzy_clock_check(fdi_dotclock, dotclock),
12157                      "FDI dotclock and encoder dotclock mismatch, fdi: %i, encoder: %i\n",
12158                      fdi_dotclock, dotclock);
12159         }
12160 }
12161
12162 static void verify_wm_state(struct drm_crtc *crtc,
12163                             struct drm_crtc_state *new_state)
12164 {
12165         struct drm_device *dev = crtc->dev;
12166         struct drm_i915_private *dev_priv = dev->dev_private;
12167         struct skl_ddb_allocation hw_ddb, *sw_ddb;
12168         struct skl_ddb_entry *hw_entry, *sw_entry;
12169         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
12170         const enum pipe pipe = intel_crtc->pipe;
12171         int plane;
12172
12173         if (INTEL_INFO(dev)->gen < 9 || !new_state->active)
12174                 return;
12175
12176         skl_ddb_get_hw_state(dev_priv, &hw_ddb);
12177         sw_ddb = &dev_priv->wm.skl_hw.ddb;
12178
12179         /* planes */
12180         for_each_plane(dev_priv, pipe, plane) {
12181                 hw_entry = &hw_ddb.plane[pipe][plane];
12182                 sw_entry = &sw_ddb->plane[pipe][plane];
12183
12184                 if (skl_ddb_entry_equal(hw_entry, sw_entry))
12185                         continue;
12186
12187                 DRM_ERROR("mismatch in DDB state pipe %c plane %d "
12188                           "(expected (%u,%u), found (%u,%u))\n",
12189                           pipe_name(pipe), plane + 1,
12190                           sw_entry->start, sw_entry->end,
12191                           hw_entry->start, hw_entry->end);
12192         }
12193
12194         /* cursor */
12195         hw_entry = &hw_ddb.plane[pipe][PLANE_CURSOR];
12196         sw_entry = &sw_ddb->plane[pipe][PLANE_CURSOR];
12197
12198         if (!skl_ddb_entry_equal(hw_entry, sw_entry)) {
12199                 DRM_ERROR("mismatch in DDB state pipe %c cursor "
12200                           "(expected (%u,%u), found (%u,%u))\n",
12201                           pipe_name(pipe),
12202                           sw_entry->start, sw_entry->end,
12203                           hw_entry->start, hw_entry->end);
12204         }
12205 }
12206
12207 static void
12208 verify_connector_state(struct drm_device *dev, struct drm_crtc *crtc)
12209 {
12210         struct drm_connector *connector;
12211
12212         drm_for_each_connector(connector, dev) {
12213                 struct drm_encoder *encoder = connector->encoder;
12214                 struct drm_connector_state *state = connector->state;
12215
12216                 if (state->crtc != crtc)
12217                         continue;
12218
12219                 intel_connector_verify_state(to_intel_connector(connector),
12220                                              connector->state);
12221
12222                 I915_STATE_WARN(state->best_encoder != encoder,
12223                      "connector's atomic encoder doesn't match legacy encoder\n");
12224         }
12225 }
12226
12227 static void
12228 verify_encoder_state(struct drm_device *dev)
12229 {
12230         struct intel_encoder *encoder;
12231         struct intel_connector *connector;
12232
12233         for_each_intel_encoder(dev, encoder) {
12234                 bool enabled = false;
12235                 enum pipe pipe;
12236
12237                 DRM_DEBUG_KMS("[ENCODER:%d:%s]\n",
12238                               encoder->base.base.id,
12239                               encoder->base.name);
12240
12241                 for_each_intel_connector(dev, connector) {
12242                         if (connector->base.state->best_encoder != &encoder->base)
12243                                 continue;
12244                         enabled = true;
12245
12246                         I915_STATE_WARN(connector->base.state->crtc !=
12247                                         encoder->base.crtc,
12248                              "connector's crtc doesn't match encoder crtc\n");
12249                 }
12250
12251                 I915_STATE_WARN(!!encoder->base.crtc != enabled,
12252                      "encoder's enabled state mismatch "
12253                      "(expected %i, found %i)\n",
12254                      !!encoder->base.crtc, enabled);
12255
12256                 if (!encoder->base.crtc) {
12257                         bool active;
12258
12259                         active = encoder->get_hw_state(encoder, &pipe);
12260                         I915_STATE_WARN(active,
12261                              "encoder detached but still enabled on pipe %c.\n",
12262                              pipe_name(pipe));
12263                 }
12264         }
12265 }
12266
12267 static void
12268 verify_crtc_state(struct drm_crtc *crtc,
12269                   struct drm_crtc_state *old_crtc_state,
12270                   struct drm_crtc_state *new_crtc_state)
12271 {
12272         struct drm_device *dev = crtc->dev;
12273         struct drm_i915_private *dev_priv = dev->dev_private;
12274         struct intel_encoder *encoder;
12275         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
12276         struct intel_crtc_state *pipe_config, *sw_config;
12277         struct drm_atomic_state *old_state;
12278         bool active;
12279
12280         old_state = old_crtc_state->state;
12281         __drm_atomic_helper_crtc_destroy_state(crtc, old_crtc_state);
12282         pipe_config = to_intel_crtc_state(old_crtc_state);
12283         memset(pipe_config, 0, sizeof(*pipe_config));
12284         pipe_config->base.crtc = crtc;
12285         pipe_config->base.state = old_state;
12286
12287         DRM_DEBUG_KMS("[CRTC:%d]\n", crtc->base.id);
12288
12289         active = dev_priv->display.get_pipe_config(intel_crtc, pipe_config);
12290
12291         /* hw state is inconsistent with the pipe quirk */
12292         if ((intel_crtc->pipe == PIPE_A && dev_priv->quirks & QUIRK_PIPEA_FORCE) ||
12293             (intel_crtc->pipe == PIPE_B && dev_priv->quirks & QUIRK_PIPEB_FORCE))
12294                 active = new_crtc_state->active;
12295
12296         I915_STATE_WARN(new_crtc_state->active != active,
12297              "crtc active state doesn't match with hw state "
12298              "(expected %i, found %i)\n", new_crtc_state->active, active);
12299
12300         I915_STATE_WARN(intel_crtc->active != new_crtc_state->active,
12301              "transitional active state does not match atomic hw state "
12302              "(expected %i, found %i)\n", new_crtc_state->active, intel_crtc->active);
12303
12304         for_each_encoder_on_crtc(dev, crtc, encoder) {
12305                 enum pipe pipe;
12306
12307                 active = encoder->get_hw_state(encoder, &pipe);
12308                 I915_STATE_WARN(active != new_crtc_state->active,
12309                         "[ENCODER:%i] active %i with crtc active %i\n",
12310                         encoder->base.base.id, active, new_crtc_state->active);
12311
12312                 I915_STATE_WARN(active && intel_crtc->pipe != pipe,
12313                                 "Encoder connected to wrong pipe %c\n",
12314                                 pipe_name(pipe));
12315
12316                 if (active)
12317                         encoder->get_config(encoder, pipe_config);
12318         }
12319
12320         if (!new_crtc_state->active)
12321                 return;
12322
12323         intel_pipe_config_sanity_check(dev_priv, pipe_config);
12324
12325         sw_config = to_intel_crtc_state(crtc->state);
12326         if (!intel_pipe_config_compare(dev, sw_config,
12327                                        pipe_config, false)) {
12328                 I915_STATE_WARN(1, "pipe state doesn't match!\n");
12329                 intel_dump_pipe_config(intel_crtc, pipe_config,
12330                                        "[hw state]");
12331                 intel_dump_pipe_config(intel_crtc, sw_config,
12332                                        "[sw state]");
12333         }
12334 }
12335
12336 static void
12337 verify_single_dpll_state(struct drm_i915_private *dev_priv,
12338                          struct intel_shared_dpll *pll,
12339                          struct drm_crtc *crtc,
12340                          struct drm_crtc_state *new_state)
12341 {
12342         struct intel_dpll_hw_state dpll_hw_state;
12343         unsigned crtc_mask;
12344         bool active;
12345
12346         memset(&dpll_hw_state, 0, sizeof(dpll_hw_state));
12347
12348         DRM_DEBUG_KMS("%s\n", pll->name);
12349
12350         active = pll->funcs.get_hw_state(dev_priv, pll, &dpll_hw_state);
12351
12352         if (!(pll->flags & INTEL_DPLL_ALWAYS_ON)) {
12353                 I915_STATE_WARN(!pll->on && pll->active_mask,
12354                      "pll in active use but not on in sw tracking\n");
12355                 I915_STATE_WARN(pll->on && !pll->active_mask,
12356                      "pll is on but not used by any active crtc\n");
12357                 I915_STATE_WARN(pll->on != active,
12358                      "pll on state mismatch (expected %i, found %i)\n",
12359                      pll->on, active);
12360         }
12361
12362         if (!crtc) {
12363                 I915_STATE_WARN(pll->active_mask & ~pll->config.crtc_mask,
12364                                 "more active pll users than references: %x vs %x\n",
12365                                 pll->active_mask, pll->config.crtc_mask);
12366
12367                 return;
12368         }
12369
12370         crtc_mask = 1 << drm_crtc_index(crtc);
12371
12372         if (new_state->active)
12373                 I915_STATE_WARN(!(pll->active_mask & crtc_mask),
12374                                 "pll active mismatch (expected pipe %c in active mask 0x%02x)\n",
12375                                 pipe_name(drm_crtc_index(crtc)), pll->active_mask);
12376         else
12377                 I915_STATE_WARN(pll->active_mask & crtc_mask,
12378                                 "pll active mismatch (didn't expect pipe %c in active mask 0x%02x)\n",
12379                                 pipe_name(drm_crtc_index(crtc)), pll->active_mask);
12380
12381         I915_STATE_WARN(!(pll->config.crtc_mask & crtc_mask),
12382                         "pll enabled crtcs mismatch (expected 0x%x in 0x%02x)\n",
12383                         crtc_mask, pll->config.crtc_mask);
12384
12385         I915_STATE_WARN(pll->on && memcmp(&pll->config.hw_state,
12386                                           &dpll_hw_state,
12387                                           sizeof(dpll_hw_state)),
12388                         "pll hw state mismatch\n");
12389 }
12390
12391 static void
12392 verify_shared_dpll_state(struct drm_device *dev, struct drm_crtc *crtc,
12393                          struct drm_crtc_state *old_crtc_state,
12394                          struct drm_crtc_state *new_crtc_state)
12395 {
12396         struct drm_i915_private *dev_priv = dev->dev_private;
12397         struct intel_crtc_state *old_state = to_intel_crtc_state(old_crtc_state);
12398         struct intel_crtc_state *new_state = to_intel_crtc_state(new_crtc_state);
12399
12400         if (new_state->shared_dpll)
12401                 verify_single_dpll_state(dev_priv, new_state->shared_dpll, crtc, new_crtc_state);
12402
12403         if (old_state->shared_dpll &&
12404             old_state->shared_dpll != new_state->shared_dpll) {
12405                 unsigned crtc_mask = 1 << drm_crtc_index(crtc);
12406                 struct intel_shared_dpll *pll = old_state->shared_dpll;
12407
12408                 I915_STATE_WARN(pll->active_mask & crtc_mask,
12409                                 "pll active mismatch (didn't expect pipe %c in active mask)\n",
12410                                 pipe_name(drm_crtc_index(crtc)));
12411                 I915_STATE_WARN(pll->config.crtc_mask & crtc_mask,
12412                                 "pll enabled crtcs mismatch (found %x in enabled mask)\n",
12413                                 pipe_name(drm_crtc_index(crtc)));
12414         }
12415 }
12416
12417 static void
12418 intel_modeset_verify_crtc(struct drm_crtc *crtc,
12419                          struct drm_crtc_state *old_state,
12420                          struct drm_crtc_state *new_state)
12421 {
12422         verify_wm_state(crtc, new_state);
12423         verify_crtc_state(crtc, old_state, new_state);
12424         verify_shared_dpll_state(crtc->dev, crtc, old_state, new_state);
12425 }
12426
12427 static void
12428 verify_disabled_dpll_state(struct drm_device *dev)
12429 {
12430         struct drm_i915_private *dev_priv = dev->dev_private;
12431         int i;
12432
12433         for (i = 0; i < dev_priv->num_shared_dpll; i++)
12434                 verify_single_dpll_state(dev_priv, &dev_priv->shared_dplls[i], NULL, NULL);
12435 }
12436
12437 static void
12438 intel_modeset_verify_disabled(struct drm_device *dev)
12439 {
12440         verify_encoder_state(dev);
12441         verify_connector_state(dev, NULL);
12442         verify_disabled_dpll_state(dev);
12443 }
12444
12445 static void update_scanline_offset(struct intel_crtc *crtc)
12446 {
12447         struct drm_device *dev = crtc->base.dev;
12448
12449         /*
12450          * The scanline counter increments at the leading edge of hsync.
12451          *
12452          * On most platforms it starts counting from vtotal-1 on the
12453          * first active line. That means the scanline counter value is
12454          * always one less than what we would expect. Ie. just after
12455          * start of vblank, which also occurs at start of hsync (on the
12456          * last active line), the scanline counter will read vblank_start-1.
12457          *
12458          * On gen2 the scanline counter starts counting from 1 instead
12459          * of vtotal-1, so we have to subtract one (or rather add vtotal-1
12460          * to keep the value positive), instead of adding one.
12461          *
12462          * On HSW+ the behaviour of the scanline counter depends on the output
12463          * type. For DP ports it behaves like most other platforms, but on HDMI
12464          * there's an extra 1 line difference. So we need to add two instead of
12465          * one to the value.
12466          */
12467         if (IS_GEN2(dev)) {
12468                 const struct drm_display_mode *adjusted_mode = &crtc->config->base.adjusted_mode;
12469                 int vtotal;
12470
12471                 vtotal = adjusted_mode->crtc_vtotal;
12472                 if (adjusted_mode->flags & DRM_MODE_FLAG_INTERLACE)
12473                         vtotal /= 2;
12474
12475                 crtc->scanline_offset = vtotal - 1;
12476         } else if (HAS_DDI(dev) &&
12477                    intel_pipe_has_type(crtc, INTEL_OUTPUT_HDMI)) {
12478                 crtc->scanline_offset = 2;
12479         } else
12480                 crtc->scanline_offset = 1;
12481 }
12482
12483 static void intel_modeset_clear_plls(struct drm_atomic_state *state)
12484 {
12485         struct drm_device *dev = state->dev;
12486         struct drm_i915_private *dev_priv = to_i915(dev);
12487         struct intel_shared_dpll_config *shared_dpll = NULL;
12488         struct drm_crtc *crtc;
12489         struct drm_crtc_state *crtc_state;
12490         int i;
12491
12492         if (!dev_priv->display.crtc_compute_clock)
12493                 return;
12494
12495         for_each_crtc_in_state(state, crtc, crtc_state, i) {
12496                 struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
12497                 struct intel_shared_dpll *old_dpll =
12498                         to_intel_crtc_state(crtc->state)->shared_dpll;
12499
12500                 if (!needs_modeset(crtc_state))
12501                         continue;
12502
12503                 to_intel_crtc_state(crtc_state)->shared_dpll = NULL;
12504
12505                 if (!old_dpll)
12506                         continue;
12507
12508                 if (!shared_dpll)
12509                         shared_dpll = intel_atomic_get_shared_dpll_state(state);
12510
12511                 intel_shared_dpll_config_put(shared_dpll, old_dpll, intel_crtc);
12512         }
12513 }
12514
12515 /*
12516  * This implements the workaround described in the "notes" section of the mode
12517  * set sequence documentation. When going from no pipes or single pipe to
12518  * multiple pipes, and planes are enabled after the pipe, we need to wait at
12519  * least 2 vblanks on the first pipe before enabling planes on the second pipe.
12520  */
12521 static int haswell_mode_set_planes_workaround(struct drm_atomic_state *state)
12522 {
12523         struct drm_crtc_state *crtc_state;
12524         struct intel_crtc *intel_crtc;
12525         struct drm_crtc *crtc;
12526         struct intel_crtc_state *first_crtc_state = NULL;
12527         struct intel_crtc_state *other_crtc_state = NULL;
12528         enum pipe first_pipe = INVALID_PIPE, enabled_pipe = INVALID_PIPE;
12529         int i;
12530
12531         /* look at all crtc's that are going to be enabled in during modeset */
12532         for_each_crtc_in_state(state, crtc, crtc_state, i) {
12533                 intel_crtc = to_intel_crtc(crtc);
12534
12535                 if (!crtc_state->active || !needs_modeset(crtc_state))
12536                         continue;
12537
12538                 if (first_crtc_state) {
12539                         other_crtc_state = to_intel_crtc_state(crtc_state);
12540                         break;
12541                 } else {
12542                         first_crtc_state = to_intel_crtc_state(crtc_state);
12543                         first_pipe = intel_crtc->pipe;
12544                 }
12545         }
12546
12547         /* No workaround needed? */
12548         if (!first_crtc_state)
12549                 return 0;
12550
12551         /* w/a possibly needed, check how many crtc's are already enabled. */
12552         for_each_intel_crtc(state->dev, intel_crtc) {
12553                 struct intel_crtc_state *pipe_config;
12554
12555                 pipe_config = intel_atomic_get_crtc_state(state, intel_crtc);
12556                 if (IS_ERR(pipe_config))
12557                         return PTR_ERR(pipe_config);
12558
12559                 pipe_config->hsw_workaround_pipe = INVALID_PIPE;
12560
12561                 if (!pipe_config->base.active ||
12562                     needs_modeset(&pipe_config->base))
12563                         continue;
12564
12565                 /* 2 or more enabled crtcs means no need for w/a */
12566                 if (enabled_pipe != INVALID_PIPE)
12567                         return 0;
12568
12569                 enabled_pipe = intel_crtc->pipe;
12570         }
12571
12572         if (enabled_pipe != INVALID_PIPE)
12573                 first_crtc_state->hsw_workaround_pipe = enabled_pipe;
12574         else if (other_crtc_state)
12575                 other_crtc_state->hsw_workaround_pipe = first_pipe;
12576
12577         return 0;
12578 }
12579
12580 static int intel_modeset_all_pipes(struct drm_atomic_state *state)
12581 {
12582         struct drm_crtc *crtc;
12583         struct drm_crtc_state *crtc_state;
12584         int ret = 0;
12585
12586         /* add all active pipes to the state */
12587         for_each_crtc(state->dev, crtc) {
12588                 crtc_state = drm_atomic_get_crtc_state(state, crtc);
12589                 if (IS_ERR(crtc_state))
12590                         return PTR_ERR(crtc_state);
12591
12592                 if (!crtc_state->active || needs_modeset(crtc_state))
12593                         continue;
12594
12595                 crtc_state->mode_changed = true;
12596
12597                 ret = drm_atomic_add_affected_connectors(state, crtc);
12598                 if (ret)
12599                         break;
12600
12601                 ret = drm_atomic_add_affected_planes(state, crtc);
12602                 if (ret)
12603                         break;
12604         }
12605
12606         return ret;
12607 }
12608
12609 static int intel_modeset_checks(struct drm_atomic_state *state)
12610 {
12611         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
12612         struct drm_i915_private *dev_priv = state->dev->dev_private;
12613         struct drm_crtc *crtc;
12614         struct drm_crtc_state *crtc_state;
12615         int ret = 0, i;
12616
12617         if (!check_digital_port_conflicts(state)) {
12618                 DRM_DEBUG_KMS("rejecting conflicting digital port configuration\n");
12619                 return -EINVAL;
12620         }
12621
12622         intel_state->modeset = true;
12623         intel_state->active_crtcs = dev_priv->active_crtcs;
12624
12625         for_each_crtc_in_state(state, crtc, crtc_state, i) {
12626                 if (crtc_state->active)
12627                         intel_state->active_crtcs |= 1 << i;
12628                 else
12629                         intel_state->active_crtcs &= ~(1 << i);
12630
12631                 if (crtc_state->active != crtc->state->active)
12632                         intel_state->active_pipe_changes |= drm_crtc_mask(crtc);
12633         }
12634
12635         /*
12636          * See if the config requires any additional preparation, e.g.
12637          * to adjust global state with pipes off.  We need to do this
12638          * here so we can get the modeset_pipe updated config for the new
12639          * mode set on this crtc.  For other crtcs we need to use the
12640          * adjusted_mode bits in the crtc directly.
12641          */
12642         if (dev_priv->display.modeset_calc_cdclk) {
12643                 if (!intel_state->cdclk_pll_vco)
12644                         intel_state->cdclk_pll_vco = dev_priv->skl_vco_freq;
12645
12646                 ret = dev_priv->display.modeset_calc_cdclk(state);
12647                 if (ret < 0)
12648                         return ret;
12649
12650                 if (intel_state->dev_cdclk != dev_priv->cdclk_freq ||
12651                     intel_state->cdclk_pll_vco != dev_priv->skl_vco_freq)
12652                         ret = intel_modeset_all_pipes(state);
12653
12654                 if (ret < 0)
12655                         return ret;
12656
12657                 DRM_DEBUG_KMS("New cdclk calculated to be atomic %u, actual %u\n",
12658                               intel_state->cdclk, intel_state->dev_cdclk);
12659         } else
12660                 to_intel_atomic_state(state)->cdclk = dev_priv->atomic_cdclk_freq;
12661
12662         intel_modeset_clear_plls(state);
12663
12664         if (IS_HASWELL(dev_priv))
12665                 return haswell_mode_set_planes_workaround(state);
12666
12667         return 0;
12668 }
12669
12670 /*
12671  * Handle calculation of various watermark data at the end of the atomic check
12672  * phase.  The code here should be run after the per-crtc and per-plane 'check'
12673  * handlers to ensure that all derived state has been updated.
12674  */
12675 static int calc_watermark_data(struct drm_atomic_state *state)
12676 {
12677         struct drm_device *dev = state->dev;
12678         struct drm_i915_private *dev_priv = to_i915(dev);
12679
12680         /* Is there platform-specific watermark information to calculate? */
12681         if (dev_priv->display.compute_global_watermarks)
12682                 return dev_priv->display.compute_global_watermarks(state);
12683
12684         return 0;
12685 }
12686
12687 /**
12688  * intel_atomic_check - validate state object
12689  * @dev: drm device
12690  * @state: state to validate
12691  */
12692 static int intel_atomic_check(struct drm_device *dev,
12693                               struct drm_atomic_state *state)
12694 {
12695         struct drm_i915_private *dev_priv = to_i915(dev);
12696         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
12697         struct drm_crtc *crtc;
12698         struct drm_crtc_state *crtc_state;
12699         int ret, i;
12700         bool any_ms = false;
12701
12702         ret = drm_atomic_helper_check_modeset(dev, state);
12703         if (ret)
12704                 return ret;
12705
12706         for_each_crtc_in_state(state, crtc, crtc_state, i) {
12707                 struct intel_crtc_state *pipe_config =
12708                         to_intel_crtc_state(crtc_state);
12709
12710                 /* Catch I915_MODE_FLAG_INHERITED */
12711                 if (crtc_state->mode.private_flags != crtc->state->mode.private_flags)
12712                         crtc_state->mode_changed = true;
12713
12714                 if (!needs_modeset(crtc_state))
12715                         continue;
12716
12717                 if (!crtc_state->enable) {
12718                         any_ms = true;
12719                         continue;
12720                 }
12721
12722                 /* FIXME: For only active_changed we shouldn't need to do any
12723                  * state recomputation at all. */
12724
12725                 ret = drm_atomic_add_affected_connectors(state, crtc);
12726                 if (ret)
12727                         return ret;
12728
12729                 ret = intel_modeset_pipe_config(crtc, pipe_config);
12730                 if (ret) {
12731                         intel_dump_pipe_config(to_intel_crtc(crtc),
12732                                                pipe_config, "[failed]");
12733                         return ret;
12734                 }
12735
12736                 if (i915.fastboot &&
12737                     intel_pipe_config_compare(dev,
12738                                         to_intel_crtc_state(crtc->state),
12739                                         pipe_config, true)) {
12740                         crtc_state->mode_changed = false;
12741                         to_intel_crtc_state(crtc_state)->update_pipe = true;
12742                 }
12743
12744                 if (needs_modeset(crtc_state))
12745                         any_ms = true;
12746
12747                 ret = drm_atomic_add_affected_planes(state, crtc);
12748                 if (ret)
12749                         return ret;
12750
12751                 intel_dump_pipe_config(to_intel_crtc(crtc), pipe_config,
12752                                        needs_modeset(crtc_state) ?
12753                                        "[modeset]" : "[fastset]");
12754         }
12755
12756         if (any_ms) {
12757                 ret = intel_modeset_checks(state);
12758
12759                 if (ret)
12760                         return ret;
12761         } else
12762                 intel_state->cdclk = dev_priv->cdclk_freq;
12763
12764         ret = drm_atomic_helper_check_planes(dev, state);
12765         if (ret)
12766                 return ret;
12767
12768         intel_fbc_choose_crtc(dev_priv, state);
12769         return calc_watermark_data(state);
12770 }
12771
12772 static bool needs_work(struct drm_crtc_state *crtc_state)
12773 {
12774         /* hw state checker needs to run */
12775         if (needs_modeset(crtc_state))
12776                 return true;
12777
12778         /* unpin old fb's, possibly vblank update */
12779         if (crtc_state->planes_changed)
12780                 return true;
12781
12782         /* pipe parameters need to be updated, and hw state checker */
12783         if (to_intel_crtc_state(crtc_state)->update_pipe)
12784                 return true;
12785
12786         /* vblank event requested? */
12787         if (crtc_state->event)
12788                 return true;
12789
12790         return false;
12791 }
12792
12793 static int intel_atomic_prepare_commit(struct drm_device *dev,
12794                                        struct drm_atomic_state *state,
12795                                        bool nonblock)
12796 {
12797         struct drm_i915_private *dev_priv = dev->dev_private;
12798         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
12799         struct drm_plane_state *plane_state;
12800         struct drm_crtc_state *crtc_state;
12801         struct drm_plane *plane;
12802         struct drm_crtc *crtc;
12803         int i, ret;
12804
12805         for_each_crtc_in_state(state, crtc, crtc_state, i) {
12806                 struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
12807                 struct intel_flip_work *work;
12808
12809                 if (!state->legacy_cursor_update) {
12810                         ret = intel_crtc_wait_for_pending_flips(crtc);
12811                         if (ret)
12812                                 return ret;
12813
12814                         if (atomic_read(&intel_crtc->unpin_work_count) >= 2)
12815                                 flush_workqueue(dev_priv->wq);
12816                 }
12817
12818                 /* test if we need to update something */
12819                 if (!needs_work(crtc_state))
12820                         continue;
12821
12822                 intel_state->work[i] = work =
12823                         kzalloc(sizeof(**intel_state->work), GFP_KERNEL);
12824
12825                 if (!work)
12826                         return -ENOMEM;
12827
12828                 if (needs_modeset(crtc_state) ||
12829                     to_intel_crtc_state(crtc_state)->update_pipe) {
12830                         work->num_old_connectors = hweight32(crtc->state->connector_mask);
12831
12832                         work->old_connector_state = kcalloc(work->num_old_connectors,
12833                                                             sizeof(*work->old_connector_state),
12834                                                             GFP_KERNEL);
12835
12836                         work->num_new_connectors = hweight32(crtc_state->connector_mask);
12837                         work->new_connector_state = kcalloc(work->num_new_connectors,
12838                                                             sizeof(*work->new_connector_state),
12839                                                             GFP_KERNEL);
12840
12841                         if (!work->old_connector_state || !work->new_connector_state)
12842                                 return -ENOMEM;
12843                 }
12844         }
12845
12846         if (intel_state->modeset && nonblock) {
12847                 DRM_DEBUG_ATOMIC("Nonblock modesets are not yet supported!\n");
12848                 return -EINVAL;
12849         }
12850
12851         ret = mutex_lock_interruptible(&dev->struct_mutex);
12852         if (ret)
12853                 return ret;
12854
12855         ret = drm_atomic_helper_prepare_planes(dev, state);
12856         mutex_unlock(&dev->struct_mutex);
12857
12858         if (!ret && !nonblock) {
12859                 for_each_plane_in_state(state, plane, plane_state, i) {
12860                         struct intel_plane_state *intel_plane_state =
12861                                 to_intel_plane_state(plane_state);
12862
12863                         if (plane_state->fence) {
12864                                 long lret = fence_wait(plane_state->fence, true);
12865
12866                                 if (lret < 0) {
12867                                         ret = lret;
12868                                         break;
12869                                 }
12870                         }
12871
12872                         if (!intel_plane_state->wait_req)
12873                                 continue;
12874
12875                         ret = __i915_wait_request(intel_plane_state->wait_req,
12876                                                   true, NULL, NULL);
12877                         if (ret) {
12878                                 /* Any hang should be swallowed by the wait */
12879                                 WARN_ON(ret == -EIO);
12880                                 mutex_lock(&dev->struct_mutex);
12881                                 drm_atomic_helper_cleanup_planes(dev, state);
12882                                 mutex_unlock(&dev->struct_mutex);
12883                                 break;
12884                         }
12885                 }
12886         }
12887
12888         return ret;
12889 }
12890
12891 u32 intel_crtc_get_vblank_counter(struct intel_crtc *crtc)
12892 {
12893         struct drm_device *dev = crtc->base.dev;
12894
12895         if (!dev->max_vblank_count)
12896                 return drm_accurate_vblank_count(&crtc->base);
12897
12898         return dev->driver->get_vblank_counter(dev, crtc->pipe);
12899 }
12900
12901 static void intel_prepare_work(struct drm_crtc *crtc,
12902                                struct intel_flip_work *work,
12903                                struct drm_atomic_state *state,
12904                                struct drm_crtc_state *old_crtc_state)
12905 {
12906         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
12907         struct drm_plane_state *old_plane_state;
12908         struct drm_plane *plane;
12909         int i, j = 0;
12910
12911         INIT_WORK(&work->unpin_work, intel_unpin_work_fn);
12912         INIT_WORK(&work->mmio_work, intel_mmio_flip_work_func);
12913         atomic_inc(&intel_crtc->unpin_work_count);
12914
12915         for_each_plane_in_state(state, plane, old_plane_state, i) {
12916                 struct intel_plane_state *old_state = to_intel_plane_state(old_plane_state);
12917                 struct intel_plane_state *new_state = to_intel_plane_state(plane->state);
12918
12919                 if (old_state->base.crtc != crtc &&
12920                     new_state->base.crtc != crtc)
12921                         continue;
12922
12923                 if (plane->type == DRM_PLANE_TYPE_PRIMARY) {
12924                         plane->fb = new_state->base.fb;
12925                         crtc->x = new_state->base.src_x >> 16;
12926                         crtc->y = new_state->base.src_y >> 16;
12927                 }
12928
12929                 old_state->wait_req = new_state->wait_req;
12930                 new_state->wait_req = NULL;
12931
12932                 old_state->base.fence = new_state->base.fence;
12933                 new_state->base.fence = NULL;
12934
12935                 /* remove plane state from the atomic state and move it to work */
12936                 old_plane_state->state = NULL;
12937                 state->planes[i] = NULL;
12938                 state->plane_states[i] = NULL;
12939
12940                 work->old_plane_state[j] = old_state;
12941                 work->new_plane_state[j++] = new_state;
12942         }
12943
12944         old_crtc_state->state = NULL;
12945         state->crtcs[drm_crtc_index(crtc)] = NULL;
12946         state->crtc_states[drm_crtc_index(crtc)] = NULL;
12947
12948         work->old_crtc_state = to_intel_crtc_state(old_crtc_state);
12949         work->new_crtc_state = to_intel_crtc_state(crtc->state);
12950         work->num_planes = j;
12951
12952         work->event = crtc->state->event;
12953         crtc->state->event = NULL;
12954
12955         if (needs_modeset(crtc->state) || work->new_crtc_state->update_pipe) {
12956                 struct drm_connector *conn;
12957                 struct drm_connector_state *old_conn_state;
12958                 int k = 0;
12959
12960                 j = 0;
12961
12962                 /*
12963                  * intel_unpin_work_fn cannot depend on the connector list
12964                  * because it may be freed from underneath it, so add
12965                  * them all to the work struct while we're holding locks.
12966                  */
12967                 for_each_connector_in_state(state, conn, old_conn_state, i) {
12968                         if (old_conn_state->crtc == crtc) {
12969                                 work->old_connector_state[j++] = old_conn_state;
12970
12971                                 state->connectors[i] = NULL;
12972                                 state->connector_states[i] = NULL;
12973                         }
12974                 }
12975
12976                 /* If another crtc has stolen the connector from state,
12977                  * then for_each_connector_in_state is no longer reliable,
12978                  * so use drm_for_each_connector here.
12979                  */
12980                 drm_for_each_connector(conn, state->dev)
12981                         if (conn->state->crtc == crtc)
12982                                 work->new_connector_state[k++] = conn->state;
12983
12984                 WARN(j != work->num_old_connectors, "j = %i, expected %i\n", j, work->num_old_connectors);
12985                 WARN(k != work->num_new_connectors, "k = %i, expected %i\n", k, work->num_new_connectors);
12986         } else if (!work->new_crtc_state->update_wm_post)
12987                 work->can_async_unpin = true;
12988
12989         work->fb_bits = work->new_crtc_state->fb_bits;
12990 }
12991
12992 static void intel_schedule_unpin(struct drm_crtc *crtc,
12993                                  struct intel_atomic_state *state,
12994                                  struct intel_flip_work *work)
12995 {
12996         struct drm_device *dev = crtc->dev;
12997         struct drm_i915_private *dev_priv = dev->dev_private;
12998
12999         to_intel_crtc(crtc)->config = work->new_crtc_state;
13000
13001         queue_work(dev_priv->wq, &work->unpin_work);
13002 }
13003
13004 static void intel_schedule_flip(struct drm_crtc *crtc,
13005                                 struct intel_atomic_state *state,
13006                                 struct intel_flip_work *work,
13007                                 bool nonblock)
13008 {
13009         struct intel_crtc_state *crtc_state = work->new_crtc_state;
13010
13011         if (crtc_state->base.planes_changed ||
13012             needs_modeset(&crtc_state->base) ||
13013             crtc_state->update_pipe) {
13014                 if (nonblock)
13015                         schedule_work(&work->mmio_work);
13016                 else
13017                         intel_mmio_flip_work_func(&work->mmio_work);
13018         } else {
13019                 int ret;
13020
13021                 ret = drm_crtc_vblank_get(crtc);
13022                 I915_STATE_WARN(ret < 0, "enabling vblank failed with %i\n", ret);
13023
13024                 work->flip_queued_vblank = intel_crtc_get_vblank_counter(to_intel_crtc(crtc));
13025                 smp_mb__before_atomic();
13026                 atomic_set(&work->pending, 1);
13027         }
13028 }
13029
13030 static void intel_schedule_update(struct drm_crtc *crtc,
13031                                   struct intel_atomic_state *state,
13032                                   struct intel_flip_work *work,
13033                                   bool nonblock)
13034 {
13035         struct drm_device *dev = crtc->dev;
13036         struct intel_crtc_state *pipe_config = work->new_crtc_state;
13037
13038         if (!pipe_config->base.active && work->can_async_unpin) {
13039                 INIT_LIST_HEAD(&work->head);
13040                 intel_schedule_unpin(crtc, state, work);
13041                 return;
13042         }
13043
13044         spin_lock_irq(&dev->event_lock);
13045         list_add_tail(&work->head, &to_intel_crtc(crtc)->flip_work);
13046         spin_unlock_irq(&dev->event_lock);
13047
13048         if (!pipe_config->base.active)
13049                 intel_schedule_unpin(crtc, state, work);
13050         else
13051                 intel_schedule_flip(crtc, state, work, nonblock);
13052 }
13053
13054 /**
13055  * intel_atomic_commit - commit validated state object
13056  * @dev: DRM device
13057  * @state: the top-level driver state object
13058  * @nonblock: nonblocking commit
13059  *
13060  * This function commits a top-level state object that has been validated
13061  * with drm_atomic_helper_check().
13062  *
13063  * FIXME:  Atomic modeset support for i915 is not yet complete.  At the moment
13064  * we can only handle plane-related operations and do not yet support
13065  * nonblocking commit.
13066  *
13067  * RETURNS
13068  * Zero for success or -errno.
13069  */
13070 static int intel_atomic_commit(struct drm_device *dev,
13071                                struct drm_atomic_state *state,
13072                                bool nonblock)
13073 {
13074         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
13075         struct drm_i915_private *dev_priv = dev->dev_private;
13076         struct drm_crtc_state *old_crtc_state;
13077         struct drm_crtc *crtc;
13078         int ret = 0, i;
13079
13080         ret = intel_atomic_prepare_commit(dev, state, nonblock);
13081         if (ret) {
13082                 DRM_DEBUG_ATOMIC("Preparing state failed with %i\n", ret);
13083                 return ret;
13084         }
13085
13086         drm_atomic_helper_swap_state(dev, state);
13087         dev_priv->wm.distrust_bios_wm = false;
13088         dev_priv->wm.skl_results = intel_state->wm_results;
13089         intel_shared_dpll_commit(state);
13090
13091         if (intel_state->modeset) {
13092                 memcpy(dev_priv->min_pixclk, intel_state->min_pixclk,
13093                        sizeof(intel_state->min_pixclk));
13094                 dev_priv->active_crtcs = intel_state->active_crtcs;
13095                 dev_priv->atomic_cdclk_freq = intel_state->cdclk;
13096         }
13097
13098         for_each_crtc_in_state(state, crtc, old_crtc_state, i) {
13099                 struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
13100
13101                 if (!needs_modeset(crtc->state))
13102                         continue;
13103
13104                 intel_pre_plane_update(to_intel_crtc_state(old_crtc_state));
13105
13106                 intel_state->work[i]->put_power_domains =
13107                         modeset_get_crtc_power_domains(crtc,
13108                                 to_intel_crtc_state(crtc->state));
13109
13110                 if (old_crtc_state->active) {
13111                         intel_crtc_disable_planes(crtc, old_crtc_state->plane_mask);
13112                         dev_priv->display.crtc_disable(crtc);
13113                         intel_crtc->active = false;
13114                         intel_fbc_disable(intel_crtc);
13115                         intel_disable_shared_dpll(intel_crtc);
13116
13117                         /*
13118                          * Underruns don't always raise
13119                          * interrupts, so check manually.
13120                          */
13121                         intel_check_cpu_fifo_underruns(dev_priv);
13122                         intel_check_pch_fifo_underruns(dev_priv);
13123
13124                         if (!crtc->state->active)
13125                                 intel_update_watermarks(crtc);
13126                 }
13127         }
13128
13129         /* Only after disabling all output pipelines that will be changed can we
13130          * update the the output configuration. */
13131         intel_modeset_update_crtc_state(state);
13132
13133         if (intel_state->modeset) {
13134                 drm_atomic_helper_update_legacy_modeset_state(state->dev, state);
13135
13136                 if (dev_priv->display.modeset_commit_cdclk &&
13137                     (intel_state->dev_cdclk != dev_priv->cdclk_freq ||
13138                      intel_state->cdclk_pll_vco != dev_priv->skl_vco_freq))
13139                         dev_priv->display.modeset_commit_cdclk(state);
13140
13141                 intel_modeset_verify_disabled(dev);
13142         }
13143
13144         /* Now enable the clocks, plane, pipe, and connectors that we set up. */
13145         for_each_crtc_in_state(state, crtc, old_crtc_state, i) {
13146                 struct intel_flip_work *work = intel_state->work[i];
13147                 struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
13148                 bool modeset = needs_modeset(crtc->state);
13149
13150                 if (modeset && crtc->state->active) {
13151                         update_scanline_offset(to_intel_crtc(crtc));
13152                         dev_priv->display.crtc_enable(crtc);
13153                 }
13154
13155                 if (!modeset)
13156                         intel_pre_plane_update(to_intel_crtc_state(old_crtc_state));
13157
13158                 if (!work) {
13159                         if (!list_empty_careful(&intel_crtc->flip_work)) {
13160                                 spin_lock_irq(&dev->event_lock);
13161                                 if (!list_empty(&intel_crtc->flip_work))
13162                                         work = list_last_entry(&intel_crtc->flip_work,
13163                                                                struct intel_flip_work, head);
13164
13165                                 if (work && work->new_crtc_state == to_intel_crtc_state(old_crtc_state)) {
13166                                         work->free_new_crtc_state = true;
13167                                         state->crtc_states[i] = NULL;
13168                                         state->crtcs[i] = NULL;
13169                                 }
13170                                 spin_unlock_irq(&dev->event_lock);
13171                         }
13172                         continue;
13173                 }
13174
13175                 intel_state->work[i] = NULL;
13176                 intel_prepare_work(crtc, work, state, old_crtc_state);
13177                 intel_schedule_update(crtc, intel_state, work, nonblock);
13178         }
13179
13180         /* FIXME: add subpixel order */
13181
13182         drm_atomic_state_free(state);
13183
13184         /* As one of the primary mmio accessors, KMS has a high likelihood
13185          * of triggering bugs in unclaimed access. After we finish
13186          * modesetting, see if an error has been flagged, and if so
13187          * enable debugging for the next modeset - and hope we catch
13188          * the culprit.
13189          *
13190          * XXX note that we assume display power is on at this point.
13191          * This might hold true now but we need to add pm helper to check
13192          * unclaimed only when the hardware is on, as atomic commits
13193          * can happen also when the device is completely off.
13194          */
13195         intel_uncore_arm_unclaimed_mmio_detection(dev_priv);
13196
13197         return 0;
13198 }
13199
13200 void intel_crtc_restore_mode(struct drm_crtc *crtc)
13201 {
13202         struct drm_device *dev = crtc->dev;
13203         struct drm_atomic_state *state;
13204         struct drm_crtc_state *crtc_state;
13205         int ret;
13206
13207         state = drm_atomic_state_alloc(dev);
13208         if (!state) {
13209                 DRM_DEBUG_KMS("[CRTC:%d] crtc restore failed, out of memory",
13210                               crtc->base.id);
13211                 return;
13212         }
13213
13214         state->acquire_ctx = drm_modeset_legacy_acquire_ctx(crtc);
13215
13216 retry:
13217         crtc_state = drm_atomic_get_crtc_state(state, crtc);
13218         ret = PTR_ERR_OR_ZERO(crtc_state);
13219         if (!ret) {
13220                 if (!crtc_state->active)
13221                         goto out;
13222
13223                 crtc_state->mode_changed = true;
13224                 ret = drm_atomic_commit(state);
13225         }
13226
13227         if (ret == -EDEADLK) {
13228                 drm_atomic_state_clear(state);
13229                 drm_modeset_backoff(state->acquire_ctx);
13230                 goto retry;
13231         }
13232
13233         if (ret)
13234 out:
13235                 drm_atomic_state_free(state);
13236 }
13237
13238 #undef for_each_intel_crtc_masked
13239
13240 static const struct drm_crtc_funcs intel_crtc_funcs = {
13241         .gamma_set = drm_atomic_helper_legacy_gamma_set,
13242         .set_config = drm_atomic_helper_set_config,
13243         .set_property = drm_atomic_helper_crtc_set_property,
13244         .destroy = intel_crtc_destroy,
13245         .page_flip = drm_atomic_helper_page_flip,
13246         .atomic_duplicate_state = intel_crtc_duplicate_state,
13247         .atomic_destroy_state = intel_crtc_destroy_state,
13248 };
13249
13250 static struct fence *intel_get_excl_fence(struct drm_i915_gem_object *obj)
13251 {
13252         struct reservation_object *resv;
13253
13254
13255         if (!obj->base.dma_buf)
13256                 return NULL;
13257
13258         resv = obj->base.dma_buf->resv;
13259
13260         /* For framebuffer backed by dmabuf, wait for fence */
13261         while (1) {
13262                 struct fence *fence_excl, *ret = NULL;
13263
13264                 rcu_read_lock();
13265
13266                 fence_excl = rcu_dereference(resv->fence_excl);
13267                 if (fence_excl)
13268                         ret = fence_get_rcu(fence_excl);
13269
13270                 rcu_read_unlock();
13271
13272                 if (ret == fence_excl)
13273                         return ret;
13274         }
13275 }
13276
13277 /**
13278  * intel_prepare_plane_fb - Prepare fb for usage on plane
13279  * @plane: drm plane to prepare for
13280  * @fb: framebuffer to prepare for presentation
13281  *
13282  * Prepares a framebuffer for usage on a display plane.  Generally this
13283  * involves pinning the underlying object and updating the frontbuffer tracking
13284  * bits.  Some older platforms need special physical address handling for
13285  * cursor planes.
13286  *
13287  * Must be called with struct_mutex held.
13288  *
13289  * Returns 0 on success, negative error code on failure.
13290  */
13291 int
13292 intel_prepare_plane_fb(struct drm_plane *plane,
13293                        const struct drm_plane_state *new_state)
13294 {
13295         struct drm_device *dev = plane->dev;
13296         struct drm_framebuffer *fb = new_state->fb;
13297         struct intel_plane *intel_plane = to_intel_plane(plane);
13298         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
13299         struct drm_i915_gem_object *old_obj = intel_fb_obj(plane->state->fb);
13300         struct drm_crtc *crtc = new_state->crtc ?: plane->state->crtc;
13301         int ret = 0;
13302
13303         if (!obj && !old_obj)
13304                 return 0;
13305
13306         if (WARN_ON(!new_state->state) || WARN_ON(!crtc) ||
13307             WARN_ON(!to_intel_atomic_state(new_state->state)->work[to_intel_crtc(crtc)->pipe])) {
13308                 if (WARN_ON(old_obj != obj))
13309                         return -EINVAL;
13310
13311                 return 0;
13312         }
13313
13314         if (old_obj) {
13315                 struct drm_crtc_state *crtc_state =
13316                         drm_atomic_get_existing_crtc_state(new_state->state, plane->state->crtc);
13317
13318                 /* Big Hammer, we also need to ensure that any pending
13319                  * MI_WAIT_FOR_EVENT inside a user batch buffer on the
13320                  * current scanout is retired before unpinning the old
13321                  * framebuffer. Note that we rely on userspace rendering
13322                  * into the buffer attached to the pipe they are waiting
13323                  * on. If not, userspace generates a GPU hang with IPEHR
13324                  * point to the MI_WAIT_FOR_EVENT.
13325                  *
13326                  * This should only fail upon a hung GPU, in which case we
13327                  * can safely continue.
13328                  */
13329                 if (needs_modeset(crtc_state))
13330                         ret = i915_gem_object_wait_rendering(old_obj, true);
13331                 if (ret) {
13332                         /* GPU hangs should have been swallowed by the wait */
13333                         WARN_ON(ret == -EIO);
13334                         return ret;
13335                 }
13336         }
13337
13338         if (!obj) {
13339                 ret = 0;
13340         } else if (plane->type == DRM_PLANE_TYPE_CURSOR &&
13341             INTEL_INFO(dev)->cursor_needs_physical) {
13342                 int align = IS_I830(dev) ? 16 * 1024 : 256;
13343                 ret = i915_gem_object_attach_phys(obj, align);
13344                 if (ret)
13345                         DRM_DEBUG_KMS("failed to attach phys object\n");
13346         } else {
13347                 ret = intel_pin_and_fence_fb_obj(fb, new_state->rotation);
13348         }
13349
13350         if (ret == 0) {
13351                 if (obj) {
13352                         struct intel_plane_state *plane_state =
13353                                 to_intel_plane_state(new_state);
13354
13355                         i915_gem_request_assign(&plane_state->wait_req,
13356                                                 obj->last_write_req);
13357
13358                         plane_state->base.fence = intel_get_excl_fence(obj);
13359                 }
13360
13361                 i915_gem_track_fb(old_obj, obj, intel_plane->frontbuffer_bit);
13362         }
13363
13364         return ret;
13365 }
13366
13367 /**
13368  * intel_cleanup_plane_fb - Cleans up an fb after plane use
13369  * @plane: drm plane to clean up for
13370  * @fb: old framebuffer that was on plane
13371  *
13372  * Cleans up a framebuffer that has just been removed from a plane.
13373  *
13374  * Must be called with struct_mutex held.
13375  */
13376 void
13377 intel_cleanup_plane_fb(struct drm_plane *plane,
13378                        const struct drm_plane_state *old_state)
13379 {
13380         struct drm_device *dev = plane->dev;
13381         struct intel_plane *intel_plane = to_intel_plane(plane);
13382         struct intel_plane_state *old_intel_state;
13383         struct drm_i915_gem_object *old_obj = intel_fb_obj(old_state->fb);
13384         struct drm_i915_gem_object *obj = intel_fb_obj(plane->state->fb);
13385
13386         old_intel_state = to_intel_plane_state(old_state);
13387
13388         if (!obj && !old_obj)
13389                 return;
13390
13391         if (old_obj && (plane->type != DRM_PLANE_TYPE_CURSOR ||
13392             !INTEL_INFO(dev)->cursor_needs_physical))
13393                 intel_unpin_fb_obj(old_state->fb, old_state->rotation);
13394
13395         /* prepare_fb aborted? */
13396         if ((old_obj && (old_obj->frontbuffer_bits & intel_plane->frontbuffer_bit)) ||
13397             (obj && !(obj->frontbuffer_bits & intel_plane->frontbuffer_bit)))
13398                 i915_gem_track_fb(old_obj, obj, intel_plane->frontbuffer_bit);
13399
13400         i915_gem_request_assign(&old_intel_state->wait_req, NULL);
13401
13402         fence_put(old_intel_state->base.fence);
13403         old_intel_state->base.fence = NULL;
13404 }
13405
13406 int
13407 skl_max_scale(struct intel_crtc *intel_crtc, struct intel_crtc_state *crtc_state)
13408 {
13409         int max_scale;
13410         struct drm_device *dev;
13411         struct drm_i915_private *dev_priv;
13412         int crtc_clock, cdclk;
13413
13414         if (!intel_crtc || !crtc_state->base.enable)
13415                 return DRM_PLANE_HELPER_NO_SCALING;
13416
13417         dev = intel_crtc->base.dev;
13418         dev_priv = dev->dev_private;
13419         crtc_clock = crtc_state->base.adjusted_mode.crtc_clock;
13420         cdclk = to_intel_atomic_state(crtc_state->base.state)->cdclk;
13421
13422         if (WARN_ON_ONCE(!crtc_clock || cdclk < crtc_clock))
13423                 return DRM_PLANE_HELPER_NO_SCALING;
13424
13425         /*
13426          * skl max scale is lower of:
13427          *    close to 3 but not 3, -1 is for that purpose
13428          *            or
13429          *    cdclk/crtc_clock
13430          */
13431         max_scale = min((1 << 16) * 3 - 1, (1 << 8) * ((cdclk << 8) / crtc_clock));
13432
13433         return max_scale;
13434 }
13435
13436 static int
13437 intel_check_primary_plane(struct drm_plane *plane,
13438                           struct intel_crtc_state *crtc_state,
13439                           struct intel_plane_state *state)
13440 {
13441         struct drm_crtc *crtc = state->base.crtc;
13442         struct drm_framebuffer *fb = state->base.fb;
13443         int min_scale = DRM_PLANE_HELPER_NO_SCALING;
13444         int max_scale = DRM_PLANE_HELPER_NO_SCALING;
13445         bool can_position = false;
13446
13447         if (INTEL_INFO(plane->dev)->gen >= 9) {
13448                 /* use scaler when colorkey is not required */
13449                 if (state->ckey.flags == I915_SET_COLORKEY_NONE) {
13450                         min_scale = 1;
13451                         max_scale = skl_max_scale(to_intel_crtc(crtc), crtc_state);
13452                 }
13453                 can_position = true;
13454         }
13455
13456         return drm_plane_helper_check_update(plane, crtc, fb, &state->src,
13457                                              &state->dst, &state->clip,
13458                                              min_scale, max_scale,
13459                                              can_position, true,
13460                                              &state->visible);
13461 }
13462
13463 /**
13464  * intel_plane_destroy - destroy a plane
13465  * @plane: plane to destroy
13466  *
13467  * Common destruction function for all types of planes (primary, cursor,
13468  * sprite).
13469  */
13470 void intel_plane_destroy(struct drm_plane *plane)
13471 {
13472         struct intel_plane *intel_plane = to_intel_plane(plane);
13473         drm_plane_cleanup(plane);
13474         kfree(intel_plane);
13475 }
13476
13477 const struct drm_plane_funcs intel_plane_funcs = {
13478         .update_plane = drm_atomic_helper_update_plane,
13479         .disable_plane = drm_atomic_helper_disable_plane,
13480         .destroy = intel_plane_destroy,
13481         .set_property = drm_atomic_helper_plane_set_property,
13482         .atomic_get_property = intel_plane_atomic_get_property,
13483         .atomic_set_property = intel_plane_atomic_set_property,
13484         .atomic_duplicate_state = intel_plane_duplicate_state,
13485         .atomic_destroy_state = intel_plane_destroy_state,
13486
13487 };
13488
13489 static struct drm_plane *intel_primary_plane_create(struct drm_device *dev,
13490                                                     int pipe)
13491 {
13492         struct intel_plane *primary = NULL;
13493         struct intel_plane_state *state = NULL;
13494         const uint32_t *intel_primary_formats;
13495         unsigned int num_formats;
13496         int ret;
13497
13498         primary = kzalloc(sizeof(*primary), GFP_KERNEL);
13499         if (!primary)
13500                 goto fail;
13501
13502         state = intel_create_plane_state(&primary->base);
13503         if (!state)
13504                 goto fail;
13505         primary->base.state = &state->base;
13506
13507         primary->can_scale = false;
13508         primary->max_downscale = 1;
13509         if (INTEL_INFO(dev)->gen >= 9) {
13510                 primary->can_scale = true;
13511                 state->scaler_id = -1;
13512         }
13513         primary->pipe = pipe;
13514         primary->plane = pipe;
13515         primary->frontbuffer_bit = INTEL_FRONTBUFFER_PRIMARY(pipe);
13516         primary->check_plane = intel_check_primary_plane;
13517         if (HAS_FBC(dev) && INTEL_INFO(dev)->gen < 4)
13518                 primary->plane = !pipe;
13519
13520         if (INTEL_INFO(dev)->gen >= 9) {
13521                 intel_primary_formats = skl_primary_formats;
13522                 num_formats = ARRAY_SIZE(skl_primary_formats);
13523
13524                 primary->update_plane = skylake_update_primary_plane;
13525                 primary->disable_plane = skylake_disable_primary_plane;
13526         } else if (HAS_PCH_SPLIT(dev)) {
13527                 intel_primary_formats = i965_primary_formats;
13528                 num_formats = ARRAY_SIZE(i965_primary_formats);
13529
13530                 primary->update_plane = ironlake_update_primary_plane;
13531                 primary->disable_plane = i9xx_disable_primary_plane;
13532         } else if (INTEL_INFO(dev)->gen >= 4) {
13533                 intel_primary_formats = i965_primary_formats;
13534                 num_formats = ARRAY_SIZE(i965_primary_formats);
13535
13536                 primary->update_plane = i9xx_update_primary_plane;
13537                 primary->disable_plane = i9xx_disable_primary_plane;
13538         } else {
13539                 intel_primary_formats = i8xx_primary_formats;
13540                 num_formats = ARRAY_SIZE(i8xx_primary_formats);
13541
13542                 primary->update_plane = i9xx_update_primary_plane;
13543                 primary->disable_plane = i9xx_disable_primary_plane;
13544         }
13545
13546         ret = drm_universal_plane_init(dev, &primary->base, 0,
13547                                        &intel_plane_funcs,
13548                                        intel_primary_formats, num_formats,
13549                                        DRM_PLANE_TYPE_PRIMARY, NULL);
13550         if (ret)
13551                 goto fail;
13552
13553         if (INTEL_INFO(dev)->gen >= 4)
13554                 intel_create_rotation_property(dev, primary);
13555
13556         drm_plane_helper_add(&primary->base, &intel_plane_helper_funcs);
13557
13558         return &primary->base;
13559
13560 fail:
13561         kfree(state);
13562         kfree(primary);
13563
13564         return NULL;
13565 }
13566
13567 void intel_create_rotation_property(struct drm_device *dev, struct intel_plane *plane)
13568 {
13569         if (!dev->mode_config.rotation_property) {
13570                 unsigned long flags = BIT(DRM_ROTATE_0) |
13571                         BIT(DRM_ROTATE_180);
13572
13573                 if (INTEL_INFO(dev)->gen >= 9)
13574                         flags |= BIT(DRM_ROTATE_90) | BIT(DRM_ROTATE_270);
13575
13576                 dev->mode_config.rotation_property =
13577                         drm_mode_create_rotation_property(dev, flags);
13578         }
13579         if (dev->mode_config.rotation_property)
13580                 drm_object_attach_property(&plane->base.base,
13581                                 dev->mode_config.rotation_property,
13582                                 plane->base.state->rotation);
13583 }
13584
13585 static int
13586 intel_check_cursor_plane(struct drm_plane *plane,
13587                          struct intel_crtc_state *crtc_state,
13588                          struct intel_plane_state *state)
13589 {
13590         struct drm_crtc *crtc = crtc_state->base.crtc;
13591         struct drm_framebuffer *fb = state->base.fb;
13592         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
13593         enum pipe pipe = to_intel_plane(plane)->pipe;
13594         unsigned stride;
13595         int ret;
13596
13597         ret = drm_plane_helper_check_update(plane, crtc, fb, &state->src,
13598                                             &state->dst, &state->clip,
13599                                             DRM_PLANE_HELPER_NO_SCALING,
13600                                             DRM_PLANE_HELPER_NO_SCALING,
13601                                             true, true, &state->visible);
13602         if (ret)
13603                 return ret;
13604
13605         /* if we want to turn off the cursor ignore width and height */
13606         if (!obj)
13607                 return 0;
13608
13609         /* Check for which cursor types we support */
13610         if (!cursor_size_ok(plane->dev, state->base.crtc_w, state->base.crtc_h)) {
13611                 DRM_DEBUG("Cursor dimension %dx%d not supported\n",
13612                           state->base.crtc_w, state->base.crtc_h);
13613                 return -EINVAL;
13614         }
13615
13616         stride = roundup_pow_of_two(state->base.crtc_w) * 4;
13617         if (obj->base.size < stride * state->base.crtc_h) {
13618                 DRM_DEBUG_KMS("buffer is too small\n");
13619                 return -ENOMEM;
13620         }
13621
13622         if (fb->modifier[0] != DRM_FORMAT_MOD_NONE) {
13623                 DRM_DEBUG_KMS("cursor cannot be tiled\n");
13624                 return -EINVAL;
13625         }
13626
13627         /*
13628          * There's something wrong with the cursor on CHV pipe C.
13629          * If it straddles the left edge of the screen then
13630          * moving it away from the edge or disabling it often
13631          * results in a pipe underrun, and often that can lead to
13632          * dead pipe (constant underrun reported, and it scans
13633          * out just a solid color). To recover from that, the
13634          * display power well must be turned off and on again.
13635          * Refuse the put the cursor into that compromised position.
13636          */
13637         if (IS_CHERRYVIEW(plane->dev) && pipe == PIPE_C &&
13638             state->visible && state->base.crtc_x < 0) {
13639                 DRM_DEBUG_KMS("CHV cursor C not allowed to straddle the left screen edge\n");
13640                 return -EINVAL;
13641         }
13642
13643         return 0;
13644 }
13645
13646 static void
13647 intel_disable_cursor_plane(struct drm_plane *plane,
13648                            struct drm_crtc *crtc)
13649 {
13650         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
13651
13652         intel_crtc->cursor_addr = 0;
13653         intel_crtc_update_cursor(crtc, NULL);
13654 }
13655
13656 static void
13657 intel_update_cursor_plane(struct drm_plane *plane,
13658                           const struct intel_crtc_state *crtc_state,
13659                           const struct intel_plane_state *state)
13660 {
13661         struct drm_crtc *crtc = crtc_state->base.crtc;
13662         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
13663         struct drm_device *dev = plane->dev;
13664         struct drm_i915_gem_object *obj = intel_fb_obj(state->base.fb);
13665         uint32_t addr;
13666
13667         if (!obj)
13668                 addr = 0;
13669         else if (!INTEL_INFO(dev)->cursor_needs_physical)
13670                 addr = i915_gem_obj_ggtt_offset(obj);
13671         else
13672                 addr = obj->phys_handle->busaddr;
13673
13674         intel_crtc->cursor_addr = addr;
13675         intel_crtc_update_cursor(crtc, state);
13676 }
13677
13678 static struct drm_plane *intel_cursor_plane_create(struct drm_device *dev,
13679                                                    int pipe)
13680 {
13681         struct intel_plane *cursor = NULL;
13682         struct intel_plane_state *state = NULL;
13683         int ret;
13684
13685         cursor = kzalloc(sizeof(*cursor), GFP_KERNEL);
13686         if (!cursor)
13687                 goto fail;
13688
13689         state = intel_create_plane_state(&cursor->base);
13690         if (!state)
13691                 goto fail;
13692         cursor->base.state = &state->base;
13693
13694         cursor->can_scale = false;
13695         cursor->max_downscale = 1;
13696         cursor->pipe = pipe;
13697         cursor->plane = pipe;
13698         cursor->frontbuffer_bit = INTEL_FRONTBUFFER_CURSOR(pipe);
13699         cursor->check_plane = intel_check_cursor_plane;
13700         cursor->update_plane = intel_update_cursor_plane;
13701         cursor->disable_plane = intel_disable_cursor_plane;
13702
13703         ret = drm_universal_plane_init(dev, &cursor->base, 0,
13704                                        &intel_plane_funcs,
13705                                        intel_cursor_formats,
13706                                        ARRAY_SIZE(intel_cursor_formats),
13707                                        DRM_PLANE_TYPE_CURSOR, NULL);
13708         if (ret)
13709                 goto fail;
13710
13711         if (INTEL_INFO(dev)->gen >= 4) {
13712                 if (!dev->mode_config.rotation_property)
13713                         dev->mode_config.rotation_property =
13714                                 drm_mode_create_rotation_property(dev,
13715                                                         BIT(DRM_ROTATE_0) |
13716                                                         BIT(DRM_ROTATE_180));
13717                 if (dev->mode_config.rotation_property)
13718                         drm_object_attach_property(&cursor->base.base,
13719                                 dev->mode_config.rotation_property,
13720                                 state->base.rotation);
13721         }
13722
13723         if (INTEL_INFO(dev)->gen >=9)
13724                 state->scaler_id = -1;
13725
13726         drm_plane_helper_add(&cursor->base, &intel_plane_helper_funcs);
13727
13728         return &cursor->base;
13729
13730 fail:
13731         kfree(state);
13732         kfree(cursor);
13733
13734         return NULL;
13735 }
13736
13737 static void skl_init_scalers(struct drm_device *dev, struct intel_crtc *intel_crtc,
13738         struct intel_crtc_state *crtc_state)
13739 {
13740         int i;
13741         struct intel_scaler *intel_scaler;
13742         struct intel_crtc_scaler_state *scaler_state = &crtc_state->scaler_state;
13743
13744         for (i = 0; i < intel_crtc->num_scalers; i++) {
13745                 intel_scaler = &scaler_state->scalers[i];
13746                 intel_scaler->in_use = 0;
13747                 intel_scaler->mode = PS_SCALER_MODE_DYN;
13748         }
13749
13750         scaler_state->scaler_id = -1;
13751 }
13752
13753 static void intel_crtc_init(struct drm_device *dev, int pipe)
13754 {
13755         struct drm_i915_private *dev_priv = dev->dev_private;
13756         struct intel_crtc *intel_crtc;
13757         struct intel_crtc_state *crtc_state = NULL;
13758         struct drm_plane *primary = NULL;
13759         struct drm_plane *cursor = NULL;
13760         int ret;
13761
13762         intel_crtc = kzalloc(sizeof(*intel_crtc), GFP_KERNEL);
13763         if (intel_crtc == NULL)
13764                 return;
13765
13766         crtc_state = kzalloc(sizeof(*crtc_state), GFP_KERNEL);
13767         if (!crtc_state)
13768                 goto fail;
13769         intel_crtc->config = crtc_state;
13770         intel_crtc->base.state = &crtc_state->base;
13771         crtc_state->base.crtc = &intel_crtc->base;
13772
13773         INIT_LIST_HEAD(&intel_crtc->flip_work);
13774
13775         /* initialize shared scalers */
13776         if (INTEL_INFO(dev)->gen >= 9) {
13777                 if (pipe == PIPE_C)
13778                         intel_crtc->num_scalers = 1;
13779                 else
13780                         intel_crtc->num_scalers = SKL_NUM_SCALERS;
13781
13782                 skl_init_scalers(dev, intel_crtc, crtc_state);
13783         }
13784
13785         primary = intel_primary_plane_create(dev, pipe);
13786         if (!primary)
13787                 goto fail;
13788
13789         cursor = intel_cursor_plane_create(dev, pipe);
13790         if (!cursor)
13791                 goto fail;
13792
13793         ret = drm_crtc_init_with_planes(dev, &intel_crtc->base, primary,
13794                                         cursor, &intel_crtc_funcs, NULL);
13795         if (ret)
13796                 goto fail;
13797
13798         /*
13799          * On gen2/3 only plane A can do fbc, but the panel fitter and lvds port
13800          * is hooked to pipe B. Hence we want plane A feeding pipe B.
13801          */
13802         intel_crtc->pipe = pipe;
13803         intel_crtc->plane = pipe;
13804         if (HAS_FBC(dev) && INTEL_INFO(dev)->gen < 4) {
13805                 DRM_DEBUG_KMS("swapping pipes & planes for FBC\n");
13806                 intel_crtc->plane = !pipe;
13807         }
13808
13809         intel_crtc->cursor_base = ~0;
13810         intel_crtc->cursor_cntl = ~0;
13811         intel_crtc->cursor_size = ~0;
13812
13813         intel_crtc->wm.cxsr_allowed = true;
13814
13815         BUG_ON(pipe >= ARRAY_SIZE(dev_priv->plane_to_crtc_mapping) ||
13816                dev_priv->plane_to_crtc_mapping[intel_crtc->plane] != NULL);
13817         dev_priv->plane_to_crtc_mapping[intel_crtc->plane] = &intel_crtc->base;
13818         dev_priv->pipe_to_crtc_mapping[intel_crtc->pipe] = &intel_crtc->base;
13819
13820         drm_crtc_helper_add(&intel_crtc->base, &intel_helper_funcs);
13821
13822         intel_color_init(&intel_crtc->base);
13823
13824         WARN_ON(drm_crtc_index(&intel_crtc->base) != intel_crtc->pipe);
13825         return;
13826
13827 fail:
13828         if (primary)
13829                 drm_plane_cleanup(primary);
13830         if (cursor)
13831                 drm_plane_cleanup(cursor);
13832         kfree(crtc_state);
13833         kfree(intel_crtc);
13834 }
13835
13836 enum pipe intel_get_pipe_from_connector(struct intel_connector *connector)
13837 {
13838         struct drm_encoder *encoder = connector->base.encoder;
13839         struct drm_device *dev = connector->base.dev;
13840
13841         WARN_ON(!drm_modeset_is_locked(&dev->mode_config.connection_mutex));
13842
13843         if (!encoder || WARN_ON(!encoder->crtc))
13844                 return INVALID_PIPE;
13845
13846         return to_intel_crtc(encoder->crtc)->pipe;
13847 }
13848
13849 int intel_get_pipe_from_crtc_id(struct drm_device *dev, void *data,
13850                                 struct drm_file *file)
13851 {
13852         struct drm_i915_get_pipe_from_crtc_id *pipe_from_crtc_id = data;
13853         struct drm_crtc *drmmode_crtc;
13854         struct intel_crtc *crtc;
13855
13856         drmmode_crtc = drm_crtc_find(dev, pipe_from_crtc_id->crtc_id);
13857
13858         if (!drmmode_crtc) {
13859                 DRM_ERROR("no such CRTC id\n");
13860                 return -ENOENT;
13861         }
13862
13863         crtc = to_intel_crtc(drmmode_crtc);
13864         pipe_from_crtc_id->pipe = crtc->pipe;
13865
13866         return 0;
13867 }
13868
13869 static int intel_encoder_clones(struct intel_encoder *encoder)
13870 {
13871         struct drm_device *dev = encoder->base.dev;
13872         struct intel_encoder *source_encoder;
13873         int index_mask = 0;
13874         int entry = 0;
13875
13876         for_each_intel_encoder(dev, source_encoder) {
13877                 if (encoders_cloneable(encoder, source_encoder))
13878                         index_mask |= (1 << entry);
13879
13880                 entry++;
13881         }
13882
13883         return index_mask;
13884 }
13885
13886 static bool has_edp_a(struct drm_device *dev)
13887 {
13888         struct drm_i915_private *dev_priv = dev->dev_private;
13889
13890         if (!IS_MOBILE(dev))
13891                 return false;
13892
13893         if ((I915_READ(DP_A) & DP_DETECTED) == 0)
13894                 return false;
13895
13896         if (IS_GEN5(dev) && (I915_READ(FUSE_STRAP) & ILK_eDP_A_DISABLE))
13897                 return false;
13898
13899         return true;
13900 }
13901
13902 static bool intel_crt_present(struct drm_device *dev)
13903 {
13904         struct drm_i915_private *dev_priv = dev->dev_private;
13905
13906         if (INTEL_INFO(dev)->gen >= 9)
13907                 return false;
13908
13909         if (IS_HSW_ULT(dev) || IS_BDW_ULT(dev))
13910                 return false;
13911
13912         if (IS_CHERRYVIEW(dev))
13913                 return false;
13914
13915         if (HAS_PCH_LPT_H(dev) && I915_READ(SFUSE_STRAP) & SFUSE_STRAP_CRT_DISABLED)
13916                 return false;
13917
13918         /* DDI E can't be used if DDI A requires 4 lanes */
13919         if (HAS_DDI(dev) && I915_READ(DDI_BUF_CTL(PORT_A)) & DDI_A_4_LANES)
13920                 return false;
13921
13922         if (!dev_priv->vbt.int_crt_support)
13923                 return false;
13924
13925         return true;
13926 }
13927
13928 static void intel_setup_outputs(struct drm_device *dev)
13929 {
13930         struct drm_i915_private *dev_priv = dev->dev_private;
13931         struct intel_encoder *encoder;
13932         bool dpd_is_edp = false;
13933
13934         intel_lvds_init(dev);
13935
13936         if (intel_crt_present(dev))
13937                 intel_crt_init(dev);
13938
13939         if (IS_BROXTON(dev)) {
13940                 /*
13941                  * FIXME: Broxton doesn't support port detection via the
13942                  * DDI_BUF_CTL_A or SFUSE_STRAP registers, find another way to
13943                  * detect the ports.
13944                  */
13945                 intel_ddi_init(dev, PORT_A);
13946                 intel_ddi_init(dev, PORT_B);
13947                 intel_ddi_init(dev, PORT_C);
13948
13949                 intel_dsi_init(dev);
13950         } else if (HAS_DDI(dev)) {
13951                 int found;
13952
13953                 /*
13954                  * Haswell uses DDI functions to detect digital outputs.
13955                  * On SKL pre-D0 the strap isn't connected, so we assume
13956                  * it's there.
13957                  */
13958                 found = I915_READ(DDI_BUF_CTL(PORT_A)) & DDI_INIT_DISPLAY_DETECTED;
13959                 /* WaIgnoreDDIAStrap: skl */
13960                 if (found || IS_SKYLAKE(dev) || IS_KABYLAKE(dev))
13961                         intel_ddi_init(dev, PORT_A);
13962
13963                 /* DDI B, C and D detection is indicated by the SFUSE_STRAP
13964                  * register */
13965                 found = I915_READ(SFUSE_STRAP);
13966
13967                 if (found & SFUSE_STRAP_DDIB_DETECTED)
13968                         intel_ddi_init(dev, PORT_B);
13969                 if (found & SFUSE_STRAP_DDIC_DETECTED)
13970                         intel_ddi_init(dev, PORT_C);
13971                 if (found & SFUSE_STRAP_DDID_DETECTED)
13972                         intel_ddi_init(dev, PORT_D);
13973                 /*
13974                  * On SKL we don't have a way to detect DDI-E so we rely on VBT.
13975                  */
13976                 if ((IS_SKYLAKE(dev) || IS_KABYLAKE(dev)) &&
13977                     (dev_priv->vbt.ddi_port_info[PORT_E].supports_dp ||
13978                      dev_priv->vbt.ddi_port_info[PORT_E].supports_dvi ||
13979                      dev_priv->vbt.ddi_port_info[PORT_E].supports_hdmi))
13980                         intel_ddi_init(dev, PORT_E);
13981
13982         } else if (HAS_PCH_SPLIT(dev)) {
13983                 int found;
13984                 dpd_is_edp = intel_dp_is_edp(dev, PORT_D);
13985
13986                 if (has_edp_a(dev))
13987                         intel_dp_init(dev, DP_A, PORT_A);
13988
13989                 if (I915_READ(PCH_HDMIB) & SDVO_DETECTED) {
13990                         /* PCH SDVOB multiplex with HDMIB */
13991                         found = intel_sdvo_init(dev, PCH_SDVOB, PORT_B);
13992                         if (!found)
13993                                 intel_hdmi_init(dev, PCH_HDMIB, PORT_B);
13994                         if (!found && (I915_READ(PCH_DP_B) & DP_DETECTED))
13995                                 intel_dp_init(dev, PCH_DP_B, PORT_B);
13996                 }
13997
13998                 if (I915_READ(PCH_HDMIC) & SDVO_DETECTED)
13999                         intel_hdmi_init(dev, PCH_HDMIC, PORT_C);
14000
14001                 if (!dpd_is_edp && I915_READ(PCH_HDMID) & SDVO_DETECTED)
14002                         intel_hdmi_init(dev, PCH_HDMID, PORT_D);
14003
14004                 if (I915_READ(PCH_DP_C) & DP_DETECTED)
14005                         intel_dp_init(dev, PCH_DP_C, PORT_C);
14006
14007                 if (I915_READ(PCH_DP_D) & DP_DETECTED)
14008                         intel_dp_init(dev, PCH_DP_D, PORT_D);
14009         } else if (IS_VALLEYVIEW(dev) || IS_CHERRYVIEW(dev)) {
14010                 /*
14011                  * The DP_DETECTED bit is the latched state of the DDC
14012                  * SDA pin at boot. However since eDP doesn't require DDC
14013                  * (no way to plug in a DP->HDMI dongle) the DDC pins for
14014                  * eDP ports may have been muxed to an alternate function.
14015                  * Thus we can't rely on the DP_DETECTED bit alone to detect
14016                  * eDP ports. Consult the VBT as well as DP_DETECTED to
14017                  * detect eDP ports.
14018                  */
14019                 if (I915_READ(VLV_HDMIB) & SDVO_DETECTED &&
14020                     !intel_dp_is_edp(dev, PORT_B))
14021                         intel_hdmi_init(dev, VLV_HDMIB, PORT_B);
14022                 if (I915_READ(VLV_DP_B) & DP_DETECTED ||
14023                     intel_dp_is_edp(dev, PORT_B))
14024                         intel_dp_init(dev, VLV_DP_B, PORT_B);
14025
14026                 if (I915_READ(VLV_HDMIC) & SDVO_DETECTED &&
14027                     !intel_dp_is_edp(dev, PORT_C))
14028                         intel_hdmi_init(dev, VLV_HDMIC, PORT_C);
14029                 if (I915_READ(VLV_DP_C) & DP_DETECTED ||
14030                     intel_dp_is_edp(dev, PORT_C))
14031                         intel_dp_init(dev, VLV_DP_C, PORT_C);
14032
14033                 if (IS_CHERRYVIEW(dev)) {
14034                         /* eDP not supported on port D, so don't check VBT */
14035                         if (I915_READ(CHV_HDMID) & SDVO_DETECTED)
14036                                 intel_hdmi_init(dev, CHV_HDMID, PORT_D);
14037                         if (I915_READ(CHV_DP_D) & DP_DETECTED)
14038                                 intel_dp_init(dev, CHV_DP_D, PORT_D);
14039                 }
14040
14041                 intel_dsi_init(dev);
14042         } else if (!IS_GEN2(dev) && !IS_PINEVIEW(dev)) {
14043                 bool found = false;
14044
14045                 if (I915_READ(GEN3_SDVOB) & SDVO_DETECTED) {
14046                         DRM_DEBUG_KMS("probing SDVOB\n");
14047                         found = intel_sdvo_init(dev, GEN3_SDVOB, PORT_B);
14048                         if (!found && IS_G4X(dev)) {
14049                                 DRM_DEBUG_KMS("probing HDMI on SDVOB\n");
14050                                 intel_hdmi_init(dev, GEN4_HDMIB, PORT_B);
14051                         }
14052
14053                         if (!found && IS_G4X(dev))
14054                                 intel_dp_init(dev, DP_B, PORT_B);
14055                 }
14056
14057                 /* Before G4X SDVOC doesn't have its own detect register */
14058
14059                 if (I915_READ(GEN3_SDVOB) & SDVO_DETECTED) {
14060                         DRM_DEBUG_KMS("probing SDVOC\n");
14061                         found = intel_sdvo_init(dev, GEN3_SDVOC, PORT_C);
14062                 }
14063
14064                 if (!found && (I915_READ(GEN3_SDVOC) & SDVO_DETECTED)) {
14065
14066                         if (IS_G4X(dev)) {
14067                                 DRM_DEBUG_KMS("probing HDMI on SDVOC\n");
14068                                 intel_hdmi_init(dev, GEN4_HDMIC, PORT_C);
14069                         }
14070                         if (IS_G4X(dev))
14071                                 intel_dp_init(dev, DP_C, PORT_C);
14072                 }
14073
14074                 if (IS_G4X(dev) &&
14075                     (I915_READ(DP_D) & DP_DETECTED))
14076                         intel_dp_init(dev, DP_D, PORT_D);
14077         } else if (IS_GEN2(dev))
14078                 intel_dvo_init(dev);
14079
14080         if (SUPPORTS_TV(dev))
14081                 intel_tv_init(dev);
14082
14083         intel_psr_init(dev);
14084
14085         for_each_intel_encoder(dev, encoder) {
14086                 encoder->base.possible_crtcs = encoder->crtc_mask;
14087                 encoder->base.possible_clones =
14088                         intel_encoder_clones(encoder);
14089         }
14090
14091         intel_init_pch_refclk(dev);
14092
14093         drm_helper_move_panel_connectors_to_head(dev);
14094 }
14095
14096 static void intel_user_framebuffer_destroy(struct drm_framebuffer *fb)
14097 {
14098         struct drm_device *dev = fb->dev;
14099         struct intel_framebuffer *intel_fb = to_intel_framebuffer(fb);
14100
14101         drm_framebuffer_cleanup(fb);
14102         mutex_lock(&dev->struct_mutex);
14103         WARN_ON(!intel_fb->obj->framebuffer_references--);
14104         drm_gem_object_unreference(&intel_fb->obj->base);
14105         mutex_unlock(&dev->struct_mutex);
14106         kfree(intel_fb);
14107 }
14108
14109 static int intel_user_framebuffer_create_handle(struct drm_framebuffer *fb,
14110                                                 struct drm_file *file,
14111                                                 unsigned int *handle)
14112 {
14113         struct intel_framebuffer *intel_fb = to_intel_framebuffer(fb);
14114         struct drm_i915_gem_object *obj = intel_fb->obj;
14115
14116         if (obj->userptr.mm) {
14117                 DRM_DEBUG("attempting to use a userptr for a framebuffer, denied\n");
14118                 return -EINVAL;
14119         }
14120
14121         return drm_gem_handle_create(file, &obj->base, handle);
14122 }
14123
14124 static int intel_user_framebuffer_dirty(struct drm_framebuffer *fb,
14125                                         struct drm_file *file,
14126                                         unsigned flags, unsigned color,
14127                                         struct drm_clip_rect *clips,
14128                                         unsigned num_clips)
14129 {
14130         struct drm_device *dev = fb->dev;
14131         struct intel_framebuffer *intel_fb = to_intel_framebuffer(fb);
14132         struct drm_i915_gem_object *obj = intel_fb->obj;
14133
14134         mutex_lock(&dev->struct_mutex);
14135         intel_fb_obj_flush(obj, false, ORIGIN_DIRTYFB);
14136         mutex_unlock(&dev->struct_mutex);
14137
14138         return 0;
14139 }
14140
14141 static const struct drm_framebuffer_funcs intel_fb_funcs = {
14142         .destroy = intel_user_framebuffer_destroy,
14143         .create_handle = intel_user_framebuffer_create_handle,
14144         .dirty = intel_user_framebuffer_dirty,
14145 };
14146
14147 static
14148 u32 intel_fb_pitch_limit(struct drm_device *dev, uint64_t fb_modifier,
14149                          uint32_t pixel_format)
14150 {
14151         u32 gen = INTEL_INFO(dev)->gen;
14152
14153         if (gen >= 9) {
14154                 int cpp = drm_format_plane_cpp(pixel_format, 0);
14155
14156                 /* "The stride in bytes must not exceed the of the size of 8K
14157                  *  pixels and 32K bytes."
14158                  */
14159                 return min(8192 * cpp, 32768);
14160         } else if (gen >= 5 && !IS_VALLEYVIEW(dev) && !IS_CHERRYVIEW(dev)) {
14161                 return 32*1024;
14162         } else if (gen >= 4) {
14163                 if (fb_modifier == I915_FORMAT_MOD_X_TILED)
14164                         return 16*1024;
14165                 else
14166                         return 32*1024;
14167         } else if (gen >= 3) {
14168                 if (fb_modifier == I915_FORMAT_MOD_X_TILED)
14169                         return 8*1024;
14170                 else
14171                         return 16*1024;
14172         } else {
14173                 /* XXX DSPC is limited to 4k tiled */
14174                 return 8*1024;
14175         }
14176 }
14177
14178 static int intel_framebuffer_init(struct drm_device *dev,
14179                                   struct intel_framebuffer *intel_fb,
14180                                   struct drm_mode_fb_cmd2 *mode_cmd,
14181                                   struct drm_i915_gem_object *obj)
14182 {
14183         struct drm_i915_private *dev_priv = to_i915(dev);
14184         unsigned int aligned_height;
14185         int ret;
14186         u32 pitch_limit, stride_alignment;
14187
14188         WARN_ON(!mutex_is_locked(&dev->struct_mutex));
14189
14190         if (mode_cmd->flags & DRM_MODE_FB_MODIFIERS) {
14191                 /* Enforce that fb modifier and tiling mode match, but only for
14192                  * X-tiled. This is needed for FBC. */
14193                 if (!!(obj->tiling_mode == I915_TILING_X) !=
14194                     !!(mode_cmd->modifier[0] == I915_FORMAT_MOD_X_TILED)) {
14195                         DRM_DEBUG("tiling_mode doesn't match fb modifier\n");
14196                         return -EINVAL;
14197                 }
14198         } else {
14199                 if (obj->tiling_mode == I915_TILING_X)
14200                         mode_cmd->modifier[0] = I915_FORMAT_MOD_X_TILED;
14201                 else if (obj->tiling_mode == I915_TILING_Y) {
14202                         DRM_DEBUG("No Y tiling for legacy addfb\n");
14203                         return -EINVAL;
14204                 }
14205         }
14206
14207         /* Passed in modifier sanity checking. */
14208         switch (mode_cmd->modifier[0]) {
14209         case I915_FORMAT_MOD_Y_TILED:
14210         case I915_FORMAT_MOD_Yf_TILED:
14211                 if (INTEL_INFO(dev)->gen < 9) {
14212                         DRM_DEBUG("Unsupported tiling 0x%llx!\n",
14213                                   mode_cmd->modifier[0]);
14214                         return -EINVAL;
14215                 }
14216         case DRM_FORMAT_MOD_NONE:
14217         case I915_FORMAT_MOD_X_TILED:
14218                 break;
14219         default:
14220                 DRM_DEBUG("Unsupported fb modifier 0x%llx!\n",
14221                           mode_cmd->modifier[0]);
14222                 return -EINVAL;
14223         }
14224
14225         stride_alignment = intel_fb_stride_alignment(dev_priv,
14226                                                      mode_cmd->modifier[0],
14227                                                      mode_cmd->pixel_format);
14228         if (mode_cmd->pitches[0] & (stride_alignment - 1)) {
14229                 DRM_DEBUG("pitch (%d) must be at least %u byte aligned\n",
14230                           mode_cmd->pitches[0], stride_alignment);
14231                 return -EINVAL;
14232         }
14233
14234         pitch_limit = intel_fb_pitch_limit(dev, mode_cmd->modifier[0],
14235                                            mode_cmd->pixel_format);
14236         if (mode_cmd->pitches[0] > pitch_limit) {
14237                 DRM_DEBUG("%s pitch (%u) must be at less than %d\n",
14238                           mode_cmd->modifier[0] != DRM_FORMAT_MOD_NONE ?
14239                           "tiled" : "linear",
14240                           mode_cmd->pitches[0], pitch_limit);
14241                 return -EINVAL;
14242         }
14243
14244         if (mode_cmd->modifier[0] == I915_FORMAT_MOD_X_TILED &&
14245             mode_cmd->pitches[0] != obj->stride) {
14246                 DRM_DEBUG("pitch (%d) must match tiling stride (%d)\n",
14247                           mode_cmd->pitches[0], obj->stride);
14248                 return -EINVAL;
14249         }
14250
14251         /* Reject formats not supported by any plane early. */
14252         switch (mode_cmd->pixel_format) {
14253         case DRM_FORMAT_C8:
14254         case DRM_FORMAT_RGB565:
14255         case DRM_FORMAT_XRGB8888:
14256         case DRM_FORMAT_ARGB8888:
14257                 break;
14258         case DRM_FORMAT_XRGB1555:
14259                 if (INTEL_INFO(dev)->gen > 3) {
14260                         DRM_DEBUG("unsupported pixel format: %s\n",
14261                                   drm_get_format_name(mode_cmd->pixel_format));
14262                         return -EINVAL;
14263                 }
14264                 break;
14265         case DRM_FORMAT_ABGR8888:
14266                 if (!IS_VALLEYVIEW(dev) && !IS_CHERRYVIEW(dev) &&
14267                     INTEL_INFO(dev)->gen < 9) {
14268                         DRM_DEBUG("unsupported pixel format: %s\n",
14269                                   drm_get_format_name(mode_cmd->pixel_format));
14270                         return -EINVAL;
14271                 }
14272                 break;
14273         case DRM_FORMAT_XBGR8888:
14274         case DRM_FORMAT_XRGB2101010:
14275         case DRM_FORMAT_XBGR2101010:
14276                 if (INTEL_INFO(dev)->gen < 4) {
14277                         DRM_DEBUG("unsupported pixel format: %s\n",
14278                                   drm_get_format_name(mode_cmd->pixel_format));
14279                         return -EINVAL;
14280                 }
14281                 break;
14282         case DRM_FORMAT_ABGR2101010:
14283                 if (!IS_VALLEYVIEW(dev) && !IS_CHERRYVIEW(dev)) {
14284                         DRM_DEBUG("unsupported pixel format: %s\n",
14285                                   drm_get_format_name(mode_cmd->pixel_format));
14286                         return -EINVAL;
14287                 }
14288                 break;
14289         case DRM_FORMAT_YUYV:
14290         case DRM_FORMAT_UYVY:
14291         case DRM_FORMAT_YVYU:
14292         case DRM_FORMAT_VYUY:
14293                 if (INTEL_INFO(dev)->gen < 5) {
14294                         DRM_DEBUG("unsupported pixel format: %s\n",
14295                                   drm_get_format_name(mode_cmd->pixel_format));
14296                         return -EINVAL;
14297                 }
14298                 break;
14299         default:
14300                 DRM_DEBUG("unsupported pixel format: %s\n",
14301                           drm_get_format_name(mode_cmd->pixel_format));
14302                 return -EINVAL;
14303         }
14304
14305         /* FIXME need to adjust LINOFF/TILEOFF accordingly. */
14306         if (mode_cmd->offsets[0] != 0)
14307                 return -EINVAL;
14308
14309         aligned_height = intel_fb_align_height(dev, mode_cmd->height,
14310                                                mode_cmd->pixel_format,
14311                                                mode_cmd->modifier[0]);
14312         /* FIXME drm helper for size checks (especially planar formats)? */
14313         if (obj->base.size < aligned_height * mode_cmd->pitches[0])
14314                 return -EINVAL;
14315
14316         drm_helper_mode_fill_fb_struct(&intel_fb->base, mode_cmd);
14317         intel_fb->obj = obj;
14318
14319         intel_fill_fb_info(dev_priv, &intel_fb->base);
14320
14321         ret = drm_framebuffer_init(dev, &intel_fb->base, &intel_fb_funcs);
14322         if (ret) {
14323                 DRM_ERROR("framebuffer init failed %d\n", ret);
14324                 return ret;
14325         }
14326
14327         intel_fb->obj->framebuffer_references++;
14328
14329         return 0;
14330 }
14331
14332 static struct drm_framebuffer *
14333 intel_user_framebuffer_create(struct drm_device *dev,
14334                               struct drm_file *filp,
14335                               const struct drm_mode_fb_cmd2 *user_mode_cmd)
14336 {
14337         struct drm_framebuffer *fb;
14338         struct drm_i915_gem_object *obj;
14339         struct drm_mode_fb_cmd2 mode_cmd = *user_mode_cmd;
14340
14341         obj = to_intel_bo(drm_gem_object_lookup(dev, filp,
14342                                                 mode_cmd.handles[0]));
14343         if (&obj->base == NULL)
14344                 return ERR_PTR(-ENOENT);
14345
14346         fb = intel_framebuffer_create(dev, &mode_cmd, obj);
14347         if (IS_ERR(fb))
14348                 drm_gem_object_unreference_unlocked(&obj->base);
14349
14350         return fb;
14351 }
14352
14353 #ifndef CONFIG_DRM_FBDEV_EMULATION
14354 static inline void intel_fbdev_output_poll_changed(struct drm_device *dev)
14355 {
14356 }
14357 #endif
14358
14359 static const struct drm_mode_config_funcs intel_mode_funcs = {
14360         .fb_create = intel_user_framebuffer_create,
14361         .output_poll_changed = intel_fbdev_output_poll_changed,
14362         .atomic_check = intel_atomic_check,
14363         .atomic_commit = intel_atomic_commit,
14364         .atomic_state_alloc = intel_atomic_state_alloc,
14365         .atomic_state_clear = intel_atomic_state_clear,
14366 };
14367
14368 /**
14369  * intel_init_display_hooks - initialize the display modesetting hooks
14370  * @dev_priv: device private
14371  */
14372 void intel_init_display_hooks(struct drm_i915_private *dev_priv)
14373 {
14374         if (INTEL_INFO(dev_priv)->gen >= 9) {
14375                 dev_priv->display.get_pipe_config = haswell_get_pipe_config;
14376                 dev_priv->display.get_initial_plane_config =
14377                         skylake_get_initial_plane_config;
14378                 dev_priv->display.crtc_compute_clock =
14379                         haswell_crtc_compute_clock;
14380                 dev_priv->display.crtc_enable = haswell_crtc_enable;
14381                 dev_priv->display.crtc_disable = haswell_crtc_disable;
14382         } else if (HAS_DDI(dev_priv)) {
14383                 dev_priv->display.get_pipe_config = haswell_get_pipe_config;
14384                 dev_priv->display.get_initial_plane_config =
14385                         ironlake_get_initial_plane_config;
14386                 dev_priv->display.crtc_compute_clock =
14387                         haswell_crtc_compute_clock;
14388                 dev_priv->display.crtc_enable = haswell_crtc_enable;
14389                 dev_priv->display.crtc_disable = haswell_crtc_disable;
14390         } else if (HAS_PCH_SPLIT(dev_priv)) {
14391                 dev_priv->display.get_pipe_config = ironlake_get_pipe_config;
14392                 dev_priv->display.get_initial_plane_config =
14393                         ironlake_get_initial_plane_config;
14394                 dev_priv->display.crtc_compute_clock =
14395                         ironlake_crtc_compute_clock;
14396                 dev_priv->display.crtc_enable = ironlake_crtc_enable;
14397                 dev_priv->display.crtc_disable = ironlake_crtc_disable;
14398         } else if (IS_CHERRYVIEW(dev_priv)) {
14399                 dev_priv->display.get_pipe_config = i9xx_get_pipe_config;
14400                 dev_priv->display.get_initial_plane_config =
14401                         i9xx_get_initial_plane_config;
14402                 dev_priv->display.crtc_compute_clock = chv_crtc_compute_clock;
14403                 dev_priv->display.crtc_enable = valleyview_crtc_enable;
14404                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
14405         } else if (IS_VALLEYVIEW(dev_priv)) {
14406                 dev_priv->display.get_pipe_config = i9xx_get_pipe_config;
14407                 dev_priv->display.get_initial_plane_config =
14408                         i9xx_get_initial_plane_config;
14409                 dev_priv->display.crtc_compute_clock = vlv_crtc_compute_clock;
14410                 dev_priv->display.crtc_enable = valleyview_crtc_enable;
14411                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
14412         } else if (IS_G4X(dev_priv)) {
14413                 dev_priv->display.get_pipe_config = i9xx_get_pipe_config;
14414                 dev_priv->display.get_initial_plane_config =
14415                         i9xx_get_initial_plane_config;
14416                 dev_priv->display.crtc_compute_clock = g4x_crtc_compute_clock;
14417                 dev_priv->display.crtc_enable = i9xx_crtc_enable;
14418                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
14419         } else if (IS_PINEVIEW(dev_priv)) {
14420                 dev_priv->display.get_pipe_config = i9xx_get_pipe_config;
14421                 dev_priv->display.get_initial_plane_config =
14422                         i9xx_get_initial_plane_config;
14423                 dev_priv->display.crtc_compute_clock = pnv_crtc_compute_clock;
14424                 dev_priv->display.crtc_enable = i9xx_crtc_enable;
14425                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
14426         } else if (!IS_GEN2(dev_priv)) {
14427                 dev_priv->display.get_pipe_config = i9xx_get_pipe_config;
14428                 dev_priv->display.get_initial_plane_config =
14429                         i9xx_get_initial_plane_config;
14430                 dev_priv->display.crtc_compute_clock = i9xx_crtc_compute_clock;
14431                 dev_priv->display.crtc_enable = i9xx_crtc_enable;
14432                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
14433         } else {
14434                 dev_priv->display.get_pipe_config = i9xx_get_pipe_config;
14435                 dev_priv->display.get_initial_plane_config =
14436                         i9xx_get_initial_plane_config;
14437                 dev_priv->display.crtc_compute_clock = i8xx_crtc_compute_clock;
14438                 dev_priv->display.crtc_enable = i9xx_crtc_enable;
14439                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
14440         }
14441
14442         /* Returns the core display clock speed */
14443         if (IS_SKYLAKE(dev_priv) || IS_KABYLAKE(dev_priv))
14444                 dev_priv->display.get_display_clock_speed =
14445                         skylake_get_display_clock_speed;
14446         else if (IS_BROXTON(dev_priv))
14447                 dev_priv->display.get_display_clock_speed =
14448                         broxton_get_display_clock_speed;
14449         else if (IS_BROADWELL(dev_priv))
14450                 dev_priv->display.get_display_clock_speed =
14451                         broadwell_get_display_clock_speed;
14452         else if (IS_HASWELL(dev_priv))
14453                 dev_priv->display.get_display_clock_speed =
14454                         haswell_get_display_clock_speed;
14455         else if (IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv))
14456                 dev_priv->display.get_display_clock_speed =
14457                         valleyview_get_display_clock_speed;
14458         else if (IS_GEN5(dev_priv))
14459                 dev_priv->display.get_display_clock_speed =
14460                         ilk_get_display_clock_speed;
14461         else if (IS_I945G(dev_priv) || IS_BROADWATER(dev_priv) ||
14462                  IS_GEN6(dev_priv) || IS_IVYBRIDGE(dev_priv))
14463                 dev_priv->display.get_display_clock_speed =
14464                         i945_get_display_clock_speed;
14465         else if (IS_GM45(dev_priv))
14466                 dev_priv->display.get_display_clock_speed =
14467                         gm45_get_display_clock_speed;
14468         else if (IS_CRESTLINE(dev_priv))
14469                 dev_priv->display.get_display_clock_speed =
14470                         i965gm_get_display_clock_speed;
14471         else if (IS_PINEVIEW(dev_priv))
14472                 dev_priv->display.get_display_clock_speed =
14473                         pnv_get_display_clock_speed;
14474         else if (IS_G33(dev_priv) || IS_G4X(dev_priv))
14475                 dev_priv->display.get_display_clock_speed =
14476                         g33_get_display_clock_speed;
14477         else if (IS_I915G(dev_priv))
14478                 dev_priv->display.get_display_clock_speed =
14479                         i915_get_display_clock_speed;
14480         else if (IS_I945GM(dev_priv) || IS_845G(dev_priv))
14481                 dev_priv->display.get_display_clock_speed =
14482                         i9xx_misc_get_display_clock_speed;
14483         else if (IS_I915GM(dev_priv))
14484                 dev_priv->display.get_display_clock_speed =
14485                         i915gm_get_display_clock_speed;
14486         else if (IS_I865G(dev_priv))
14487                 dev_priv->display.get_display_clock_speed =
14488                         i865_get_display_clock_speed;
14489         else if (IS_I85X(dev_priv))
14490                 dev_priv->display.get_display_clock_speed =
14491                         i85x_get_display_clock_speed;
14492         else { /* 830 */
14493                 WARN(!IS_I830(dev_priv), "Unknown platform. Assuming 133 MHz CDCLK\n");
14494                 dev_priv->display.get_display_clock_speed =
14495                         i830_get_display_clock_speed;
14496         }
14497
14498         if (IS_GEN5(dev_priv)) {
14499                 dev_priv->display.fdi_link_train = ironlake_fdi_link_train;
14500         } else if (IS_GEN6(dev_priv)) {
14501                 dev_priv->display.fdi_link_train = gen6_fdi_link_train;
14502         } else if (IS_IVYBRIDGE(dev_priv)) {
14503                 /* FIXME: detect B0+ stepping and use auto training */
14504                 dev_priv->display.fdi_link_train = ivb_manual_fdi_link_train;
14505         } else if (IS_HASWELL(dev_priv) || IS_BROADWELL(dev_priv)) {
14506                 dev_priv->display.fdi_link_train = hsw_fdi_link_train;
14507         }
14508
14509         if (IS_BROADWELL(dev_priv)) {
14510                 dev_priv->display.modeset_commit_cdclk =
14511                         broadwell_modeset_commit_cdclk;
14512                 dev_priv->display.modeset_calc_cdclk =
14513                         broadwell_modeset_calc_cdclk;
14514         } else if (IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv)) {
14515                 dev_priv->display.modeset_commit_cdclk =
14516                         valleyview_modeset_commit_cdclk;
14517                 dev_priv->display.modeset_calc_cdclk =
14518                         valleyview_modeset_calc_cdclk;
14519         } else if (IS_BROXTON(dev_priv)) {
14520                 dev_priv->display.modeset_commit_cdclk =
14521                         broxton_modeset_commit_cdclk;
14522                 dev_priv->display.modeset_calc_cdclk =
14523                         broxton_modeset_calc_cdclk;
14524         } else if (IS_SKYLAKE(dev_priv) || IS_KABYLAKE(dev_priv)) {
14525                 dev_priv->display.modeset_commit_cdclk =
14526                         skl_modeset_commit_cdclk;
14527                 dev_priv->display.modeset_calc_cdclk =
14528                         skl_modeset_calc_cdclk;
14529         }
14530 }
14531
14532 /*
14533  * Some BIOSes insist on assuming the GPU's pipe A is enabled at suspend,
14534  * resume, or other times.  This quirk makes sure that's the case for
14535  * affected systems.
14536  */
14537 static void quirk_pipea_force(struct drm_device *dev)
14538 {
14539         struct drm_i915_private *dev_priv = dev->dev_private;
14540
14541         dev_priv->quirks |= QUIRK_PIPEA_FORCE;
14542         DRM_INFO("applying pipe a force quirk\n");
14543 }
14544
14545 static void quirk_pipeb_force(struct drm_device *dev)
14546 {
14547         struct drm_i915_private *dev_priv = dev->dev_private;
14548
14549         dev_priv->quirks |= QUIRK_PIPEB_FORCE;
14550         DRM_INFO("applying pipe b force quirk\n");
14551 }
14552
14553 /*
14554  * Some machines (Lenovo U160) do not work with SSC on LVDS for some reason
14555  */
14556 static void quirk_ssc_force_disable(struct drm_device *dev)
14557 {
14558         struct drm_i915_private *dev_priv = dev->dev_private;
14559         dev_priv->quirks |= QUIRK_LVDS_SSC_DISABLE;
14560         DRM_INFO("applying lvds SSC disable quirk\n");
14561 }
14562
14563 /*
14564  * A machine (e.g. Acer Aspire 5734Z) may need to invert the panel backlight
14565  * brightness value
14566  */
14567 static void quirk_invert_brightness(struct drm_device *dev)
14568 {
14569         struct drm_i915_private *dev_priv = dev->dev_private;
14570         dev_priv->quirks |= QUIRK_INVERT_BRIGHTNESS;
14571         DRM_INFO("applying inverted panel brightness quirk\n");
14572 }
14573
14574 /* Some VBT's incorrectly indicate no backlight is present */
14575 static void quirk_backlight_present(struct drm_device *dev)
14576 {
14577         struct drm_i915_private *dev_priv = dev->dev_private;
14578         dev_priv->quirks |= QUIRK_BACKLIGHT_PRESENT;
14579         DRM_INFO("applying backlight present quirk\n");
14580 }
14581
14582 struct intel_quirk {
14583         int device;
14584         int subsystem_vendor;
14585         int subsystem_device;
14586         void (*hook)(struct drm_device *dev);
14587 };
14588
14589 /* For systems that don't have a meaningful PCI subdevice/subvendor ID */
14590 struct intel_dmi_quirk {
14591         void (*hook)(struct drm_device *dev);
14592         const struct dmi_system_id (*dmi_id_list)[];
14593 };
14594
14595 static int intel_dmi_reverse_brightness(const struct dmi_system_id *id)
14596 {
14597         DRM_INFO("Backlight polarity reversed on %s\n", id->ident);
14598         return 1;
14599 }
14600
14601 static const struct intel_dmi_quirk intel_dmi_quirks[] = {
14602         {
14603                 .dmi_id_list = &(const struct dmi_system_id[]) {
14604                         {
14605                                 .callback = intel_dmi_reverse_brightness,
14606                                 .ident = "NCR Corporation",
14607                                 .matches = {DMI_MATCH(DMI_SYS_VENDOR, "NCR Corporation"),
14608                                             DMI_MATCH(DMI_PRODUCT_NAME, ""),
14609                                 },
14610                         },
14611                         { }  /* terminating entry */
14612                 },
14613                 .hook = quirk_invert_brightness,
14614         },
14615 };
14616
14617 static struct intel_quirk intel_quirks[] = {
14618         /* Toshiba Protege R-205, S-209 needs pipe A force quirk */
14619         { 0x2592, 0x1179, 0x0001, quirk_pipea_force },
14620
14621         /* ThinkPad T60 needs pipe A force quirk (bug #16494) */
14622         { 0x2782, 0x17aa, 0x201a, quirk_pipea_force },
14623
14624         /* 830 needs to leave pipe A & dpll A up */
14625         { 0x3577, PCI_ANY_ID, PCI_ANY_ID, quirk_pipea_force },
14626
14627         /* 830 needs to leave pipe B & dpll B up */
14628         { 0x3577, PCI_ANY_ID, PCI_ANY_ID, quirk_pipeb_force },
14629
14630         /* Lenovo U160 cannot use SSC on LVDS */
14631         { 0x0046, 0x17aa, 0x3920, quirk_ssc_force_disable },
14632
14633         /* Sony Vaio Y cannot use SSC on LVDS */
14634         { 0x0046, 0x104d, 0x9076, quirk_ssc_force_disable },
14635
14636         /* Acer Aspire 5734Z must invert backlight brightness */
14637         { 0x2a42, 0x1025, 0x0459, quirk_invert_brightness },
14638
14639         /* Acer/eMachines G725 */
14640         { 0x2a42, 0x1025, 0x0210, quirk_invert_brightness },
14641
14642         /* Acer/eMachines e725 */
14643         { 0x2a42, 0x1025, 0x0212, quirk_invert_brightness },
14644
14645         /* Acer/Packard Bell NCL20 */
14646         { 0x2a42, 0x1025, 0x034b, quirk_invert_brightness },
14647
14648         /* Acer Aspire 4736Z */
14649         { 0x2a42, 0x1025, 0x0260, quirk_invert_brightness },
14650
14651         /* Acer Aspire 5336 */
14652         { 0x2a42, 0x1025, 0x048a, quirk_invert_brightness },
14653
14654         /* Acer C720 and C720P Chromebooks (Celeron 2955U) have backlights */
14655         { 0x0a06, 0x1025, 0x0a11, quirk_backlight_present },
14656
14657         /* Acer C720 Chromebook (Core i3 4005U) */
14658         { 0x0a16, 0x1025, 0x0a11, quirk_backlight_present },
14659
14660         /* Apple Macbook 2,1 (Core 2 T7400) */
14661         { 0x27a2, 0x8086, 0x7270, quirk_backlight_present },
14662
14663         /* Apple Macbook 4,1 */
14664         { 0x2a02, 0x106b, 0x00a1, quirk_backlight_present },
14665
14666         /* Toshiba CB35 Chromebook (Celeron 2955U) */
14667         { 0x0a06, 0x1179, 0x0a88, quirk_backlight_present },
14668
14669         /* HP Chromebook 14 (Celeron 2955U) */
14670         { 0x0a06, 0x103c, 0x21ed, quirk_backlight_present },
14671
14672         /* Dell Chromebook 11 */
14673         { 0x0a06, 0x1028, 0x0a35, quirk_backlight_present },
14674
14675         /* Dell Chromebook 11 (2015 version) */
14676         { 0x0a16, 0x1028, 0x0a35, quirk_backlight_present },
14677 };
14678
14679 static void intel_init_quirks(struct drm_device *dev)
14680 {
14681         struct pci_dev *d = dev->pdev;
14682         int i;
14683
14684         for (i = 0; i < ARRAY_SIZE(intel_quirks); i++) {
14685                 struct intel_quirk *q = &intel_quirks[i];
14686
14687                 if (d->device == q->device &&
14688                     (d->subsystem_vendor == q->subsystem_vendor ||
14689                      q->subsystem_vendor == PCI_ANY_ID) &&
14690                     (d->subsystem_device == q->subsystem_device ||
14691                      q->subsystem_device == PCI_ANY_ID))
14692                         q->hook(dev);
14693         }
14694         for (i = 0; i < ARRAY_SIZE(intel_dmi_quirks); i++) {
14695                 if (dmi_check_system(*intel_dmi_quirks[i].dmi_id_list) != 0)
14696                         intel_dmi_quirks[i].hook(dev);
14697         }
14698 }
14699
14700 /* Disable the VGA plane that we never use */
14701 static void i915_disable_vga(struct drm_device *dev)
14702 {
14703         struct drm_i915_private *dev_priv = dev->dev_private;
14704         u8 sr1;
14705         i915_reg_t vga_reg = i915_vgacntrl_reg(dev);
14706
14707         /* WaEnableVGAAccessThroughIOPort:ctg,elk,ilk,snb,ivb,vlv,hsw */
14708         vga_get_uninterruptible(dev->pdev, VGA_RSRC_LEGACY_IO);
14709         outb(SR01, VGA_SR_INDEX);
14710         sr1 = inb(VGA_SR_DATA);
14711         outb(sr1 | 1<<5, VGA_SR_DATA);
14712         vga_put(dev->pdev, VGA_RSRC_LEGACY_IO);
14713         udelay(300);
14714
14715         I915_WRITE(vga_reg, VGA_DISP_DISABLE);
14716         POSTING_READ(vga_reg);
14717 }
14718
14719 void intel_modeset_init_hw(struct drm_device *dev)
14720 {
14721         struct drm_i915_private *dev_priv = dev->dev_private;
14722
14723         intel_update_cdclk(dev);
14724
14725         dev_priv->atomic_cdclk_freq = dev_priv->cdclk_freq;
14726
14727         intel_init_clock_gating(dev);
14728         intel_enable_gt_powersave(dev_priv);
14729 }
14730
14731 /*
14732  * Calculate what we think the watermarks should be for the state we've read
14733  * out of the hardware and then immediately program those watermarks so that
14734  * we ensure the hardware settings match our internal state.
14735  *
14736  * We can calculate what we think WM's should be by creating a duplicate of the
14737  * current state (which was constructed during hardware readout) and running it
14738  * through the atomic check code to calculate new watermark values in the
14739  * state object.
14740  */
14741 static void sanitize_watermarks(struct drm_device *dev)
14742 {
14743         struct drm_i915_private *dev_priv = to_i915(dev);
14744         struct drm_atomic_state *state;
14745         struct drm_crtc *crtc;
14746         struct drm_crtc_state *cstate;
14747         struct drm_modeset_acquire_ctx ctx;
14748         int ret;
14749         int i;
14750
14751         /* Only supported on platforms that use atomic watermark design */
14752         if (!dev_priv->display.optimize_watermarks)
14753                 return;
14754
14755         /*
14756          * We need to hold connection_mutex before calling duplicate_state so
14757          * that the connector loop is protected.
14758          */
14759         drm_modeset_acquire_init(&ctx, 0);
14760 retry:
14761         ret = drm_modeset_lock_all_ctx(dev, &ctx);
14762         if (ret == -EDEADLK) {
14763                 drm_modeset_backoff(&ctx);
14764                 goto retry;
14765         } else if (WARN_ON(ret)) {
14766                 goto fail;
14767         }
14768
14769         state = drm_atomic_helper_duplicate_state(dev, &ctx);
14770         if (WARN_ON(IS_ERR(state)))
14771                 goto fail;
14772
14773         /*
14774          * Hardware readout is the only time we don't want to calculate
14775          * intermediate watermarks (since we don't trust the current
14776          * watermarks).
14777          */
14778         to_intel_atomic_state(state)->skip_intermediate_wm = true;
14779
14780         ret = intel_atomic_check(dev, state);
14781         if (ret) {
14782                 /*
14783                  * If we fail here, it means that the hardware appears to be
14784                  * programmed in a way that shouldn't be possible, given our
14785                  * understanding of watermark requirements.  This might mean a
14786                  * mistake in the hardware readout code or a mistake in the
14787                  * watermark calculations for a given platform.  Raise a WARN
14788                  * so that this is noticeable.
14789                  *
14790                  * If this actually happens, we'll have to just leave the
14791                  * BIOS-programmed watermarks untouched and hope for the best.
14792                  */
14793                 WARN(true, "Could not determine valid watermarks for inherited state\n");
14794                 goto fail;
14795         }
14796
14797         /* Write calculated watermark values back */
14798         for_each_crtc_in_state(state, crtc, cstate, i) {
14799                 struct intel_crtc_state *cs = to_intel_crtc_state(cstate);
14800
14801                 cs->wm.need_postvbl_update = true;
14802                 dev_priv->display.optimize_watermarks(cs);
14803         }
14804
14805         drm_atomic_state_free(state);
14806 fail:
14807         drm_modeset_drop_locks(&ctx);
14808         drm_modeset_acquire_fini(&ctx);
14809 }
14810
14811 void intel_modeset_init(struct drm_device *dev)
14812 {
14813         struct drm_i915_private *dev_priv = to_i915(dev);
14814         struct i915_ggtt *ggtt = &dev_priv->ggtt;
14815         int sprite, ret;
14816         enum pipe pipe;
14817         struct intel_crtc *crtc;
14818
14819         drm_mode_config_init(dev);
14820
14821         dev->mode_config.min_width = 0;
14822         dev->mode_config.min_height = 0;
14823
14824         dev->mode_config.preferred_depth = 24;
14825         dev->mode_config.prefer_shadow = 1;
14826
14827         dev->mode_config.allow_fb_modifiers = true;
14828
14829         dev->mode_config.funcs = &intel_mode_funcs;
14830
14831         intel_init_quirks(dev);
14832
14833         intel_init_pm(dev);
14834
14835         if (INTEL_INFO(dev)->num_pipes == 0)
14836                 return;
14837
14838         /*
14839          * There may be no VBT; and if the BIOS enabled SSC we can
14840          * just keep using it to avoid unnecessary flicker.  Whereas if the
14841          * BIOS isn't using it, don't assume it will work even if the VBT
14842          * indicates as much.
14843          */
14844         if (HAS_PCH_IBX(dev) || HAS_PCH_CPT(dev)) {
14845                 bool bios_lvds_use_ssc = !!(I915_READ(PCH_DREF_CONTROL) &
14846                                             DREF_SSC1_ENABLE);
14847
14848                 if (dev_priv->vbt.lvds_use_ssc != bios_lvds_use_ssc) {
14849                         DRM_DEBUG_KMS("SSC %sabled by BIOS, overriding VBT which says %sabled\n",
14850                                      bios_lvds_use_ssc ? "en" : "dis",
14851                                      dev_priv->vbt.lvds_use_ssc ? "en" : "dis");
14852                         dev_priv->vbt.lvds_use_ssc = bios_lvds_use_ssc;
14853                 }
14854         }
14855
14856         if (IS_GEN2(dev)) {
14857                 dev->mode_config.max_width = 2048;
14858                 dev->mode_config.max_height = 2048;
14859         } else if (IS_GEN3(dev)) {
14860                 dev->mode_config.max_width = 4096;
14861                 dev->mode_config.max_height = 4096;
14862         } else {
14863                 dev->mode_config.max_width = 8192;
14864                 dev->mode_config.max_height = 8192;
14865         }
14866
14867         if (IS_845G(dev) || IS_I865G(dev)) {
14868                 dev->mode_config.cursor_width = IS_845G(dev) ? 64 : 512;
14869                 dev->mode_config.cursor_height = 1023;
14870         } else if (IS_GEN2(dev)) {
14871                 dev->mode_config.cursor_width = GEN2_CURSOR_WIDTH;
14872                 dev->mode_config.cursor_height = GEN2_CURSOR_HEIGHT;
14873         } else {
14874                 dev->mode_config.cursor_width = MAX_CURSOR_WIDTH;
14875                 dev->mode_config.cursor_height = MAX_CURSOR_HEIGHT;
14876         }
14877
14878         dev->mode_config.fb_base = ggtt->mappable_base;
14879
14880         DRM_DEBUG_KMS("%d display pipe%s available.\n",
14881                       INTEL_INFO(dev)->num_pipes,
14882                       INTEL_INFO(dev)->num_pipes > 1 ? "s" : "");
14883
14884         for_each_pipe(dev_priv, pipe) {
14885                 intel_crtc_init(dev, pipe);
14886                 for_each_sprite(dev_priv, pipe, sprite) {
14887                         ret = intel_plane_init(dev, pipe, sprite);
14888                         if (ret)
14889                                 DRM_DEBUG_KMS("pipe %c sprite %c init failed: %d\n",
14890                                               pipe_name(pipe), sprite_name(pipe, sprite), ret);
14891                 }
14892         }
14893
14894         intel_update_czclk(dev_priv);
14895         intel_update_cdclk(dev);
14896
14897         intel_shared_dpll_init(dev);
14898
14899         /* Just disable it once at startup */
14900         i915_disable_vga(dev);
14901         intel_setup_outputs(dev);
14902
14903         drm_modeset_lock_all(dev);
14904         intel_modeset_setup_hw_state(dev);
14905         drm_modeset_unlock_all(dev);
14906
14907         for_each_intel_crtc(dev, crtc) {
14908                 struct intel_initial_plane_config plane_config = {};
14909
14910                 if (!crtc->active)
14911                         continue;
14912
14913                 /*
14914                  * Note that reserving the BIOS fb up front prevents us
14915                  * from stuffing other stolen allocations like the ring
14916                  * on top.  This prevents some ugliness at boot time, and
14917                  * can even allow for smooth boot transitions if the BIOS
14918                  * fb is large enough for the active pipe configuration.
14919                  */
14920                 dev_priv->display.get_initial_plane_config(crtc,
14921                                                            &plane_config);
14922
14923                 /*
14924                  * If the fb is shared between multiple heads, we'll
14925                  * just get the first one.
14926                  */
14927                 intel_find_initial_plane_obj(crtc, &plane_config);
14928         }
14929
14930         /*
14931          * Make sure hardware watermarks really match the state we read out.
14932          * Note that we need to do this after reconstructing the BIOS fb's
14933          * since the watermark calculation done here will use pstate->fb.
14934          */
14935         sanitize_watermarks(dev);
14936 }
14937
14938 static void intel_enable_pipe_a(struct drm_device *dev)
14939 {
14940         struct intel_connector *connector;
14941         struct drm_connector *crt = NULL;
14942         struct intel_load_detect_pipe load_detect_temp;
14943         struct drm_modeset_acquire_ctx *ctx = dev->mode_config.acquire_ctx;
14944
14945         /* We can't just switch on the pipe A, we need to set things up with a
14946          * proper mode and output configuration. As a gross hack, enable pipe A
14947          * by enabling the load detect pipe once. */
14948         for_each_intel_connector(dev, connector) {
14949                 if (connector->encoder->type == INTEL_OUTPUT_ANALOG) {
14950                         crt = &connector->base;
14951                         break;
14952                 }
14953         }
14954
14955         if (!crt)
14956                 return;
14957
14958         if (intel_get_load_detect_pipe(crt, NULL, &load_detect_temp, ctx))
14959                 intel_release_load_detect_pipe(crt, &load_detect_temp, ctx);
14960 }
14961
14962 static bool
14963 intel_check_plane_mapping(struct intel_crtc *crtc)
14964 {
14965         struct drm_device *dev = crtc->base.dev;
14966         struct drm_i915_private *dev_priv = dev->dev_private;
14967         u32 val;
14968
14969         if (INTEL_INFO(dev)->num_pipes == 1)
14970                 return true;
14971
14972         val = I915_READ(DSPCNTR(!crtc->plane));
14973
14974         if ((val & DISPLAY_PLANE_ENABLE) &&
14975             (!!(val & DISPPLANE_SEL_PIPE_MASK) == crtc->pipe))
14976                 return false;
14977
14978         return true;
14979 }
14980
14981 static bool intel_crtc_has_encoders(struct intel_crtc *crtc)
14982 {
14983         struct drm_device *dev = crtc->base.dev;
14984         struct intel_encoder *encoder;
14985
14986         for_each_encoder_on_crtc(dev, &crtc->base, encoder)
14987                 return true;
14988
14989         return false;
14990 }
14991
14992 static bool intel_encoder_has_connectors(struct intel_encoder *encoder)
14993 {
14994         struct drm_device *dev = encoder->base.dev;
14995         struct intel_connector *connector;
14996
14997         for_each_connector_on_encoder(dev, &encoder->base, connector)
14998                 return true;
14999
15000         return false;
15001 }
15002
15003 static void intel_sanitize_crtc(struct intel_crtc *crtc)
15004 {
15005         struct drm_device *dev = crtc->base.dev;
15006         struct drm_i915_private *dev_priv = dev->dev_private;
15007         enum transcoder cpu_transcoder = crtc->config->cpu_transcoder;
15008
15009         /* Clear any frame start delays used for debugging left by the BIOS */
15010         if (!transcoder_is_dsi(cpu_transcoder)) {
15011                 i915_reg_t reg = PIPECONF(cpu_transcoder);
15012
15013                 I915_WRITE(reg,
15014                            I915_READ(reg) & ~PIPECONF_FRAME_START_DELAY_MASK);
15015         }
15016
15017         /* restore vblank interrupts to correct state */
15018         drm_crtc_vblank_reset(&crtc->base);
15019         if (crtc->active) {
15020                 struct intel_plane *plane;
15021
15022                 drm_crtc_vblank_on(&crtc->base);
15023
15024                 /* Disable everything but the primary plane */
15025                 for_each_intel_plane_on_crtc(dev, crtc, plane) {
15026                         if (plane->base.type == DRM_PLANE_TYPE_PRIMARY)
15027                                 continue;
15028
15029                         plane->disable_plane(&plane->base, &crtc->base);
15030                 }
15031         }
15032
15033         /* We need to sanitize the plane -> pipe mapping first because this will
15034          * disable the crtc (and hence change the state) if it is wrong. Note
15035          * that gen4+ has a fixed plane -> pipe mapping.  */
15036         if (INTEL_INFO(dev)->gen < 4 && !intel_check_plane_mapping(crtc)) {
15037                 bool plane;
15038
15039                 DRM_DEBUG_KMS("[CRTC:%d] wrong plane connection detected!\n",
15040                               crtc->base.base.id);
15041
15042                 /* Pipe has the wrong plane attached and the plane is active.
15043                  * Temporarily change the plane mapping and disable everything
15044                  * ...  */
15045                 plane = crtc->plane;
15046                 to_intel_plane_state(crtc->base.primary->state)->visible = true;
15047                 crtc->plane = !plane;
15048                 intel_crtc_disable_noatomic(&crtc->base);
15049                 crtc->plane = plane;
15050         }
15051
15052         if (dev_priv->quirks & QUIRK_PIPEA_FORCE &&
15053             crtc->pipe == PIPE_A && !crtc->active) {
15054                 /* BIOS forgot to enable pipe A, this mostly happens after
15055                  * resume. Force-enable the pipe to fix this, the update_dpms
15056                  * call below we restore the pipe to the right state, but leave
15057                  * the required bits on. */
15058                 intel_enable_pipe_a(dev);
15059         }
15060
15061         /* Adjust the state of the output pipe according to whether we
15062          * have active connectors/encoders. */
15063         if (crtc->active && !intel_crtc_has_encoders(crtc))
15064                 intel_crtc_disable_noatomic(&crtc->base);
15065
15066         if (crtc->active || HAS_GMCH_DISPLAY(dev)) {
15067                 /*
15068                  * We start out with underrun reporting disabled to avoid races.
15069                  * For correct bookkeeping mark this on active crtcs.
15070                  *
15071                  * Also on gmch platforms we dont have any hardware bits to
15072                  * disable the underrun reporting. Which means we need to start
15073                  * out with underrun reporting disabled also on inactive pipes,
15074                  * since otherwise we'll complain about the garbage we read when
15075                  * e.g. coming up after runtime pm.
15076                  *
15077                  * No protection against concurrent access is required - at
15078                  * worst a fifo underrun happens which also sets this to false.
15079                  */
15080                 crtc->cpu_fifo_underrun_disabled = true;
15081                 crtc->pch_fifo_underrun_disabled = true;
15082         }
15083 }
15084
15085 static void intel_sanitize_encoder(struct intel_encoder *encoder)
15086 {
15087         struct intel_connector *connector;
15088         struct drm_device *dev = encoder->base.dev;
15089
15090         /* We need to check both for a crtc link (meaning that the
15091          * encoder is active and trying to read from a pipe) and the
15092          * pipe itself being active. */
15093         bool has_active_crtc = encoder->base.crtc &&
15094                 to_intel_crtc(encoder->base.crtc)->active;
15095
15096         if (intel_encoder_has_connectors(encoder) && !has_active_crtc) {
15097                 DRM_DEBUG_KMS("[ENCODER:%d:%s] has active connectors but no active pipe!\n",
15098                               encoder->base.base.id,
15099                               encoder->base.name);
15100
15101                 /* Connector is active, but has no active pipe. This is
15102                  * fallout from our resume register restoring. Disable
15103                  * the encoder manually again. */
15104                 if (encoder->base.crtc) {
15105                         DRM_DEBUG_KMS("[ENCODER:%d:%s] manually disabled\n",
15106                                       encoder->base.base.id,
15107                                       encoder->base.name);
15108                         encoder->disable(encoder);
15109                         if (encoder->post_disable)
15110                                 encoder->post_disable(encoder);
15111                 }
15112                 encoder->base.crtc = NULL;
15113
15114                 /* Inconsistent output/port/pipe state happens presumably due to
15115                  * a bug in one of the get_hw_state functions. Or someplace else
15116                  * in our code, like the register restore mess on resume. Clamp
15117                  * things to off as a safer default. */
15118                 for_each_intel_connector(dev, connector) {
15119                         if (connector->encoder != encoder)
15120                                 continue;
15121                         connector->base.dpms = DRM_MODE_DPMS_OFF;
15122                         connector->base.encoder = NULL;
15123                 }
15124         }
15125         /* Enabled encoders without active connectors will be fixed in
15126          * the crtc fixup. */
15127 }
15128
15129 void i915_redisable_vga_power_on(struct drm_device *dev)
15130 {
15131         struct drm_i915_private *dev_priv = dev->dev_private;
15132         i915_reg_t vga_reg = i915_vgacntrl_reg(dev);
15133
15134         if (!(I915_READ(vga_reg) & VGA_DISP_DISABLE)) {
15135                 DRM_DEBUG_KMS("Something enabled VGA plane, disabling it\n");
15136                 i915_disable_vga(dev);
15137         }
15138 }
15139
15140 void i915_redisable_vga(struct drm_device *dev)
15141 {
15142         struct drm_i915_private *dev_priv = dev->dev_private;
15143
15144         /* This function can be called both from intel_modeset_setup_hw_state or
15145          * at a very early point in our resume sequence, where the power well
15146          * structures are not yet restored. Since this function is at a very
15147          * paranoid "someone might have enabled VGA while we were not looking"
15148          * level, just check if the power well is enabled instead of trying to
15149          * follow the "don't touch the power well if we don't need it" policy
15150          * the rest of the driver uses. */
15151         if (!intel_display_power_get_if_enabled(dev_priv, POWER_DOMAIN_VGA))
15152                 return;
15153
15154         i915_redisable_vga_power_on(dev);
15155
15156         intel_display_power_put(dev_priv, POWER_DOMAIN_VGA);
15157 }
15158
15159 static bool primary_get_hw_state(struct intel_plane *plane)
15160 {
15161         struct drm_i915_private *dev_priv = to_i915(plane->base.dev);
15162
15163         return I915_READ(DSPCNTR(plane->plane)) & DISPLAY_PLANE_ENABLE;
15164 }
15165
15166 /* FIXME read out full plane state for all planes */
15167 static void readout_plane_state(struct intel_crtc *crtc)
15168 {
15169         struct drm_plane *primary = crtc->base.primary;
15170         struct intel_plane_state *plane_state =
15171                 to_intel_plane_state(primary->state);
15172
15173         plane_state->visible = crtc->active &&
15174                 primary_get_hw_state(to_intel_plane(primary));
15175
15176         if (plane_state->visible)
15177                 crtc->base.state->plane_mask |= 1 << drm_plane_index(primary);
15178 }
15179
15180 static void intel_modeset_readout_hw_state(struct drm_device *dev)
15181 {
15182         struct drm_i915_private *dev_priv = dev->dev_private;
15183         enum pipe pipe;
15184         struct intel_crtc *crtc;
15185         struct intel_encoder *encoder;
15186         struct intel_connector *connector;
15187         int i;
15188
15189         dev_priv->active_crtcs = 0;
15190
15191         for_each_intel_crtc(dev, crtc) {
15192                 struct intel_crtc_state *crtc_state = crtc->config;
15193                 int pixclk = 0;
15194
15195                 __drm_atomic_helper_crtc_destroy_state(&crtc->base, &crtc_state->base);
15196                 memset(crtc_state, 0, sizeof(*crtc_state));
15197                 crtc_state->base.crtc = &crtc->base;
15198
15199                 crtc_state->base.active = crtc_state->base.enable =
15200                         dev_priv->display.get_pipe_config(crtc, crtc_state);
15201
15202                 crtc->base.enabled = crtc_state->base.enable;
15203                 crtc->active = crtc_state->base.active;
15204
15205                 if (crtc_state->base.active) {
15206                         dev_priv->active_crtcs |= 1 << crtc->pipe;
15207
15208                         if (INTEL_GEN(dev_priv) >= 9 || IS_BROADWELL(dev_priv))
15209                                 pixclk = ilk_pipe_pixel_rate(crtc_state);
15210                         else if (IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv))
15211                                 pixclk = crtc_state->base.adjusted_mode.crtc_clock;
15212                         else
15213                                 WARN_ON(dev_priv->display.modeset_calc_cdclk);
15214
15215                         /* pixel rate mustn't exceed 95% of cdclk with IPS on BDW */
15216                         if (IS_BROADWELL(dev_priv) && crtc_state->ips_enabled)
15217                                 pixclk = DIV_ROUND_UP(pixclk * 100, 95);
15218                 }
15219
15220                 dev_priv->min_pixclk[crtc->pipe] = pixclk;
15221
15222                 readout_plane_state(crtc);
15223
15224                 DRM_DEBUG_KMS("[CRTC:%d] hw state readout: %s\n",
15225                               crtc->base.base.id,
15226                               crtc->active ? "enabled" : "disabled");
15227         }
15228
15229         for (i = 0; i < dev_priv->num_shared_dpll; i++) {
15230                 struct intel_shared_dpll *pll = &dev_priv->shared_dplls[i];
15231
15232                 pll->on = pll->funcs.get_hw_state(dev_priv, pll,
15233                                                   &pll->config.hw_state);
15234                 pll->config.crtc_mask = 0;
15235                 for_each_intel_crtc(dev, crtc) {
15236                         if (crtc->active && crtc->config->shared_dpll == pll)
15237                                 pll->config.crtc_mask |= 1 << crtc->pipe;
15238                 }
15239                 pll->active_mask = pll->config.crtc_mask;
15240
15241                 DRM_DEBUG_KMS("%s hw state readout: crtc_mask 0x%08x, on %i\n",
15242                               pll->name, pll->config.crtc_mask, pll->on);
15243         }
15244
15245         for_each_intel_encoder(dev, encoder) {
15246                 pipe = 0;
15247
15248                 if (encoder->get_hw_state(encoder, &pipe)) {
15249                         crtc = to_intel_crtc(dev_priv->pipe_to_crtc_mapping[pipe]);
15250                         encoder->base.crtc = &crtc->base;
15251                         encoder->get_config(encoder, crtc->config);
15252                 } else {
15253                         encoder->base.crtc = NULL;
15254                 }
15255
15256                 DRM_DEBUG_KMS("[ENCODER:%d:%s] hw state readout: %s, pipe %c\n",
15257                               encoder->base.base.id,
15258                               encoder->base.name,
15259                               encoder->base.crtc ? "enabled" : "disabled",
15260                               pipe_name(pipe));
15261         }
15262
15263         for_each_intel_connector(dev, connector) {
15264                 if (connector->get_hw_state(connector)) {
15265                         connector->base.dpms = DRM_MODE_DPMS_ON;
15266
15267                         encoder = connector->encoder;
15268                         connector->base.encoder = &encoder->base;
15269
15270                         if (encoder->base.crtc &&
15271                             encoder->base.crtc->state->active) {
15272                                 /*
15273                                  * This has to be done during hardware readout
15274                                  * because anything calling .crtc_disable may
15275                                  * rely on the connector_mask being accurate.
15276                                  */
15277                                 encoder->base.crtc->state->connector_mask |=
15278                                         1 << drm_connector_index(&connector->base);
15279                                 encoder->base.crtc->state->encoder_mask |=
15280                                         1 << drm_encoder_index(&encoder->base);
15281                         }
15282
15283                 } else {
15284                         connector->base.dpms = DRM_MODE_DPMS_OFF;
15285                         connector->base.encoder = NULL;
15286                 }
15287                 DRM_DEBUG_KMS("[CONNECTOR:%d:%s] hw state readout: %s\n",
15288                               connector->base.base.id,
15289                               connector->base.name,
15290                               connector->base.encoder ? "enabled" : "disabled");
15291         }
15292
15293         for_each_intel_crtc(dev, crtc) {
15294                 crtc->base.hwmode = crtc->config->base.adjusted_mode;
15295
15296                 memset(&crtc->base.mode, 0, sizeof(crtc->base.mode));
15297                 if (crtc->base.state->active) {
15298                         intel_mode_from_pipe_config(&crtc->base.mode, crtc->config);
15299                         intel_mode_from_pipe_config(&crtc->base.state->adjusted_mode, crtc->config);
15300                         WARN_ON(drm_atomic_set_mode_for_crtc(crtc->base.state, &crtc->base.mode));
15301
15302                         /*
15303                          * The initial mode needs to be set in order to keep
15304                          * the atomic core happy. It wants a valid mode if the
15305                          * crtc's enabled, so we do the above call.
15306                          *
15307                          * At this point some state updated by the connectors
15308                          * in their ->detect() callback has not run yet, so
15309                          * no recalculation can be done yet.
15310                          *
15311                          * Even if we could do a recalculation and modeset
15312                          * right now it would cause a double modeset if
15313                          * fbdev or userspace chooses a different initial mode.
15314                          *
15315                          * If that happens, someone indicated they wanted a
15316                          * mode change, which means it's safe to do a full
15317                          * recalculation.
15318                          */
15319                         crtc->base.state->mode.private_flags = I915_MODE_FLAG_INHERITED;
15320
15321                         drm_calc_timestamping_constants(&crtc->base, &crtc->base.hwmode);
15322                         update_scanline_offset(crtc);
15323                 }
15324
15325                 intel_pipe_config_sanity_check(dev_priv, crtc->config);
15326         }
15327 }
15328
15329 /* Scan out the current hw modeset state,
15330  * and sanitizes it to the current state
15331  */
15332 static void
15333 intel_modeset_setup_hw_state(struct drm_device *dev)
15334 {
15335         struct drm_i915_private *dev_priv = dev->dev_private;
15336         enum pipe pipe;
15337         struct intel_crtc *crtc;
15338         struct intel_encoder *encoder;
15339         int i;
15340
15341         intel_modeset_readout_hw_state(dev);
15342
15343         /* HW state is read out, now we need to sanitize this mess. */
15344         for_each_intel_encoder(dev, encoder) {
15345                 intel_sanitize_encoder(encoder);
15346         }
15347
15348         for_each_pipe(dev_priv, pipe) {
15349                 crtc = to_intel_crtc(dev_priv->pipe_to_crtc_mapping[pipe]);
15350                 intel_sanitize_crtc(crtc);
15351                 intel_dump_pipe_config(crtc, crtc->config,
15352                                        "[setup_hw_state]");
15353         }
15354
15355         intel_modeset_update_connector_atomic_state(dev);
15356
15357         for (i = 0; i < dev_priv->num_shared_dpll; i++) {
15358                 struct intel_shared_dpll *pll = &dev_priv->shared_dplls[i];
15359
15360                 if (!pll->on || pll->active_mask)
15361                         continue;
15362
15363                 DRM_DEBUG_KMS("%s enabled but not in use, disabling\n", pll->name);
15364
15365                 pll->funcs.disable(dev_priv, pll);
15366                 pll->on = false;
15367         }
15368
15369         if (IS_VALLEYVIEW(dev) || IS_CHERRYVIEW(dev))
15370                 vlv_wm_get_hw_state(dev);
15371         else if (IS_GEN9(dev))
15372                 skl_wm_get_hw_state(dev);
15373         else if (HAS_PCH_SPLIT(dev))
15374                 ilk_wm_get_hw_state(dev);
15375
15376         for_each_intel_crtc(dev, crtc) {
15377                 unsigned long put_domains;
15378
15379                 put_domains = modeset_get_crtc_power_domains(&crtc->base, crtc->config);
15380                 if (WARN_ON(put_domains))
15381                         modeset_put_power_domains(dev_priv, put_domains);
15382         }
15383         intel_display_set_init_power(dev_priv, false);
15384
15385         intel_fbc_init_pipe_state(dev_priv);
15386 }
15387
15388 void intel_display_resume(struct drm_device *dev)
15389 {
15390         struct drm_i915_private *dev_priv = to_i915(dev);
15391         struct drm_atomic_state *state = dev_priv->modeset_restore_state;
15392         struct drm_modeset_acquire_ctx ctx;
15393         int ret;
15394         bool setup = false;
15395
15396         dev_priv->modeset_restore_state = NULL;
15397
15398         /*
15399          * This is a cludge because with real atomic modeset mode_config.mutex
15400          * won't be taken. Unfortunately some probed state like
15401          * audio_codec_enable is still protected by mode_config.mutex, so lock
15402          * it here for now.
15403          */
15404         mutex_lock(&dev->mode_config.mutex);
15405         drm_modeset_acquire_init(&ctx, 0);
15406
15407 retry:
15408         ret = drm_modeset_lock_all_ctx(dev, &ctx);
15409
15410         if (ret == 0 && !setup) {
15411                 setup = true;
15412
15413                 intel_modeset_setup_hw_state(dev);
15414                 i915_redisable_vga(dev);
15415         }
15416
15417         if (ret == 0 && state) {
15418                 struct drm_crtc_state *crtc_state;
15419                 struct drm_crtc *crtc;
15420                 int i;
15421
15422                 state->acquire_ctx = &ctx;
15423
15424                 /* ignore any reset values/BIOS leftovers in the WM registers */
15425                 to_intel_atomic_state(state)->skip_intermediate_wm = true;
15426
15427                 for_each_crtc_in_state(state, crtc, crtc_state, i) {
15428                         /*
15429                          * Force recalculation even if we restore
15430                          * current state. With fast modeset this may not result
15431                          * in a modeset when the state is compatible.
15432                          */
15433                         crtc_state->mode_changed = true;
15434                 }
15435
15436                 ret = drm_atomic_commit(state);
15437         }
15438
15439         if (ret == -EDEADLK) {
15440                 drm_modeset_backoff(&ctx);
15441                 goto retry;
15442         }
15443
15444         drm_modeset_drop_locks(&ctx);
15445         drm_modeset_acquire_fini(&ctx);
15446         mutex_unlock(&dev->mode_config.mutex);
15447
15448         if (ret) {
15449                 DRM_ERROR("Restoring old state failed with %i\n", ret);
15450                 drm_atomic_state_free(state);
15451         }
15452 }
15453
15454 void intel_modeset_gem_init(struct drm_device *dev)
15455 {
15456         struct drm_i915_private *dev_priv = to_i915(dev);
15457         struct drm_crtc *c;
15458         struct drm_i915_gem_object *obj;
15459         int ret;
15460
15461         intel_init_gt_powersave(dev_priv);
15462
15463         intel_modeset_init_hw(dev);
15464
15465         intel_setup_overlay(dev_priv);
15466
15467         /*
15468          * Make sure any fbs we allocated at startup are properly
15469          * pinned & fenced.  When we do the allocation it's too early
15470          * for this.
15471          */
15472         for_each_crtc(dev, c) {
15473                 obj = intel_fb_obj(c->primary->fb);
15474                 if (obj == NULL)
15475                         continue;
15476
15477                 mutex_lock(&dev->struct_mutex);
15478                 ret = intel_pin_and_fence_fb_obj(c->primary->fb,
15479                                                  c->primary->state->rotation);
15480                 mutex_unlock(&dev->struct_mutex);
15481                 if (ret) {
15482                         DRM_ERROR("failed to pin boot fb on pipe %d\n",
15483                                   to_intel_crtc(c)->pipe);
15484                         drm_framebuffer_unreference(c->primary->fb);
15485                         drm_framebuffer_unreference(c->primary->state->fb);
15486                         c->primary->fb = c->primary->state->fb = NULL;
15487                         c->primary->crtc = c->primary->state->crtc = NULL;
15488                         c->state->plane_mask &= ~(1 << drm_plane_index(c->primary));
15489                 }
15490         }
15491
15492         intel_backlight_register(dev);
15493 }
15494
15495 void intel_connector_unregister(struct intel_connector *intel_connector)
15496 {
15497         struct drm_connector *connector = &intel_connector->base;
15498
15499         intel_panel_destroy_backlight(connector);
15500         drm_connector_unregister(connector);
15501 }
15502
15503 void intel_modeset_cleanup(struct drm_device *dev)
15504 {
15505         struct drm_i915_private *dev_priv = dev->dev_private;
15506         struct intel_connector *connector;
15507
15508         intel_disable_gt_powersave(dev_priv);
15509
15510         intel_backlight_unregister(dev);
15511
15512         /*
15513          * Interrupts and polling as the first thing to avoid creating havoc.
15514          * Too much stuff here (turning of connectors, ...) would
15515          * experience fancy races otherwise.
15516          */
15517         intel_irq_uninstall(dev_priv);
15518
15519         /*
15520          * Due to the hpd irq storm handling the hotplug work can re-arm the
15521          * poll handlers. Hence disable polling after hpd handling is shut down.
15522          */
15523         drm_kms_helper_poll_fini(dev);
15524
15525         intel_unregister_dsm_handler();
15526
15527         intel_fbc_global_disable(dev_priv);
15528
15529         /* flush any delayed tasks or pending work */
15530         flush_scheduled_work();
15531
15532         /* destroy the backlight and sysfs files before encoders/connectors */
15533         for_each_intel_connector(dev, connector)
15534                 connector->unregister(connector);
15535
15536         drm_mode_config_cleanup(dev);
15537
15538         intel_cleanup_overlay(dev_priv);
15539
15540         intel_cleanup_gt_powersave(dev_priv);
15541
15542         intel_teardown_gmbus(dev);
15543 }
15544
15545 /*
15546  * Return which encoder is currently attached for connector.
15547  */
15548 struct drm_encoder *intel_best_encoder(struct drm_connector *connector)
15549 {
15550         return &intel_attached_encoder(connector)->base;
15551 }
15552
15553 void intel_connector_attach_encoder(struct intel_connector *connector,
15554                                     struct intel_encoder *encoder)
15555 {
15556         connector->encoder = encoder;
15557         drm_mode_connector_attach_encoder(&connector->base,
15558                                           &encoder->base);
15559 }
15560
15561 /*
15562  * set vga decode state - true == enable VGA decode
15563  */
15564 int intel_modeset_vga_set_state(struct drm_device *dev, bool state)
15565 {
15566         struct drm_i915_private *dev_priv = dev->dev_private;
15567         unsigned reg = INTEL_INFO(dev)->gen >= 6 ? SNB_GMCH_CTRL : INTEL_GMCH_CTRL;
15568         u16 gmch_ctrl;
15569
15570         if (pci_read_config_word(dev_priv->bridge_dev, reg, &gmch_ctrl)) {
15571                 DRM_ERROR("failed to read control word\n");
15572                 return -EIO;
15573         }
15574
15575         if (!!(gmch_ctrl & INTEL_GMCH_VGA_DISABLE) == !state)
15576                 return 0;
15577
15578         if (state)
15579                 gmch_ctrl &= ~INTEL_GMCH_VGA_DISABLE;
15580         else
15581                 gmch_ctrl |= INTEL_GMCH_VGA_DISABLE;
15582
15583         if (pci_write_config_word(dev_priv->bridge_dev, reg, gmch_ctrl)) {
15584                 DRM_ERROR("failed to write control word\n");
15585                 return -EIO;
15586         }
15587
15588         return 0;
15589 }
15590
15591 struct intel_display_error_state {
15592
15593         u32 power_well_driver;
15594
15595         int num_transcoders;
15596
15597         struct intel_cursor_error_state {
15598                 u32 control;
15599                 u32 position;
15600                 u32 base;
15601                 u32 size;
15602         } cursor[I915_MAX_PIPES];
15603
15604         struct intel_pipe_error_state {
15605                 bool power_domain_on;
15606                 u32 source;
15607                 u32 stat;
15608         } pipe[I915_MAX_PIPES];
15609
15610         struct intel_plane_error_state {
15611                 u32 control;
15612                 u32 stride;
15613                 u32 size;
15614                 u32 pos;
15615                 u32 addr;
15616                 u32 surface;
15617                 u32 tile_offset;
15618         } plane[I915_MAX_PIPES];
15619
15620         struct intel_transcoder_error_state {
15621                 bool power_domain_on;
15622                 enum transcoder cpu_transcoder;
15623
15624                 u32 conf;
15625
15626                 u32 htotal;
15627                 u32 hblank;
15628                 u32 hsync;
15629                 u32 vtotal;
15630                 u32 vblank;
15631                 u32 vsync;
15632         } transcoder[4];
15633 };
15634
15635 struct intel_display_error_state *
15636 intel_display_capture_error_state(struct drm_i915_private *dev_priv)
15637 {
15638         struct intel_display_error_state *error;
15639         int transcoders[] = {
15640                 TRANSCODER_A,
15641                 TRANSCODER_B,
15642                 TRANSCODER_C,
15643                 TRANSCODER_EDP,
15644         };
15645         int i;
15646
15647         if (INTEL_INFO(dev_priv)->num_pipes == 0)
15648                 return NULL;
15649
15650         error = kzalloc(sizeof(*error), GFP_ATOMIC);
15651         if (error == NULL)
15652                 return NULL;
15653
15654         if (IS_HASWELL(dev_priv) || IS_BROADWELL(dev_priv))
15655                 error->power_well_driver = I915_READ(HSW_PWR_WELL_DRIVER);
15656
15657         for_each_pipe(dev_priv, i) {
15658                 error->pipe[i].power_domain_on =
15659                         __intel_display_power_is_enabled(dev_priv,
15660                                                          POWER_DOMAIN_PIPE(i));
15661                 if (!error->pipe[i].power_domain_on)
15662                         continue;
15663
15664                 error->cursor[i].control = I915_READ(CURCNTR(i));
15665                 error->cursor[i].position = I915_READ(CURPOS(i));
15666                 error->cursor[i].base = I915_READ(CURBASE(i));
15667
15668                 error->plane[i].control = I915_READ(DSPCNTR(i));
15669                 error->plane[i].stride = I915_READ(DSPSTRIDE(i));
15670                 if (INTEL_GEN(dev_priv) <= 3) {
15671                         error->plane[i].size = I915_READ(DSPSIZE(i));
15672                         error->plane[i].pos = I915_READ(DSPPOS(i));
15673                 }
15674                 if (INTEL_GEN(dev_priv) <= 7 && !IS_HASWELL(dev_priv))
15675                         error->plane[i].addr = I915_READ(DSPADDR(i));
15676                 if (INTEL_GEN(dev_priv) >= 4) {
15677                         error->plane[i].surface = I915_READ(DSPSURF(i));
15678                         error->plane[i].tile_offset = I915_READ(DSPTILEOFF(i));
15679                 }
15680
15681                 error->pipe[i].source = I915_READ(PIPESRC(i));
15682
15683                 if (HAS_GMCH_DISPLAY(dev_priv))
15684                         error->pipe[i].stat = I915_READ(PIPESTAT(i));
15685         }
15686
15687         /* Note: this does not include DSI transcoders. */
15688         error->num_transcoders = INTEL_INFO(dev_priv)->num_pipes;
15689         if (HAS_DDI(dev_priv))
15690                 error->num_transcoders++; /* Account for eDP. */
15691
15692         for (i = 0; i < error->num_transcoders; i++) {
15693                 enum transcoder cpu_transcoder = transcoders[i];
15694
15695                 error->transcoder[i].power_domain_on =
15696                         __intel_display_power_is_enabled(dev_priv,
15697                                 POWER_DOMAIN_TRANSCODER(cpu_transcoder));
15698                 if (!error->transcoder[i].power_domain_on)
15699                         continue;
15700
15701                 error->transcoder[i].cpu_transcoder = cpu_transcoder;
15702
15703                 error->transcoder[i].conf = I915_READ(PIPECONF(cpu_transcoder));
15704                 error->transcoder[i].htotal = I915_READ(HTOTAL(cpu_transcoder));
15705                 error->transcoder[i].hblank = I915_READ(HBLANK(cpu_transcoder));
15706                 error->transcoder[i].hsync = I915_READ(HSYNC(cpu_transcoder));
15707                 error->transcoder[i].vtotal = I915_READ(VTOTAL(cpu_transcoder));
15708                 error->transcoder[i].vblank = I915_READ(VBLANK(cpu_transcoder));
15709                 error->transcoder[i].vsync = I915_READ(VSYNC(cpu_transcoder));
15710         }
15711
15712         return error;
15713 }
15714
15715 #define err_printf(e, ...) i915_error_printf(e, __VA_ARGS__)
15716
15717 void
15718 intel_display_print_error_state(struct drm_i915_error_state_buf *m,
15719                                 struct drm_device *dev,
15720                                 struct intel_display_error_state *error)
15721 {
15722         struct drm_i915_private *dev_priv = dev->dev_private;
15723         int i;
15724
15725         if (!error)
15726                 return;
15727
15728         err_printf(m, "Num Pipes: %d\n", INTEL_INFO(dev)->num_pipes);
15729         if (IS_HASWELL(dev) || IS_BROADWELL(dev))
15730                 err_printf(m, "PWR_WELL_CTL2: %08x\n",
15731                            error->power_well_driver);
15732         for_each_pipe(dev_priv, i) {
15733                 err_printf(m, "Pipe [%d]:\n", i);
15734                 err_printf(m, "  Power: %s\n",
15735                            onoff(error->pipe[i].power_domain_on));
15736                 err_printf(m, "  SRC: %08x\n", error->pipe[i].source);
15737                 err_printf(m, "  STAT: %08x\n", error->pipe[i].stat);
15738
15739                 err_printf(m, "Plane [%d]:\n", i);
15740                 err_printf(m, "  CNTR: %08x\n", error->plane[i].control);
15741                 err_printf(m, "  STRIDE: %08x\n", error->plane[i].stride);
15742                 if (INTEL_INFO(dev)->gen <= 3) {
15743                         err_printf(m, "  SIZE: %08x\n", error->plane[i].size);
15744                         err_printf(m, "  POS: %08x\n", error->plane[i].pos);
15745                 }
15746                 if (INTEL_INFO(dev)->gen <= 7 && !IS_HASWELL(dev))
15747                         err_printf(m, "  ADDR: %08x\n", error->plane[i].addr);
15748                 if (INTEL_INFO(dev)->gen >= 4) {
15749                         err_printf(m, "  SURF: %08x\n", error->plane[i].surface);
15750                         err_printf(m, "  TILEOFF: %08x\n", error->plane[i].tile_offset);
15751                 }
15752
15753                 err_printf(m, "Cursor [%d]:\n", i);
15754                 err_printf(m, "  CNTR: %08x\n", error->cursor[i].control);
15755                 err_printf(m, "  POS: %08x\n", error->cursor[i].position);
15756                 err_printf(m, "  BASE: %08x\n", error->cursor[i].base);
15757         }
15758
15759         for (i = 0; i < error->num_transcoders; i++) {
15760                 err_printf(m, "CPU transcoder: %s\n",
15761                            transcoder_name(error->transcoder[i].cpu_transcoder));
15762                 err_printf(m, "  Power: %s\n",
15763                            onoff(error->transcoder[i].power_domain_on));
15764                 err_printf(m, "  CONF: %08x\n", error->transcoder[i].conf);
15765                 err_printf(m, "  HTOTAL: %08x\n", error->transcoder[i].htotal);
15766                 err_printf(m, "  HBLANK: %08x\n", error->transcoder[i].hblank);
15767                 err_printf(m, "  HSYNC: %08x\n", error->transcoder[i].hsync);
15768                 err_printf(m, "  VTOTAL: %08x\n", error->transcoder[i].vtotal);
15769                 err_printf(m, "  VBLANK: %08x\n", error->transcoder[i].vblank);
15770                 err_printf(m, "  VSYNC: %08x\n", error->transcoder[i].vsync);
15771         }
15772 }